1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
21#include "clang/Basic/CLWarnings.h"
22#include "clang/Basic/CodeGenOptions.h"
23#include "clang/Basic/HeaderInclude.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/MakeSupport.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
30#include "clang/Driver/CommonArgs.h"
31#include "clang/Driver/Distro.h"
32#include "clang/Driver/InputInfo.h"
33#include "clang/Driver/SanitizerArgs.h"
34#include "clang/Driver/Types.h"
35#include "clang/Driver/XRayArgs.h"
36#include "clang/Options/OptionUtils.h"
37#include "clang/Options/Options.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/BinaryFormat/Magic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Frontend/Debug/Options.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Option/ArgList.h"
46#include "llvm/ProfileData/InstrProfReader.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/Process.h"
54#include "llvm/Support/YAMLParser.h"
55#include "llvm/TargetParser/AArch64TargetParser.h"
56#include "llvm/TargetParser/ARMTargetParserCommon.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/LoongArchTargetParser.h"
59#include "llvm/TargetParser/PPCTargetParser.h"
60#include "llvm/TargetParser/RISCVISAInfo.h"
61#include "llvm/TargetParser/RISCVTargetParser.h"
62#include <cctype>
63#include <iterator>
64
65using namespace clang::driver;
66using namespace clang::driver::tools;
67using namespace clang;
68using namespace llvm::opt;
69
70static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
72 Ids: options::OPT_fminimize_whitespace,
73 Ids: options::OPT_fno_minimize_whitespace,
74 Ids: options::OPT_fkeep_system_includes,
75 Ids: options::OPT_fno_keep_system_includes)) {
76 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
77 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
79 << A->getBaseArg().getAsString(Args)
80 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81 }
82 }
83}
84
85static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
86 // In gcc, only ARM checks this, but it seems reasonable to check universally.
87 if (Args.hasArg(Ids: options::OPT_static))
88 if (const Arg *A =
89 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
90 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
91 << "-static";
92}
93
94/// Apply \a Work on the current tool chain \a RegularToolChain and any other
95/// offloading tool chain that is associated with the current action \a JA.
96static void
97forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
98 const ToolChain &RegularToolChain,
99 llvm::function_ref<void(const ToolChain &)> Work) {
100 // Apply Work on the current/regular tool chain.
101 Work(RegularToolChain);
102
103 // Apply Work on all the offloading tool chains associated with the current
104 // action.
105 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
106 Action::OFK_HIP, Action::OFK_SYCL}) {
107 if (JA.isHostOffloading(OKind: Kind)) {
108 auto TCs = C.getOffloadToolChains(Kind);
109 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
110 Work(*II->second);
111 } else if (JA.isDeviceOffloading(OKind: Kind))
112 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
113 }
114}
115
116static bool
117shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
118 const llvm::Triple &Triple) {
119 // We use the zero-cost exception tables for Objective-C if the non-fragile
120 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
121 // later.
122 if (runtime.isNonFragile())
123 return true;
124
125 if (!Triple.isMacOSX())
126 return false;
127
128 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
129 (Triple.getArch() == llvm::Triple::x86_64 ||
130 Triple.getArch() == llvm::Triple::arm));
131}
132
133/// Adds exception related arguments to the driver command arguments. There's a
134/// main flag, -fexceptions and also language specific flags to enable/disable
135/// C++ and Objective-C exceptions. This makes it possible to for example
136/// disable C++ exceptions but enable Objective-C exceptions.
137static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
138 const ToolChain &TC, bool KernelOrKext,
139 bool IsDeviceOffloadAction,
140 const ObjCRuntime &objcRuntime,
141 ArgStringList &CmdArgs) {
142 const llvm::Triple &Triple = TC.getTriple();
143
144 if (KernelOrKext) {
145 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
146 // arguments now to avoid warnings about unused arguments.
147 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
154 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
155 return false;
156 }
157
158 // See if the user explicitly enabled exceptions.
159 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
160 Default: false);
161
162 // Async exceptions are Windows MSVC only.
163 if (Triple.isWindowsMSVCEnvironment()) {
164 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
165 Neg: options::OPT_fno_async_exceptions, Default: false);
166 if (EHa) {
167 CmdArgs.push_back(Elt: "-fasync-exceptions");
168 EH = true;
169 }
170 }
171
172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
173 // is not necessarily sensible, but follows GCC.
174 if (types::isObjC(Id: InputType) &&
175 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
176 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
177 CmdArgs.push_back(Elt: "-fobjc-exceptions");
178
179 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
180 }
181
182 if (types::isCXX(Id: InputType)) {
183 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
184 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
185 !Triple.isPS() && !Triple.isDriverKit() &&
186 !(Triple.isGPU() && !IsDeviceOffloadAction);
187 Arg *ExceptionArg = Args.getLastArg(
188 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
189 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
190 if (ExceptionArg)
191 CXXExceptionsEnabled =
192 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
193 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
194
195 if (CXXExceptionsEnabled) {
196 CmdArgs.push_back(Elt: "-fcxx-exceptions");
197
198 EH = true;
199 }
200 }
201
202 // OPT_fignore_exceptions means exception could still be thrown,
203 // but no clean up or catch would happen in current module.
204 // So we do not set EH to false.
205 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
206
207 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
208 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
209
210 if (EH)
211 CmdArgs.push_back(Elt: "-fexceptions");
212 return EH;
213}
214
215static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
216 const JobAction &JA) {
217 bool Default = true;
218 if (TC.getTriple().isOSDarwin()) {
219 // The native darwin assembler doesn't support the linker_option directives,
220 // so we disable them if we think the .s file will be passed to it.
221 Default = TC.useIntegratedAs();
222 }
223 // The linker_option directives are intended for host compilation.
224 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
225 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
226 Default = false;
227 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
228 Default);
229}
230
231/// Add a CC1 option to specify the debug compilation directory.
232static const char *addDebugCompDirArg(const ArgList &Args,
233 ArgStringList &CmdArgs,
234 const llvm::vfs::FileSystem &VFS) {
235 std::string DebugCompDir;
236 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
237 Ids: options::OPT_fdebug_compilation_dir_EQ))
238 DebugCompDir = A->getValue();
239
240 if (DebugCompDir.empty()) {
241 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
242 DebugCompDir = std::move(*CWD);
243 else
244 return nullptr;
245 }
246 CmdArgs.push_back(
247 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
248 StringRef Path(CmdArgs.back());
249 return Path.substr(Start: Path.find(C: '=') + 1).data();
250}
251
252static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
253 const char *DebugCompilationDir,
254 const char *OutputFileName) {
255 // No need to generate a value for -object-file-name if it was provided.
256 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
257 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
258 return;
259
260 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
261 return;
262
263 SmallString<128> ObjFileNameForDebug(OutputFileName);
264 if (ObjFileNameForDebug != "-" &&
265 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
266 (!DebugCompilationDir ||
267 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
268 // Make the path absolute in the debug infos like MSVC does.
269 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
270 }
271 // If the object file name is a relative path, then always use Windows
272 // backslash style as -object-file-name is used for embedding object file path
273 // in codeview and it can only be generated when targeting on Windows.
274 // Otherwise, just use native absolute path.
275 llvm::sys::path::Style Style =
276 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
277 ? llvm::sys::path::Style::native
278 : llvm::sys::path::Style::windows_backslash;
279 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
280 style: Style);
281 CmdArgs.push_back(
282 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
283}
284
285/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
286static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
287 const ArgList &Args, ArgStringList &CmdArgs) {
288 auto AddOneArg = [&](StringRef Map, StringRef Name) {
289 if (!Map.contains(C: '='))
290 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
291 else
292 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
293 };
294
295 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
296 Ids: options::OPT_fdebug_prefix_map_EQ)) {
297 AddOneArg(A->getValue(), A->getOption().getName());
298 A->claim();
299 }
300 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
301 if (GlobalRemapEntry.empty())
302 return;
303 AddOneArg(GlobalRemapEntry, "environment");
304}
305
306/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
307static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
308 ArgStringList &CmdArgs) {
309 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
310 Ids: options::OPT_fmacro_prefix_map_EQ)) {
311 StringRef Map = A->getValue();
312 if (!Map.contains(C: '='))
313 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
314 << Map << A->getOption().getName();
315 else
316 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
317 A->claim();
318 }
319}
320
321/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
322static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
323 ArgStringList &CmdArgs) {
324 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
325 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
326 StringRef Map = A->getValue();
327 if (!Map.contains(C: '='))
328 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
329 << Map << A->getOption().getName();
330 else
331 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
332 A->claim();
333 }
334}
335
336/// Add -x lang to \p CmdArgs for \p Input.
337static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
338 ArgStringList &CmdArgs) {
339 // When using -verify-pch, we don't want to provide the type
340 // 'precompiled-header' if it was inferred from the file extension
341 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
342 return;
343
344 CmdArgs.push_back(Elt: "-x");
345 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
346 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
347 else {
348 // Map the driver type to the frontend type. This is mostly an identity
349 // mapping, except that the distinction between module interface units
350 // and other source files does not exist at the frontend layer.
351 const char *ClangType;
352 switch (Input.getType()) {
353 case types::TY_CXXModule:
354 case types::TY_CXXStdModule:
355 ClangType = "c++";
356 break;
357 case types::TY_PP_CXXModule:
358 ClangType = "c++-cpp-output";
359 break;
360 case types::TY_CIRBC:
361 ClangType = "cir";
362 break;
363 default:
364 ClangType = types::getTypeName(Id: Input.getType());
365 break;
366 }
367 CmdArgs.push_back(Elt: ClangType);
368 }
369}
370
371static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
372 const JobAction &JA, const InputInfo &Output,
373 const ArgList &Args, SanitizerArgs &SanArgs,
374 ArgStringList &CmdArgs) {
375 const Driver &D = TC.getDriver();
376 const llvm::Triple &T = TC.getTriple();
377 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
378 Ids: options::OPT_fprofile_generate_EQ,
379 Ids: options::OPT_fno_profile_generate);
380 if (PGOGenerateArg &&
381 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
382 PGOGenerateArg = nullptr;
383
384 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
385
386 auto *ProfileGenerateArg = Args.getLastArg(
387 Ids: options::OPT_fprofile_instr_generate,
388 Ids: options::OPT_fprofile_instr_generate_EQ,
389 Ids: options::OPT_fno_profile_instr_generate);
390 if (ProfileGenerateArg &&
391 ProfileGenerateArg->getOption().matches(
392 ID: options::OPT_fno_profile_instr_generate))
393 ProfileGenerateArg = nullptr;
394
395 if (PGOGenerateArg && ProfileGenerateArg)
396 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
397 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
398
399 auto *ProfileUseArg = getLastProfileUseArg(Args);
400
401 if (PGOGenerateArg && ProfileUseArg)
402 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
403 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
404
405 if (ProfileGenerateArg && ProfileUseArg)
406 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
407 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
408
409 if (CSPGOGenerateArg && PGOGenerateArg) {
410 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
411 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
412 PGOGenerateArg = nullptr;
413 }
414
415 if (TC.getTriple().isOSAIX()) {
416 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
417 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
418 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
419 }
420
421 if (ProfileGenerateArg) {
422 if (ProfileGenerateArg->getOption().matches(
423 ID: options::OPT_fprofile_instr_generate_EQ))
424 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
425 ProfileGenerateArg->getValue()));
426 // The default is to use Clang Instrumentation.
427 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
428 if (TC.getTriple().isWindowsMSVCEnvironment() &&
429 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
430 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
431 // Add dependent lib for clang_rt.profile
432 CmdArgs.push_back(Elt: Args.MakeArgString(
433 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
434 }
435 }
436
437 if (auto *ColdFuncCoverageArg = Args.getLastArg(
438 Ids: options::OPT_fprofile_generate_cold_function_coverage,
439 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
440 SmallString<128> Path(
441 ColdFuncCoverageArg->getOption().matches(
442 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
443 ? ColdFuncCoverageArg->getValue()
444 : "");
445 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
446 // FIXME: Idealy the file path should be passed through
447 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
448 // shared with other profile use path(see PGOOptions), we need to refactor
449 // PGOOptions to make it work.
450 CmdArgs.push_back(Elt: "-mllvm");
451 CmdArgs.push_back(Elt: Args.MakeArgString(
452 Str: Twine("--instrument-cold-function-only-path=") + Path));
453 CmdArgs.push_back(Elt: "-mllvm");
454 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
455 CmdArgs.push_back(Elt: "-mllvm");
456 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
457 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
458 }
459
460 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
461 if (!PGOGenerateArg && !CSPGOGenerateArg)
462 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
463 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
464 CmdArgs.push_back(Elt: "-mllvm");
465 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
466 }
467
468 Arg *PGOGenArg = nullptr;
469 if (PGOGenerateArg) {
470 assert(!CSPGOGenerateArg);
471 PGOGenArg = PGOGenerateArg;
472 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
473 }
474 if (CSPGOGenerateArg) {
475 assert(!PGOGenerateArg);
476 PGOGenArg = CSPGOGenerateArg;
477 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
478 }
479 if (PGOGenArg) {
480 if (TC.getTriple().isWindowsMSVCEnvironment() &&
481 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
482 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
483 // Add dependent lib for clang_rt.profile
484 CmdArgs.push_back(Elt: Args.MakeArgString(
485 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
486 }
487 if (PGOGenArg->getOption().matches(
488 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
489 : options::OPT_fcs_profile_generate_EQ)) {
490 SmallString<128> Path(PGOGenArg->getValue());
491 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
492 CmdArgs.push_back(
493 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
494 }
495 }
496
497 if (ProfileUseArg) {
498 SmallString<128> UsePathBuf;
499 StringRef UsePath;
500 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
501 UsePath = ProfileUseArg->getValue();
502 else if ((ProfileUseArg->getOption().matches(
503 ID: options::OPT_fprofile_use_EQ) ||
504 ProfileUseArg->getOption().matches(
505 ID: options::OPT_fprofile_instr_use))) {
506 UsePathBuf =
507 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
508 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
509 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
510 UsePath = UsePathBuf;
511 }
512 auto ReaderOrErr =
513 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
514 if (auto E = ReaderOrErr.takeError()) {
515 auto DiagID = D.getDiags().getCustomDiagID(
516 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
517 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
518 D.Diag(DiagID) << UsePath.str() << EI.message();
519 });
520 } else {
521 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
522 std::move(ReaderOrErr.get());
523 StringRef UseKind;
524 // Currently memprof profiles are only added at the IR level. Mark the
525 // profile type as IR in that case as well and the subsequent matching
526 // needs to detect which is available (might be one or both).
527 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
528 if (PGOReader->hasCSIRLevelProfile())
529 UseKind = "csllvm";
530 else
531 UseKind = "llvm";
532 } else
533 UseKind = "clang";
534
535 CmdArgs.push_back(
536 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
537 CmdArgs.push_back(
538 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
539 }
540 }
541
542 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
543 Neg: options::OPT_fno_test_coverage, Default: false) ||
544 Args.hasArg(Ids: options::OPT_coverage);
545 bool EmitCovData = TC.needsGCovInstrumentation(Args);
546
547 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
548 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
549 if (!ProfileGenerateArg)
550 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
551 << "-fcoverage-mapping"
552 << "-fprofile-instr-generate";
553
554 CmdArgs.push_back(Elt: "-fcoverage-mapping");
555 }
556
557 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
558 Default: false)) {
559 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
560 Neg: options::OPT_fno_coverage_mapping, Default: false))
561 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
562 << "-fcoverage-mcdc"
563 << "-fcoverage-mapping";
564
565 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
566 }
567
568 StringRef CoverageCompDir;
569 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
570 Ids: options::OPT_fcoverage_compilation_dir_EQ))
571 CoverageCompDir = A->getValue();
572 if (CoverageCompDir.empty()) {
573 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
574 CmdArgs.push_back(
575 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
576 } else
577 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
578 CoverageCompDir));
579
580 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
581 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
582 if (!Args.hasArg(Ids: options::OPT_coverage))
583 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
584 << "-fprofile-exclude-files="
585 << "--coverage";
586
587 StringRef v = Arg->getValue();
588 CmdArgs.push_back(
589 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
590 }
591
592 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
593 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
594 if (!Args.hasArg(Ids: options::OPT_coverage))
595 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
596 << "-fprofile-filter-files="
597 << "--coverage";
598
599 StringRef v = Arg->getValue();
600 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
601 }
602
603 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
604 StringRef Val = A->getValue();
605 if (Val == "atomic" || Val == "prefer-atomic")
606 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
607 else if (Val != "single")
608 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
609 << A->getSpelling() << Val;
610 }
611 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
612 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
613 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
614 << A->getSpelling()
615 << "-fprofile-generate, -fprofile-instr-generate, or "
616 "-fcs-profile-generate";
617 else {
618 CmdArgs.push_back(Elt: "-fprofile-continuous");
619 // Platforms that require a bias variable:
620 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
621 CmdArgs.push_back(Elt: "-mllvm");
622 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
623 }
624 // -fprofile-instr-generate does not decide the profile file name in the
625 // FE, and so it does not define the filename symbol
626 // (__llvm_profile_filename). Instead, the runtime uses the name
627 // "default.profraw" for the profile file. When continuous mode is ON, we
628 // will create the filename symbol so that we can insert the "%c"
629 // modifier.
630 if (ProfileGenerateArg &&
631 (ProfileGenerateArg->getOption().matches(
632 ID: options::OPT_fprofile_instr_generate) ||
633 (ProfileGenerateArg->getOption().matches(
634 ID: options::OPT_fprofile_instr_generate_EQ) &&
635 strlen(s: ProfileGenerateArg->getValue()) == 0)))
636 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
637 }
638 }
639
640 int FunctionGroups = 1;
641 int SelectedFunctionGroup = 0;
642 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
643 StringRef Val = A->getValue();
644 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
645 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
646 }
647 if (const auto *A =
648 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
649 StringRef Val = A->getValue();
650 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
651 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
652 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
653 }
654 if (FunctionGroups != 1)
655 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
656 Twine(FunctionGroups)));
657 if (SelectedFunctionGroup != 0)
658 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
659 Twine(SelectedFunctionGroup)));
660
661 // Leave -fprofile-dir= an unused argument unless .gcda emission is
662 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
663 // the flag used. There is no -fno-profile-dir, so the user has no
664 // targeted way to suppress the warning.
665 Arg *FProfileDir = nullptr;
666 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
667 Args.hasArg(Ids: options::OPT_coverage))
668 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
669
670 // Put the .gcno and .gcda files (if needed) next to the primary output file,
671 // or fall back to a file in the current directory for `clang -c --coverage
672 // d/a.c` in the absence of -o.
673 if (EmitCovNotes || EmitCovData) {
674 SmallString<128> CoverageFilename;
675 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
676 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
677 // path separator.
678 CoverageFilename = DumpDir->getValue();
679 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
680 } else if (Arg *FinalOutput =
681 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
682 CoverageFilename = FinalOutput->getValue();
683 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
684 CoverageFilename = FinalOutput->getValue();
685 } else {
686 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
687 }
688 if (llvm::sys::path::is_relative(path: CoverageFilename))
689 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
690 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
691 if (EmitCovNotes) {
692 CmdArgs.push_back(
693 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
694 }
695
696 if (EmitCovData) {
697 if (FProfileDir) {
698 SmallString<128> Gcno = std::move(CoverageFilename);
699 CoverageFilename = FProfileDir->getValue();
700 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
701 }
702 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
703 CmdArgs.push_back(
704 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
705 }
706 }
707}
708
709static void
710RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
711 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
712 unsigned DwarfVersion,
713 llvm::DebuggerKind DebuggerTuning) {
714 addDebugInfoKind(CmdArgs, DebugInfoKind);
715 if (DwarfVersion > 0)
716 CmdArgs.push_back(
717 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
718 switch (DebuggerTuning) {
719 case llvm::DebuggerKind::GDB:
720 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
721 break;
722 case llvm::DebuggerKind::LLDB:
723 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
724 break;
725 case llvm::DebuggerKind::SCE:
726 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
727 break;
728 case llvm::DebuggerKind::DBX:
729 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
730 break;
731 default:
732 break;
733 }
734}
735
736static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
737 const ArgList &Args,
738 ArgStringList &CmdArgs,
739 bool IsCC1As = false) {
740 // If no version was requested by the user, use the default value from the
741 // back end. This is consistent with the value returned from
742 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
743 // requiring the corresponding llvm to have the AMDGPU target enabled,
744 // provided the user (e.g. front end tests) can use the default.
745 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
746 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
747 CmdArgs.insert(I: CmdArgs.begin() + 1,
748 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
749 Twine(CodeObjVer)));
750 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
751 // -cc1as does not accept -mcode-object-version option.
752 if (!IsCC1As)
753 CmdArgs.insert(I: CmdArgs.begin() + 1,
754 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
755 Twine(CodeObjVer)));
756 }
757}
758
759static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
760 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
761 D.getVFS().getBufferForFile(Name: Path);
762 if (!MemBuf)
763 return false;
764 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
765 if (Magic == llvm::file_magic::unknown)
766 return false;
767 // Return true for both raw Clang AST files and object files which may
768 // contain a __clangast section.
769 if (Magic == llvm::file_magic::clang_ast)
770 return true;
771 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
772 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
773 return !Obj.takeError();
774}
775
776static bool gchProbe(const Driver &D, StringRef Path) {
777 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
778 if (!Status)
779 return false;
780
781 if (Status->isDirectory()) {
782 std::error_code EC;
783 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
784 !EC && DI != DE; DI = DI.increment(EC)) {
785 if (maybeHasClangPchSignature(D, Path: DI->path()))
786 return true;
787 }
788 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
789 return false;
790 }
791
792 if (maybeHasClangPchSignature(D, Path))
793 return true;
794 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
795 return false;
796}
797
798void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
799 const Driver &D, const ArgList &Args,
800 ArgStringList &CmdArgs,
801 const InputInfo &Output,
802 const InputInfoList &Inputs) const {
803 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
804
805 CheckPreprocessingOptions(D, Args);
806
807 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
808 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
809
810 // Handle dependency file generation.
811 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
812 if (!ArgM)
813 ArgM = Args.getLastArg(Ids: options::OPT_M);
814 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
815 if (!ArgMD)
816 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
817
818 // -M and -MM imply -w.
819 if (ArgM)
820 CmdArgs.push_back(Elt: "-w");
821 else
822 ArgM = ArgMD;
823
824 if (ArgM) {
825 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
826 // Determine the output location.
827 const char *DepFile;
828 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
829 DepFile = MF->getValue();
830 C.addFailureResultFile(Name: DepFile, JA: &JA);
831 } else if (Output.getType() == types::TY_Dependencies) {
832 DepFile = Output.getFilename();
833 } else if (!ArgMD) {
834 DepFile = "-";
835 } else {
836 DepFile = getDependencyFileName(Args, Inputs);
837 C.addFailureResultFile(Name: DepFile, JA: &JA);
838 }
839 CmdArgs.push_back(Elt: "-dependency-file");
840 CmdArgs.push_back(Elt: DepFile);
841 }
842 // Cmake generates dependency files using all compilation options specified
843 // by users. Claim those not used for dependency files.
844 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
845 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
846 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
847 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
848 }
849
850 bool HasTarget = false;
851 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
852 HasTarget = true;
853 A->claim();
854 if (A->getOption().matches(ID: options::OPT_MT)) {
855 A->render(Args, Output&: CmdArgs);
856 } else {
857 CmdArgs.push_back(Elt: "-MT");
858 SmallString<128> Quoted;
859 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
860 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
861 }
862 }
863
864 // Add a default target if one wasn't specified.
865 if (!HasTarget) {
866 const char *DepTarget;
867
868 // If user provided -o, that is the dependency target, except
869 // when we are only generating a dependency file.
870 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
871 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
872 DepTarget = OutputOpt->getValue();
873 } else {
874 // Otherwise derive from the base input.
875 //
876 // FIXME: This should use the computed output file location.
877 SmallString<128> P(Inputs[0].getBaseInput());
878 llvm::sys::path::replace_extension(path&: P, extension: "o");
879 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
880 }
881
882 CmdArgs.push_back(Elt: "-MT");
883 SmallString<128> Quoted;
884 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
885 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
886 }
887
888 if (ArgM->getOption().matches(ID: options::OPT_M) ||
889 ArgM->getOption().matches(ID: options::OPT_MD))
890 CmdArgs.push_back(Elt: "-sys-header-deps");
891
892 // Determine module file deps mode.
893 StringRef ModuleFileDepsVal;
894 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_file_deps_EQ,
895 Ids: options::OPT_fmodule_file_deps,
896 Ids: options::OPT_fno_module_file_deps)) {
897 if (A->getOption().matches(ID: options::OPT_fmodule_file_deps_EQ))
898 ModuleFileDepsVal = A->getValue();
899 else if (A->getOption().matches(ID: options::OPT_fmodule_file_deps))
900 ModuleFileDepsVal = "all";
901 else
902 ModuleFileDepsVal = "none";
903 } else if (isa<PrecompileJobAction>(Val: JA)) {
904 ModuleFileDepsVal = "all";
905 }
906 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
907 CmdArgs.push_back(
908 Elt: Args.MakeArgString(Str: "-module-file-deps=" + ModuleFileDepsVal));
909 }
910
911 if (Args.hasArg(Ids: options::OPT_MG)) {
912 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
913 ArgM->getOption().matches(ID: options::OPT_MMD))
914 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
915 CmdArgs.push_back(Elt: "-MG");
916 }
917
918 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
919 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
920
921 bool UsesLLVMOffloading = Args.hasFlag(
922 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
923 bool UsesOffloadInclude =
924 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc, Default: true);
925 bool NoBuiltinInc = Args.hasArg(Ids: options::OPT_nobuiltininc);
926
927 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
928 // want to pull in our wrappers instead of the vendor headers.
929 if (UsesLLVMOffloading) {
930 if (UsesOffloadInclude && !NoBuiltinInc) {
931 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
932 StringRef RuntimeHeader) {
933 SmallString<128> OffloadInclude(D.Dir);
934 llvm::sys::path::append(path&: OffloadInclude, a: "..", b: "include", c: "offload");
935 if (!IncludeSubdir.empty())
936 llvm::sys::path::append(path&: OffloadInclude, a: IncludeSubdir);
937 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: OffloadInclude),
938 "-include", Args.MakeArgString(Str: RuntimeHeader)});
939 };
940 auto AddForcedInclude = [&](StringRef Header) {
941 CmdArgs.push_back(Elt: "-include");
942 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Header));
943 };
944 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
945 AddForcedInclude("__clang_gpu_builtin_vars.h");
946 AddForcedInclude("__clang_gpu_device_functions.h");
947 AddForcedInclude("__clang_gpu_intrinsics.h");
948 if (JA.isOffloading(OKind: Action::OFK_Cuda))
949 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
950 if (JA.isOffloading(OKind: Action::OFK_HIP) &&
951 !Args.hasArg(Ids: options::OPT_nohipwrapperinc)) {
952 // HIP code commonly includes this as "hip/hip_runtime.h".
953 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
954 }
955 }
956 } else {
957 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
958 // happen before we -I or -include anything else, because we must pick up
959 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
960 // installation, rather than from e.g. /usr/local/include.
961 if (JA.isOffloading(OKind: Action::OFK_Cuda))
962 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
963 if (JA.isOffloading(OKind: Action::OFK_HIP))
964 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
965 if (JA.isOffloading(OKind: Action::OFK_SYCL))
966 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
967
968 // If we are offloading to a target via OpenMP we need to include the
969 // openmp_wrappers folder which contains alternative system headers.
970 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
971 !Args.hasArg(Ids: options::OPT_nostdinc) && UsesOffloadInclude &&
972 getToolChain().getTriple().isGPU()) {
973 if (!NoBuiltinInc) {
974 // Add openmp_wrappers/* to our system include path. This lets us
975 // wrap standard library headers.
976 SmallString<128> P(D.ResourceDir);
977 llvm::sys::path::append(path&: P, a: "include");
978 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
979 CmdArgs.push_back(Elt: "-internal-isystem");
980 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
981 }
982
983 CmdArgs.push_back(Elt: "-include");
984 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
985 }
986 }
987
988 // Add -i* options, and automatically translate to
989 // -include-pch/-include-pth for transparent PCH support. It's
990 // wonky, but we include looking for .gch so we can support seamless
991 // replacement into a build system already set up to be generating
992 // .gch files.
993
994 if (getToolChain().getDriver().IsCLMode()) {
995 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
996 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
997 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
998 JA.getKind() <= Action::AssembleJobClass) {
999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
1000 // -fpch-instantiate-templates is the default when creating
1001 // precomp using /Yc
1002 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
1003 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
1004 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
1005 }
1006 if (YcArg || YuArg) {
1007 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1008 if (!isa<PrecompileJobAction>(Val: JA)) {
1009 CmdArgs.push_back(Elt: "-include-pch");
1010 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1011 C, BaseName: !ThroughHeader.empty()
1012 ? ThroughHeader
1013 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1014 }
1015
1016 if (ThroughHeader.empty()) {
1017 CmdArgs.push_back(Elt: Args.MakeArgString(
1018 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1019 } else {
1020 CmdArgs.push_back(
1021 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1022 }
1023 }
1024 }
1025
1026 bool RenderedImplicitInclude = false;
1027 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1028 if (A->getOption().matches(ID: options::OPT_include) &&
1029 D.getProbePrecompiled()) {
1030 // Handling of gcc-style gch precompiled headers.
1031 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1032 RenderedImplicitInclude = true;
1033
1034 bool FoundPCH = false;
1035 SmallString<128> P(A->getValue());
1036 // We want the files to have a name like foo.h.pch. Add a dummy extension
1037 // so that replace_extension does the right thing.
1038 P += ".dummy";
1039 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1040 if (D.getVFS().exists(Path: P))
1041 FoundPCH = true;
1042
1043 if (!FoundPCH) {
1044 // For GCC compat, probe for a file or directory ending in .gch instead.
1045 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1046 FoundPCH = gchProbe(D, Path: P.str());
1047 }
1048
1049 if (FoundPCH) {
1050 if (IsFirstImplicitInclude) {
1051 A->claim();
1052 CmdArgs.push_back(Elt: "-include-pch");
1053 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1054 continue;
1055 } else {
1056 // Ignore the PCH if not first on command line and emit warning.
1057 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1058 << A->getAsString(Args);
1059 }
1060 }
1061 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1062 // Handling of paths which must come late. These entries are handled by
1063 // the toolchain itself after the resource dir is inserted in the right
1064 // search order.
1065 // Do not claim the argument so that the use of the argument does not
1066 // silently go unnoticed on toolchains which do not honour the option.
1067 continue;
1068 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1069 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1070 continue;
1071 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1072 // This is used only by the driver. No need to pass to cc1.
1073 continue;
1074 }
1075
1076 // Not translated, render as usual.
1077 A->claim();
1078 A->render(Args, Output&: CmdArgs);
1079 }
1080
1081 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1082 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1083 // Collect all enabled NVPTX architectures.
1084 std::set<unsigned> ArchIDs;
1085 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1086 const ToolChain *TC = I.second;
1087 for (BoundArch Arch :
1088 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1089 if (Arch.Arch.isNVPTX())
1090 ArchIDs.insert(x: CudaArchToID(Arch: Arch.Arch));
1091 }
1092 }
1093
1094 if (!ArchIDs.empty()) {
1095 SmallString<128> List;
1096 llvm::raw_svector_ostream OS(List);
1097 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1098 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1099 }
1100 }
1101
1102 Args.addAllArgs(Output&: CmdArgs,
1103 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1104 options::OPT_F, options::OPT_embed_dir_EQ});
1105
1106 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1107
1108 // FIXME: There is a very unfortunate problem here, some troubled
1109 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1110 // really support that we would have to parse and then translate
1111 // those options. :(
1112 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1113 Id1: options::OPT_Xpreprocessor);
1114
1115 // -I- is a deprecated GCC feature, reject it.
1116 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1117 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1118
1119 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1120 // -isysroot to the CC1 invocation.
1121 StringRef sysroot = C.getSysRoot();
1122 if (sysroot != "") {
1123 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1124 CmdArgs.push_back(Elt: "-isysroot");
1125 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1126 }
1127 }
1128
1129 // Parse additional include paths from environment variables.
1130 // FIXME: We should probably sink the logic for handling these from the
1131 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1132 // CPATH - included following the user specified includes (but prior to
1133 // builtin and standard includes).
1134 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1135 // C_INCLUDE_PATH - system includes enabled when compiling C.
1136 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1137 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1138 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1139 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1140 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1141 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1142 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1143
1144 // While adding the include arguments, we also attempt to retrieve the
1145 // arguments of related offloading toolchains or arguments that are specific
1146 // of an offloading programming model.
1147
1148 // Add C++ include arguments, if needed.
1149 if (types::isCXX(Id: Inputs[0].getType())) {
1150 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1151 forAllAssociatedToolChains(
1152 C, JA, RegularToolChain: getToolChain(),
1153 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1154 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1155 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1156 });
1157 }
1158
1159 // If we are compiling for a GPU target with the LLVM environment we want to
1160 // override the system headers with ones created by the 'libc' project if
1161 // present.
1162 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1163 // OffloadKind as an argument.
1164 bool OffloadUsesLLVMLibc =
1165 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1166 (C.getActiveOffloadKinds() != Action::OFK_None &&
1167 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1168 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1169 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1170 Default: true) &&
1171 !Args.hasArg(Ids: options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1172 SmallString<128> P(D.ResourceDir);
1173 llvm::sys::path::append(path&: P, a: "include");
1174 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1175 CmdArgs.push_back(Elt: "-internal-isystem");
1176 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1177 }
1178
1179 // Add system include arguments for all targets but IAMCU.
1180 if (!IsIAMCU)
1181 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1182 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1183 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1184 });
1185 else {
1186 // For IAMCU add special include arguments.
1187 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1188 }
1189
1190 addMacroPrefixMapArg(D, Args, CmdArgs);
1191 addCoveragePrefixMapArg(D, Args, CmdArgs);
1192
1193 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1194 Ids: options::OPT_fno_file_reproducible);
1195
1196 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1197 CmdArgs.push_back(Elt: "-source-date-epoch");
1198 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1199 }
1200
1201 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1202 Neg: options::OPT_fno_define_target_os_macros);
1203}
1204
1205// FIXME: Move to target hook.
1206static bool isSignedCharDefault(const llvm::Triple &Triple) {
1207 switch (Triple.getArch()) {
1208 default:
1209 return true;
1210
1211 case llvm::Triple::aarch64:
1212 case llvm::Triple::aarch64_32:
1213 case llvm::Triple::aarch64_be:
1214 case llvm::Triple::arm:
1215 case llvm::Triple::armeb:
1216 case llvm::Triple::thumb:
1217 case llvm::Triple::thumbeb:
1218 if (Triple.isOSDarwin() || Triple.isOSWindows())
1219 return true;
1220 return false;
1221
1222 case llvm::Triple::ppc:
1223 case llvm::Triple::ppc64:
1224 if (Triple.isOSDarwin())
1225 return true;
1226 return false;
1227
1228 case llvm::Triple::csky:
1229 case llvm::Triple::hexagon:
1230 case llvm::Triple::msp430:
1231 case llvm::Triple::ppcle:
1232 case llvm::Triple::ppc64le:
1233 case llvm::Triple::riscv32:
1234 case llvm::Triple::riscv64:
1235 case llvm::Triple::riscv32be:
1236 case llvm::Triple::riscv64be:
1237 case llvm::Triple::systemz:
1238 case llvm::Triple::xcore:
1239 case llvm::Triple::xtensa:
1240 return false;
1241 }
1242}
1243
1244static bool hasMultipleInvocations(const llvm::Triple &Triple,
1245 const ArgList &Args) {
1246 // Supported only on Darwin where we invoke the compiler multiple times
1247 // followed by an invocation to lipo.
1248 if (!Triple.isOSDarwin())
1249 return false;
1250 // If more than one "-arch <arch>" is specified, we're targeting multiple
1251 // architectures resulting in a fat binary.
1252 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1253}
1254
1255static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1256 const llvm::Triple &Triple) {
1257 // When enabling remarks, we need to error if:
1258 // * The remark file is specified but we're targeting multiple architectures,
1259 // which means more than one remark file is being generated.
1260 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1261 bool hasExplicitOutputFile =
1262 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1263 if (hasMultipleInvocations && hasExplicitOutputFile) {
1264 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1265 << "-foptimization-record-file";
1266 return false;
1267 }
1268 return true;
1269}
1270
1271static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1272 const llvm::Triple &Triple,
1273 const InputInfo &Input,
1274 const InputInfo &Output, const JobAction &JA) {
1275 StringRef Format = "yaml";
1276 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1277 Format = A->getValue();
1278
1279 CmdArgs.push_back(Elt: "-opt-record-file");
1280
1281 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1282 if (A) {
1283 CmdArgs.push_back(Elt: A->getValue());
1284 } else {
1285 bool hasMultipleArchs =
1286 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1287 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1288
1289 SmallString<128> F;
1290
1291 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1292 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1293 F = FinalOutput->getValue();
1294 } else {
1295 if (Format != "yaml" && // For YAML, keep the original behavior.
1296 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1297 Output.isFilename())
1298 F = Output.getFilename();
1299 }
1300
1301 if (F.empty()) {
1302 // Use the input filename.
1303 F = llvm::sys::path::stem(path: Input.getBaseInput());
1304
1305 // If we're compiling for an offload architecture (i.e. a CUDA device),
1306 // we need to make the file name for the device compilation different
1307 // from the host compilation.
1308 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1309 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1310 llvm::sys::path::replace_extension(path&: F, extension: "");
1311 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1312 NormalizedTriple: Triple.str());
1313 F += "-";
1314 F += JA.getOffloadingArch().ArchName;
1315 }
1316 }
1317
1318 // If we're having more than one "-arch", we should name the files
1319 // differently so that every cc1 invocation writes to a different file.
1320 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1321 // name from the triple.
1322 if (hasMultipleArchs) {
1323 // First, remember the extension.
1324 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1325 // then, remove it.
1326 llvm::sys::path::replace_extension(path&: F, extension: "");
1327 // attach -<arch> to it.
1328 F += "-";
1329 F += Triple.getArchName();
1330 // put back the extension.
1331 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1332 }
1333
1334 SmallString<32> Extension;
1335 Extension += "opt.";
1336 Extension += Format;
1337
1338 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1339 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1340 }
1341
1342 if (const Arg *A =
1343 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1344 CmdArgs.push_back(Elt: "-opt-record-passes");
1345 CmdArgs.push_back(Elt: A->getValue());
1346 }
1347
1348 if (!Format.empty()) {
1349 CmdArgs.push_back(Elt: "-opt-record-format");
1350 CmdArgs.push_back(Elt: Format.data());
1351 }
1352}
1353
1354void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1355 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1356 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1357 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1358
1359 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1360 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1361}
1362
1363namespace {
1364void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1365 const ArgList &Args, ArgStringList &CmdArgs) {
1366 // Select the ABI to use.
1367 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1368 const char *ABIName = nullptr;
1369 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1370 ABIName = A->getValue();
1371 else
1372 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1373
1374 CmdArgs.push_back(Elt: "-target-abi");
1375 CmdArgs.push_back(Elt: ABIName);
1376}
1377
1378void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1379 auto StrictAlignIter =
1380 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1381 return Arg == "+strict-align" || Arg == "-strict-align";
1382 });
1383 if (StrictAlignIter != CmdArgs.rend() &&
1384 StringRef(*StrictAlignIter) == "+strict-align")
1385 CmdArgs.push_back(Elt: "-Wunaligned-access");
1386}
1387}
1388
1389static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1390 ArgStringList &CmdArgs, bool isAArch64) {
1391 const llvm::Triple &Triple = TC.getEffectiveTriple();
1392 const Arg *A = isAArch64
1393 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1394 Ids: options::OPT_mbranch_protection_EQ)
1395 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1396 const Arg *HardenPACRetArg = Args.getLastArg(Ids: options::OPT_mharden_pac_ret_EQ);
1397 const Driver &D = TC.getDriver();
1398
1399 if (HardenPACRetArg) {
1400 if (!isAArch64) {
1401 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1402 << HardenPACRetArg->getSpelling() << TC.getTriple().str();
1403 return;
1404 }
1405 StringRef ArgValue = HardenPACRetArg->getValue();
1406 if (ArgValue != "none" && ArgValue != "load-return-address") {
1407 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1408 << HardenPACRetArg->getSpelling() << ArgValue;
1409 return;
1410 }
1411 if (ArgValue != "none" &&
1412 Args.hasFlagNoClaim(Pos: options::OPT_mexecute_only,
1413 Neg: options::OPT_mno_execute_only, Default: false)) {
1414 D.Diag(DiagID: diag::err_drv_incompatible_options)
1415 << HardenPACRetArg->getAsString(Args) << "-mexecute-only";
1416 return;
1417 }
1418 }
1419
1420 // Check CmdArgs because some toolchains bypass the driver args and add to
1421 // the frontend args directly.
1422 bool HasPtrauthReturns =
1423 llvm::is_contained(Range&: CmdArgs, Element: StringRef("-fptrauth-returns")) ||
1424 Args.hasFlagNoClaim(Pos: options::OPT_fptrauth_returns,
1425 Neg: options::OPT_fno_ptrauth_returns, Default: false);
1426
1427 auto RenderHardenPACRet = [&](StringRef Scope) {
1428 if (!HardenPACRetArg)
1429 return;
1430 if (Scope == "none" && !HasPtrauthReturns)
1431 D.Diag(DiagID: diag::warn_harden_pac_ret_requires_pac_ret);
1432 else
1433 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mharden-pac-ret=") +
1434 HardenPACRetArg->getValue()));
1435 };
1436
1437 if (!A) {
1438 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1439 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1440 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1441 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1442 RenderHardenPACRet("non-leaf");
1443 } else {
1444 RenderHardenPACRet("none");
1445 }
1446 return;
1447 }
1448
1449 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1450 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1451 << Triple.getArchName();
1452
1453 StringRef Scope, Key;
1454 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1455
1456 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1457 Scope = A->getValue();
1458 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1459 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1460 << A->getSpelling() << Scope;
1461 // This spelling cannot express a key, and AArch64 Windows only supports
1462 // B-key, so default to it there as parseBranchProtection() does.
1463 Key = isAArch64 && Triple.isOSWindows() ? "b_key" : "a_key";
1464 IndirectBranches =
1465 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1466 BranchProtectionPAuthLR = false;
1467 GuardedControlStack = false;
1468 } else {
1469 StringRef DiagMsg;
1470 llvm::ARM::ParsedBranchProtection PBP;
1471 bool EnablePAuthLR = false;
1472
1473 // To know if we need to enable PAuth-LR As part of the standard branch
1474 // protection option, it needs to be determined if the feature has been
1475 // activated in the `march` argument. This information is stored within the
1476 // CmdArgs variable and can be found using a search.
1477 if (isAArch64) {
1478 auto isPAuthLR = [](const char *member) {
1479 llvm::AArch64::ExtensionInfo pauthlr_extension =
1480 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1481 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1482 member;
1483 };
1484
1485 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1486 EnablePAuthLR = true;
1487 }
1488 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg, Triple,
1489 EnablePAuthLR))
1490 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1491 << A->getSpelling() << DiagMsg;
1492 if (!isAArch64 && PBP.Key == "b_key")
1493 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1494 << "b-key" << A->getAsString(Args);
1495 Scope = PBP.Scope;
1496 Key = PBP.Key;
1497 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1498 IndirectBranches = PBP.BranchTargetEnforcement;
1499 GuardedControlStack = PBP.GuardedControlStack;
1500 }
1501
1502 // GCS is currently untested with ptrauth-returns, but enabling this could be
1503 // allowed in future after testing with a suitable system.
1504 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1505 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1506 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1507 << A->getAsString(Args) << Triple.getTriple();
1508 else if (HasPtrauthReturns)
1509 D.Diag(DiagID: diag::err_drv_incompatible_options)
1510 << A->getAsString(Args) << "-fptrauth-returns";
1511 }
1512
1513 CmdArgs.push_back(
1514 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1515 if (Scope != "none")
1516 CmdArgs.push_back(
1517 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1518 if (BranchProtectionPAuthLR)
1519 CmdArgs.push_back(
1520 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1521 if (IndirectBranches)
1522 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1523
1524 if (GuardedControlStack)
1525 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1526
1527 RenderHardenPACRet(Scope);
1528}
1529
1530void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1531 ArgStringList &CmdArgs, bool KernelOrKext) const {
1532 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1533
1534 // Determine floating point ABI from the options & target defaults.
1535 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1536 if (ABI == arm::FloatABI::Soft) {
1537 // Floating point operations and argument passing are soft.
1538 // FIXME: This changes CPP defines, we need -target-soft-float.
1539 CmdArgs.push_back(Elt: "-msoft-float");
1540 CmdArgs.push_back(Elt: "-mfloat-abi");
1541 CmdArgs.push_back(Elt: "soft");
1542 } else if (ABI == arm::FloatABI::SoftFP) {
1543 // Floating point operations are hard, but argument passing is soft.
1544 CmdArgs.push_back(Elt: "-mfloat-abi");
1545 CmdArgs.push_back(Elt: "soft");
1546 } else {
1547 // Floating point operations and argument passing are hard.
1548 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1549 CmdArgs.push_back(Elt: "-mfloat-abi");
1550 CmdArgs.push_back(Elt: "hard");
1551 }
1552
1553 // Forward the -mglobal-merge option for explicit control over the pass.
1554 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1555 Ids: options::OPT_mno_global_merge)) {
1556 CmdArgs.push_back(Elt: "-mllvm");
1557 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1558 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1559 else
1560 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1561 }
1562
1563 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1564 Neg: options::OPT_mno_implicit_float, Default: true))
1565 CmdArgs.push_back(Elt: "-no-implicit-float");
1566
1567 if (Args.getLastArg(Ids: options::OPT_mcmse))
1568 CmdArgs.push_back(Elt: "-mcmse");
1569
1570 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1571
1572 // Enable/disable return address signing and indirect branch targets.
1573 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1574
1575 AddUnalignedAccessWarning(CmdArgs);
1576}
1577
1578void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1579 ArgStringList &CmdArgs) const {
1580 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1581 if (Arg *A = Args.getLastArg(Ids: options::OPT_mxnack, Ids: options::OPT_mno_xnack))
1582 A->render(Args, Output&: CmdArgs);
1583 if (Arg *A = Args.getLastArg(Ids: options::OPT_msramecc, Ids: options::OPT_mno_sramecc))
1584 A->render(Args, Output&: CmdArgs);
1585}
1586
1587void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1588 const ArgList &Args, bool KernelOrKext,
1589 ArgStringList &CmdArgs) const {
1590 const ToolChain &TC = getToolChain();
1591
1592 // Add the target features
1593 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1594
1595 // Add target specific flags.
1596 switch (TC.getArch()) {
1597 default:
1598 break;
1599
1600 case llvm::Triple::arm:
1601 case llvm::Triple::armeb:
1602 case llvm::Triple::thumb:
1603 case llvm::Triple::thumbeb:
1604 // Use the effective triple, which takes into account the deployment target.
1605 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1606 break;
1607
1608 case llvm::Triple::aarch64:
1609 case llvm::Triple::aarch64_32:
1610 case llvm::Triple::aarch64_be:
1611 AddAArch64TargetArgs(Args, CmdArgs);
1612 break;
1613
1614 case llvm::Triple::amdgpu:
1615 AddAMDGPUTargetArgs(Args, CmdArgs);
1616 break;
1617
1618 case llvm::Triple::loongarch32:
1619 case llvm::Triple::loongarch64:
1620 AddLoongArchTargetArgs(Args, CmdArgs);
1621 break;
1622
1623 case llvm::Triple::mips:
1624 case llvm::Triple::mipsel:
1625 case llvm::Triple::mips64:
1626 case llvm::Triple::mips64el:
1627 AddMIPSTargetArgs(Args, CmdArgs);
1628 break;
1629
1630 case llvm::Triple::ppc:
1631 case llvm::Triple::ppcle:
1632 case llvm::Triple::ppc64:
1633 case llvm::Triple::ppc64le:
1634 AddPPCTargetArgs(Args, CmdArgs);
1635 break;
1636
1637 case llvm::Triple::riscv32:
1638 case llvm::Triple::riscv64:
1639 case llvm::Triple::riscv32be:
1640 case llvm::Triple::riscv64be:
1641 AddRISCVTargetArgs(Args, CmdArgs);
1642 break;
1643
1644 case llvm::Triple::sparc:
1645 case llvm::Triple::sparcel:
1646 case llvm::Triple::sparcv9:
1647 AddSparcTargetArgs(Args, CmdArgs);
1648 break;
1649
1650 case llvm::Triple::systemz:
1651 AddSystemZTargetArgs(Args, CmdArgs);
1652 break;
1653
1654 case llvm::Triple::x86:
1655 case llvm::Triple::x86_64:
1656 AddX86TargetArgs(Args, CmdArgs);
1657 break;
1658
1659 case llvm::Triple::lanai:
1660 AddLanaiTargetArgs(Args, CmdArgs);
1661 break;
1662
1663 case llvm::Triple::hexagon:
1664 AddHexagonTargetArgs(Args, CmdArgs);
1665 break;
1666
1667 case llvm::Triple::wasm32:
1668 case llvm::Triple::wasm64:
1669 AddWebAssemblyTargetArgs(Args, CmdArgs);
1670 break;
1671
1672 case llvm::Triple::ve:
1673 AddVETargetArgs(Args, CmdArgs);
1674 break;
1675 }
1676}
1677
1678namespace {
1679void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1680 ArgStringList &CmdArgs) {
1681 const char *ABIName = nullptr;
1682 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1683 ABIName = A->getValue();
1684 else if (Triple.isOSDarwin())
1685 ABIName = "darwinpcs";
1686 // TODO: we probably want to have some target hook here.
1687 else if (Triple.isOSLinux() &&
1688 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1689 ABIName = "pauthtest";
1690 else
1691 ABIName = "aapcs";
1692
1693 CmdArgs.push_back(Elt: "-target-abi");
1694 CmdArgs.push_back(Elt: ABIName);
1695}
1696}
1697
1698void Clang::AddAArch64TargetArgs(const ArgList &Args,
1699 ArgStringList &CmdArgs) const {
1700 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1701
1702 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1703 Args.hasArg(Ids: options::OPT_mkernel) ||
1704 Args.hasArg(Ids: options::OPT_fapple_kext))
1705 CmdArgs.push_back(Elt: "-disable-red-zone");
1706
1707 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1708 Neg: options::OPT_mno_implicit_float, Default: true))
1709 CmdArgs.push_back(Elt: "-no-implicit-float");
1710
1711 RenderAArch64ABI(Triple, Args, CmdArgs);
1712
1713 // Forward the -mglobal-merge option for explicit control over the pass.
1714 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1715 Ids: options::OPT_mno_global_merge)) {
1716 CmdArgs.push_back(Elt: "-mllvm");
1717 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1718 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1719 else
1720 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1721 }
1722
1723 // Handle -msve_vector_bits=<bits>
1724 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1725 StringRef VScaleMax) {
1726 StringRef Val = A->getValue();
1727 const Driver &D = getToolChain().getDriver();
1728 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1729 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1730 Val == "1024+" || Val == "2048+") {
1731 unsigned Bits = 0;
1732 if (!Val.consume_back(Suffix: "+")) {
1733 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1734 (void)Invalid;
1735 assert(!Invalid && "Failed to parse value");
1736 CmdArgs.push_back(
1737 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1738 }
1739
1740 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1741 (void)Invalid;
1742 assert(!Invalid && "Failed to parse value");
1743
1744 CmdArgs.push_back(
1745 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1746 } else if (Val == "scalable") {
1747 // Silently drop requests for vector-length agnostic code as it's implied.
1748 } else {
1749 // Handle the unsupported values passed to msve-vector-bits.
1750 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1751 << A->getSpelling() << Val;
1752 }
1753 };
1754 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1755 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1756 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1757 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1758
1759 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1760
1761 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1762 CmdArgs.push_back(Elt: "-tune-cpu");
1763 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1764 }
1765
1766 AddUnalignedAccessWarning(CmdArgs);
1767
1768 if (Triple.isOSDarwin() ||
1769 (Triple.isOSLinux() &&
1770 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1771 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1772 Neg: options::OPT_fno_ptrauth_intrinsics);
1773 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1774 Neg: options::OPT_fno_ptrauth_calls);
1775 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1776 Neg: options::OPT_fno_ptrauth_returns);
1777 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1778 Neg: options::OPT_fno_ptrauth_auth_traps);
1779 Args.addOptInFlag(
1780 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1781 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1782 Args.addOptInFlag(
1783 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1784 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1785 Args.addOptInFlag(
1786 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1787 Neg: options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1788 Args.addOptInFlag(
1789 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1790 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1791 Args.addOptInFlag(
1792 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1793 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1794 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1795 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1796 }
1797 if (Triple.isOSLinux() &&
1798 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1799 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1800 Neg: options::OPT_fno_ptrauth_init_fini);
1801 Args.addOptInFlag(
1802 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1803 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1804 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1805 Neg: options::OPT_fno_ptrauth_elf_got);
1806 }
1807 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1808 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1809
1810 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1811 Neg: options::OPT_fno_ptrauth_objc_isa);
1812 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1813 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1814 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1815 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1816
1817 // Enable/disable return address signing and indirect branch targets.
1818 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1819}
1820
1821void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1822 ArgStringList &CmdArgs) const {
1823 const llvm::Triple &Triple = getToolChain().getTriple();
1824
1825 CmdArgs.push_back(Elt: "-target-abi");
1826 CmdArgs.push_back(
1827 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1828 .data());
1829
1830 // Handle -mtune.
1831 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1832 std::string TuneCPU = A->getValue();
1833 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1834 CmdArgs.push_back(Elt: "-tune-cpu");
1835 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1836 }
1837
1838 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1839 Ids: options::OPT_mno_annotate_tablejump)) {
1840 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1841 CmdArgs.push_back(Elt: "-mllvm");
1842 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1843 }
1844 }
1845}
1846
1847void Clang::AddMIPSTargetArgs(const ArgList &Args,
1848 ArgStringList &CmdArgs) const {
1849 const Driver &D = getToolChain().getDriver();
1850 StringRef CPUName;
1851 StringRef ABIName;
1852 const llvm::Triple &Triple = getToolChain().getTriple();
1853 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1854
1855 CmdArgs.push_back(Elt: "-target-abi");
1856 CmdArgs.push_back(Elt: ABIName.data());
1857
1858 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1859 if (ABI == mips::FloatABI::Soft) {
1860 // Floating point operations and argument passing are soft.
1861 CmdArgs.push_back(Elt: "-msoft-float");
1862 CmdArgs.push_back(Elt: "-mfloat-abi");
1863 CmdArgs.push_back(Elt: "soft");
1864 } else {
1865 // Floating point operations and argument passing are hard.
1866 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1867 CmdArgs.push_back(Elt: "-mfloat-abi");
1868 CmdArgs.push_back(Elt: "hard");
1869 }
1870
1871 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1872 Ids: options::OPT_mno_ldc1_sdc1)) {
1873 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1874 CmdArgs.push_back(Elt: "-mllvm");
1875 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1876 }
1877 }
1878
1879 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1880 Ids: options::OPT_mno_check_zero_division)) {
1881 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1882 CmdArgs.push_back(Elt: "-mllvm");
1883 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1884 }
1885 }
1886
1887 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1888 CmdArgs.push_back(Elt: "-mllvm");
1889 CmdArgs.push_back(Elt: "-mfix4300");
1890 }
1891
1892 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1893 StringRef v = A->getValue();
1894 CmdArgs.push_back(Elt: "-mllvm");
1895 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1896 A->claim();
1897 }
1898
1899 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1900 Arg *ABICalls =
1901 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1902
1903 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1904 // -mgpopt is the default for static, -fno-pic environments but these two
1905 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1906 // the only case where -mllvm -mgpopt is passed.
1907 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1908 // passed explicitly when compiling something with -mabicalls
1909 // (implictly) in affect. Currently the warning is in the backend.
1910 //
1911 // When the ABI in use is N64, we also need to determine the PIC mode that
1912 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1913 bool NoABICalls =
1914 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1915
1916 llvm::Reloc::Model RelocationModel;
1917 unsigned PICLevel;
1918 bool IsPIE;
1919 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1920 ParsePICArgs(ToolChain: getToolChain(), Args);
1921
1922 NoABICalls = NoABICalls ||
1923 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1924
1925 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1926 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1927 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1928 CmdArgs.push_back(Elt: "-mllvm");
1929 CmdArgs.push_back(Elt: "-mgpopt");
1930
1931 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1932 Ids: options::OPT_mno_local_sdata);
1933 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1934 Ids: options::OPT_mno_extern_sdata);
1935 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1936 Ids: options::OPT_mno_embedded_data);
1937 if (LocalSData) {
1938 CmdArgs.push_back(Elt: "-mllvm");
1939 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1940 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1941 } else {
1942 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1943 }
1944 LocalSData->claim();
1945 }
1946
1947 if (ExternSData) {
1948 CmdArgs.push_back(Elt: "-mllvm");
1949 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1950 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1951 } else {
1952 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1953 }
1954 ExternSData->claim();
1955 }
1956
1957 if (EmbeddedData) {
1958 CmdArgs.push_back(Elt: "-mllvm");
1959 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1960 CmdArgs.push_back(Elt: "-membedded-data=1");
1961 } else {
1962 CmdArgs.push_back(Elt: "-membedded-data=0");
1963 }
1964 EmbeddedData->claim();
1965 }
1966
1967 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1968 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1969
1970 if (GPOpt)
1971 GPOpt->claim();
1972
1973 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1974 StringRef Val = StringRef(A->getValue());
1975 if (mips::hasCompactBranches(CPU&: CPUName)) {
1976 if (Val == "never" || Val == "always" || Val == "optimal") {
1977 CmdArgs.push_back(Elt: "-mllvm");
1978 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1979 } else
1980 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1981 << A->getSpelling() << Val;
1982 } else
1983 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1984 }
1985
1986 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1987 Ids: options::OPT_mno_relax_pic_calls)) {
1988 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1989 CmdArgs.push_back(Elt: "-mllvm");
1990 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1991 }
1992 }
1993}
1994
1995void Clang::AddPPCTargetArgs(const ArgList &Args,
1996 ArgStringList &CmdArgs) const {
1997 const Driver &D = getToolChain().getDriver();
1998 const llvm::Triple &T = getToolChain().getTriple();
1999 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2000 CmdArgs.push_back(Elt: "-tune-cpu");
2001 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
2002 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
2003 }
2004
2005 // Select the ABI to use.
2006 const char *ABIName = nullptr;
2007 if (T.isOSBinFormatELF()) {
2008 switch (getToolChain().getArch()) {
2009 case llvm::Triple::ppc64: {
2010 if (T.isPPC64ELFv2ABI())
2011 ABIName = "elfv2";
2012 else
2013 ABIName = "elfv1";
2014 break;
2015 }
2016 case llvm::Triple::ppc64le:
2017 ABIName = "elfv2";
2018 break;
2019 default:
2020 break;
2021 }
2022 }
2023
2024 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2025 bool VecExtabi = false;
2026 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
2027 StringRef V = A->getValue();
2028 if (V == "ieeelongdouble") {
2029 IEEELongDouble = true;
2030 A->claim();
2031 } else if (V == "ibmlongdouble") {
2032 IEEELongDouble = false;
2033 A->claim();
2034 } else if (V == "vec-default") {
2035 VecExtabi = false;
2036 A->claim();
2037 } else if (V == "vec-extabi") {
2038 VecExtabi = true;
2039 A->claim();
2040 } else if (V == "elfv1") {
2041 ABIName = "elfv1";
2042 A->claim();
2043 } else if (V == "elfv2") {
2044 ABIName = "elfv2";
2045 A->claim();
2046 } else if (V != "altivec")
2047 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2048 // the option if given as we don't have backend support for any targets
2049 // that don't use the altivec abi.
2050 ABIName = A->getValue();
2051 }
2052 if (IEEELongDouble)
2053 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
2054 if (VecExtabi) {
2055 if (!T.isOSAIX())
2056 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2057 << "-mabi=vec-extabi" << T.str();
2058 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
2059 }
2060
2061 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
2062 CmdArgs.push_back(Elt: "-disable-red-zone");
2063
2064 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2065 if (FloatABI == ppc::FloatABI::Soft) {
2066 // Floating point operations and argument passing are soft.
2067 CmdArgs.push_back(Elt: "-msoft-float");
2068 CmdArgs.push_back(Elt: "-mfloat-abi");
2069 CmdArgs.push_back(Elt: "soft");
2070 } else {
2071 // Floating point operations and argument passing are hard.
2072 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2073 CmdArgs.push_back(Elt: "-mfloat-abi");
2074 CmdArgs.push_back(Elt: "hard");
2075 }
2076
2077 if (ABIName) {
2078 CmdArgs.push_back(Elt: "-target-abi");
2079 CmdArgs.push_back(Elt: ABIName);
2080 }
2081}
2082
2083void Clang::AddRISCVTargetArgs(const ArgList &Args,
2084 ArgStringList &CmdArgs) const {
2085 const llvm::Triple &Triple = getToolChain().getTriple();
2086 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2087
2088 CmdArgs.push_back(Elt: "-target-abi");
2089 CmdArgs.push_back(Elt: ABIName.data());
2090
2091 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2092 CmdArgs.push_back(Elt: "-msmall-data-limit");
2093 CmdArgs.push_back(Elt: A->getValue());
2094 }
2095
2096 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2097 Neg: options::OPT_mno_implicit_float, Default: true))
2098 CmdArgs.push_back(Elt: "-no-implicit-float");
2099
2100 auto TuneCPU = riscv::getRISCVTuneCPU(D: getToolChain().getDriver(), Args);
2101 if (!TuneCPU)
2102 return;
2103 if (!TuneCPU->empty()) {
2104 CmdArgs.push_back(Elt: "-tune-cpu");
2105 // TuneCPU might or might not be the original -mtune string, so we
2106 // have to create a new copy here.
2107 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
2108 }
2109
2110 // Handle -mrvv-vector-bits=<bits>
2111 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2112 StringRef Val = A->getValue();
2113 const Driver &D = getToolChain().getDriver();
2114
2115 // Get minimum VLen from march.
2116 unsigned MinVLen = 0;
2117 std::string Arch = riscv::getRISCVArch(Args, Triple);
2118 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2119 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2120 // Ignore parsing error.
2121 if (!errorToBool(Err: ISAInfo.takeError()))
2122 MinVLen = (*ISAInfo)->getMinVLen();
2123
2124 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2125 // as integer as long as we have a MinVLen.
2126 unsigned Bits = 0;
2127 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2128 Bits = MinVLen;
2129 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2130 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2131 // at least MinVLen.
2132 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2133 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2134 Bits = 0;
2135 }
2136
2137 // If we got a valid value try to use it.
2138 if (Bits != 0) {
2139 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2140 CmdArgs.push_back(
2141 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2142 CmdArgs.push_back(
2143 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2144 } else if (Val != "scalable") {
2145 // Handle the unsupported values passed to mrvv-vector-bits.
2146 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2147 << A->getSpelling() << Val;
2148 }
2149 }
2150}
2151
2152void Clang::AddSparcTargetArgs(const ArgList &Args,
2153 ArgStringList &CmdArgs) const {
2154 sparc::FloatABI FloatABI =
2155 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2156
2157 if (FloatABI == sparc::FloatABI::Soft) {
2158 // Floating point operations and argument passing are soft.
2159 CmdArgs.push_back(Elt: "-msoft-float");
2160 CmdArgs.push_back(Elt: "-mfloat-abi");
2161 CmdArgs.push_back(Elt: "soft");
2162 } else {
2163 // Floating point operations and argument passing are hard.
2164 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2165 CmdArgs.push_back(Elt: "-mfloat-abi");
2166 CmdArgs.push_back(Elt: "hard");
2167 }
2168
2169 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2170 StringRef Name = A->getValue();
2171 std::string TuneCPU;
2172 if (Name == "native")
2173 TuneCPU = std::string(llvm::sys::getHostCPUName());
2174 else
2175 TuneCPU = std::string(Name);
2176
2177 CmdArgs.push_back(Elt: "-tune-cpu");
2178 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2179 }
2180}
2181
2182void Clang::AddSystemZTargetArgs(const ArgList &Args,
2183 ArgStringList &CmdArgs) const {
2184 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2185 CmdArgs.push_back(Elt: "-tune-cpu");
2186 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2187 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2188 else
2189 CmdArgs.push_back(Elt: A->getValue());
2190 }
2191
2192 bool HasBackchain =
2193 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2194 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2195 Neg: options::OPT_mno_packed_stack, Default: false);
2196 systemz::FloatABI FloatABI =
2197 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2198 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2199
2200 // Only hard float ABI (-mhard-float) is supported on z/OS.
2201 const Driver &D = getToolChain().getDriver();
2202 const llvm::Triple &Triple = getToolChain().getTriple();
2203 if (HasSoftFloat && Triple.isOSzOS()) {
2204 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2205 << "-msoft-float" << Triple.str();
2206 }
2207 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2208 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2209 << "-mpacked-stack -mbackchain -mhard-float";
2210 }
2211 if (HasBackchain)
2212 CmdArgs.push_back(Elt: "-mbackchain");
2213 if (HasPackedStack)
2214 CmdArgs.push_back(Elt: "-mpacked-stack");
2215 if (HasSoftFloat) {
2216 // Floating point operations and argument passing are soft.
2217 CmdArgs.push_back(Elt: "-msoft-float");
2218 CmdArgs.push_back(Elt: "-mfloat-abi");
2219 CmdArgs.push_back(Elt: "soft");
2220 }
2221
2222 if (Triple.isOSzOS())
2223 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mzos_ppa1_name,
2224 Ids: options::OPT_mno_zos_ppa1_name);
2225}
2226
2227void Clang::AddX86TargetArgs(const ArgList &Args,
2228 ArgStringList &CmdArgs) const {
2229 const Driver &D = getToolChain().getDriver();
2230 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2231
2232 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2233 Args.hasArg(Ids: options::OPT_mkernel) ||
2234 Args.hasArg(Ids: options::OPT_fapple_kext))
2235 CmdArgs.push_back(Elt: "-disable-red-zone");
2236
2237 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2238 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2239 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2240
2241 // Default to avoid implicit floating-point for kernel/kext code, but allow
2242 // that to be overridden with -mno-soft-float.
2243 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2244 Args.hasArg(Ids: options::OPT_fapple_kext));
2245 if (Arg *A = Args.getLastArg(
2246 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2247 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2248 const Option &O = A->getOption();
2249 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2250 O.matches(ID: options::OPT_msoft_float));
2251 }
2252 if (NoImplicitFloat)
2253 CmdArgs.push_back(Elt: "-no-implicit-float");
2254
2255 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2256 StringRef Value = A->getValue();
2257 if (Value == "intel" || Value == "att") {
2258 CmdArgs.push_back(Elt: "-mllvm");
2259 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2260 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2261 } else {
2262 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2263 << A->getSpelling() << Value;
2264 }
2265 } else if (D.IsCLMode()) {
2266 CmdArgs.push_back(Elt: "-mllvm");
2267 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2268 }
2269
2270 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2271 Ids: options::OPT_mno_skip_rax_setup))
2272 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2273 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2274
2275 // Set flags to support MCU ABI.
2276 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2277 CmdArgs.push_back(Elt: "-mfloat-abi");
2278 CmdArgs.push_back(Elt: "soft");
2279 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2280 }
2281
2282 // Handle -mtune.
2283
2284 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2285 std::string TuneCPU;
2286 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2287 TuneCPU = "generic";
2288
2289 // Override based on -mtune.
2290 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2291 StringRef Name = A->getValue();
2292
2293 if (Name == "native") {
2294 Name = llvm::sys::getHostCPUName();
2295 if (!Name.empty())
2296 TuneCPU = std::string(Name);
2297 } else
2298 TuneCPU = std::string(Name);
2299 }
2300
2301 if (!TuneCPU.empty()) {
2302 CmdArgs.push_back(Elt: "-tune-cpu");
2303 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2304 }
2305}
2306
2307static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2308 size_t Index = Option.find(C: Delimiter);
2309 if (Index != StringRef::npos)
2310 Option = Option.substr(Start: 0, N: Index);
2311 return Option;
2312}
2313
2314static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2315 Opt = getOptionName(Option: Opt);
2316 if (CmdArgs.size() < 2)
2317 return;
2318
2319 for (auto It = std::next(x: CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2320 StringRef Option = *It;
2321 if (!Option.starts_with(Prefix: Opt))
2322 continue;
2323 Option = getOptionName(Option);
2324 if (Option != Opt)
2325 continue;
2326 if (StringRef(*(It - 1)) != "-mllvm")
2327 continue;
2328
2329 It = CmdArgs.erase(CI: It);
2330 CmdArgs.erase(CI: It - 1);
2331 return;
2332 }
2333}
2334
2335static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2336 checkAndRemoveLLVMArg(CmdArgs, Opt: A);
2337 CmdArgs.push_back(Elt: "-mllvm");
2338 CmdArgs.push_back(Elt: A);
2339}
2340
2341static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2342 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2343 StringRef Option = *It;
2344 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2345 It = CmdArgs.erase(CI: It);
2346 Ie = CmdArgs.end();
2347 } else {
2348 ++It;
2349 }
2350 }
2351
2352 CmdArgs.push_back(Elt: "-menable-no-infs");
2353 CmdArgs.push_back(Elt: "-menable-no-nans");
2354 CmdArgs.push_back(Elt: "-fapprox-func");
2355 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
2356 CmdArgs.push_back(Elt: "-fno-signed-zeros");
2357 CmdArgs.push_back(Elt: "-mreassociate");
2358 CmdArgs.push_back(Elt: "-freciprocal-math");
2359 CmdArgs.push_back(Elt: "-ffp-contract=fast");
2360 CmdArgs.push_back(Elt: "-ffast-math");
2361 CmdArgs.push_back(Elt: "-ffinite-math-only");
2362 CmdArgs.push_back(Elt: "-D__FAST_MATH__");
2363 pushBackLLVMArg(CmdArgs, A: "-fast-math=true");
2364}
2365
2366static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2367 ArgStringList &CmdArgs) {
2368 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2369 bool HasHVX = HvxVerOpt.has_value();
2370 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2371 if (!Args.hasArg(Ids: options::OPT_mhexagon_hvx, Ids: options::OPT_mhexagon_hvx_EQ,
2372 Ids: options::OPT_mhexagon_hvx_ieee_fp) ||
2373 !HasHVX)
2374 return;
2375 unsigned HvxVerNum = 0;
2376 if (StringRef(HvxVer).drop_front(N: 1).getAsInteger(Radix: 10, Result&: HvxVerNum))
2377 HvxVerNum = 0;
2378
2379 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2380 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2381 Ids: options::OPT_mhexagon_hvx_ieee_fp)) {
2382 if (HvxVerNum >= 79) {
2383 if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2384 const char *Mode =
2385 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2386 .Case(S: "strict-ieee", Value: "-hexagon-qfloat-mode=strict-ieee")
2387 .Case(S: "ieee", Value: "-hexagon-qfloat-mode=ieee")
2388 .Case(S: "lossy", Value: "-hexagon-qfloat-mode=lossy")
2389 .Case(S: "legacy", Value: "-hexagon-qfloat-mode=legacy")
2390 .Default(Value: nullptr);
2391 if (!Mode) {
2392 D.Diag(DiagID: diag::err_drv_invalid_value)
2393 << A->getAsString(Args) << A->getValue();
2394 return;
2395 }
2396 pushBackLLVMArg(CmdArgs, A: Mode);
2397 if (strcmp(s1: Mode, s2: "-hexagon-qfloat-mode=lossy") == 0)
2398 addQFloatLossyFastMathArgs(CmdArgs);
2399 } else if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat)) {
2400 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=lossy");
2401 addQFloatLossyFastMathArgs(CmdArgs);
2402 } else {
2403 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=ieee");
2404 }
2405 } else {
2406 if (Arg *QFloatArg = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2407 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2408 Ids: options::OPT_mno_hexagon_hvx_qfloat);
2409 QFloatArg &&
2410 QFloatArg->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2411 D.Diag(DiagID: diag::warn_drv_unsupported_option_part_for_target)
2412 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2413 << (std::string("HVX ") + HvxVer +
2414 "; falling back to legacy qfloat mode");
2415 }
2416 }
2417 }
2418}
2419
2420void Clang::AddHexagonTargetArgs(const ArgList &Args,
2421 ArgStringList &CmdArgs) const {
2422 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2423 CmdArgs.push_back(Elt: "-Wreturn-type");
2424
2425 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2426 CmdArgs.push_back(Elt: "-mllvm");
2427 CmdArgs.push_back(
2428 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2429 }
2430
2431 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2432 CmdArgs.push_back(Elt: "-fshort-enums");
2433 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2434 CmdArgs.push_back(Elt: "-mllvm");
2435 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2436 }
2437 CmdArgs.push_back(Elt: "-mllvm");
2438 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2439
2440 addQFloatBackendArg(D: getToolChain().getDriver(), Args, CmdArgs);
2441}
2442
2443void Clang::AddLanaiTargetArgs(const ArgList &Args,
2444 ArgStringList &CmdArgs) const {
2445 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2446 StringRef CPUName = A->getValue();
2447
2448 CmdArgs.push_back(Elt: "-target-cpu");
2449 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2450 }
2451 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2452 StringRef Value = A->getValue();
2453 // Only support mregparm=4 to support old usage. Report error for all other
2454 // cases.
2455 int Mregparm;
2456 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2457 if (Mregparm != 4) {
2458 getToolChain().getDriver().Diag(
2459 DiagID: diag::err_drv_unsupported_option_argument)
2460 << A->getSpelling() << Value;
2461 }
2462 }
2463 }
2464}
2465
2466void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2467 ArgStringList &CmdArgs) const {
2468 // Default to "hidden" visibility.
2469 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2470 Ids: options::OPT_fvisibility_ms_compat))
2471 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2472}
2473
2474void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2475 // Floating point operations and argument passing are hard.
2476 CmdArgs.push_back(Elt: "-mfloat-abi");
2477 CmdArgs.push_back(Elt: "hard");
2478}
2479
2480void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2481 StringRef Target, const InputInfo &Output,
2482 const InputInfo &Input, const ArgList &Args) const {
2483 // If this is a dry run, do not create the compilation database file.
2484 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2485 return;
2486
2487 using llvm::yaml::escape;
2488 const Driver &D = getToolChain().getDriver();
2489
2490 if (!CompilationDatabase) {
2491 std::error_code EC;
2492 auto File = std::make_unique<llvm::raw_fd_ostream>(
2493 args&: Filename, args&: EC,
2494 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2495 if (EC) {
2496 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2497 << EC.message();
2498 return;
2499 }
2500 CompilationDatabase = std::move(File);
2501 }
2502 auto &CDB = *CompilationDatabase;
2503 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2504 if (!CWD)
2505 CWD = ".";
2506 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2507 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2508 if (Output.isFilename())
2509 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2510 CDB << ", \"arguments\": [\"" << escape(Input: D.DriverExecutable) << "\"";
2511 SmallString<128> Buf;
2512 Buf = "-x";
2513 Buf += types::getTypeName(Id: Input.getType());
2514 CDB << ", \"" << escape(Input: Buf) << "\"";
2515 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2516 Buf = "--sysroot=";
2517 Buf += D.SysRoot;
2518 CDB << ", \"" << escape(Input: Buf) << "\"";
2519 }
2520 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2521 if (Output.isFilename())
2522 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2523 for (auto &A: Args) {
2524 auto &O = A->getOption();
2525 // Skip language selection, which is positional.
2526 if (O.getID() == options::OPT_x)
2527 continue;
2528 // Skip writing dependency output and the compilation database itself.
2529 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2530 continue;
2531 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2532 continue;
2533 // Skip inputs.
2534 if (O.getKind() == Option::InputClass)
2535 continue;
2536 // Skip output.
2537 if (O.getID() == options::OPT_o)
2538 continue;
2539 // All other arguments are quoted and appended.
2540 ArgStringList ASL;
2541 A->render(Args, Output&: ASL);
2542 for (auto &it: ASL)
2543 CDB << ", \"" << escape(Input: it) << "\"";
2544 }
2545 Buf = "--target=";
2546 Buf += Target;
2547 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2548}
2549
2550void Clang::DumpCompilationDatabaseFragmentToDir(
2551 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2552 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2553 // If this is a dry run, do not create the compilation database file.
2554 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2555 return;
2556
2557 if (CompilationDatabase)
2558 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2559
2560 SmallString<256> Path = Dir;
2561 const auto &Driver = C.getDriver();
2562 Driver.getVFS().makeAbsolute(Path);
2563 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2564 if (Err) {
2565 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2566 return;
2567 }
2568
2569 llvm::sys::path::append(
2570 path&: Path,
2571 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2572 int FD;
2573 SmallString<256> TempPath;
2574 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2575 Flags: llvm::sys::fs::OF_Text);
2576 if (Err) {
2577 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2578 return;
2579 }
2580 CompilationDatabase =
2581 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2582 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2583}
2584
2585static bool CheckARMImplicitITArg(StringRef Value) {
2586 return Value == "always" || Value == "never" || Value == "arm" ||
2587 Value == "thumb";
2588}
2589
2590static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2591 StringRef Value) {
2592 CmdArgs.push_back(Elt: "-mllvm");
2593 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2594}
2595
2596static void CollectArgsForIntegratedAssembler(Compilation &C,
2597 const ArgList &Args,
2598 ArgStringList &CmdArgs,
2599 const Driver &D) {
2600 // Default to -mno-relax-all.
2601 //
2602 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2603 // cannot be done by assembler branch relaxation as it needs a free temporary
2604 // register. Because of this, branch relaxation is handled by a MachineIR pass
2605 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2606 // MachineIR branch relaxation inaccurate and it will miss cases where an
2607 // indirect branch is necessary.
2608 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2609 Neg: options::OPT_mno_relax_all);
2610
2611 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mincremental_linker_compatible,
2612 Ids: options::OPT_mno_incremental_linker_compatible);
2613
2614 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2615
2616 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2617 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2618
2619 // If you add more args here, also add them to the block below that
2620 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2621
2622 // When passing -I arguments to the assembler we sometimes need to
2623 // unconditionally take the next argument. For example, when parsing
2624 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2625 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2626 // arg after parsing the '-I' arg.
2627 bool TakeNextArg = false;
2628
2629 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2630 bool IsELF = Triple.isOSBinFormatELF();
2631 bool Crel = false, ExperimentalCrel = false;
2632 StringRef RelocSectionSym;
2633 bool SFrame = false, ExperimentalSFrame = false;
2634 bool ImplicitMapSyms = false;
2635 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2636 bool UseNoExecStack = false;
2637 bool Msa = false;
2638 const char *MipsTargetFeature = nullptr;
2639 llvm::SmallVector<const char *> SparcTargetFeatures;
2640 StringRef ImplicitIt;
2641 for (const Arg *A :
2642 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2643 Ids: options::OPT_mimplicit_it_EQ)) {
2644 A->claim();
2645
2646 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2647 switch (C.getDefaultToolChain().getArch()) {
2648 case llvm::Triple::arm:
2649 case llvm::Triple::armeb:
2650 case llvm::Triple::thumb:
2651 case llvm::Triple::thumbeb:
2652 // Only store the value; the last value set takes effect.
2653 ImplicitIt = A->getValue();
2654 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2655 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2656 << A->getSpelling() << ImplicitIt;
2657 continue;
2658 default:
2659 break;
2660 }
2661 }
2662
2663 for (StringRef Value : A->getValues()) {
2664 if (TakeNextArg) {
2665 CmdArgs.push_back(Elt: Value.data());
2666 TakeNextArg = false;
2667 continue;
2668 }
2669
2670 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2671 Value == "-mbig-obj")
2672 continue; // LLVM handles bigobj automatically
2673
2674 auto Equal = Value.split(Separator: '=');
2675 auto checkArg = [&](bool ValidTarget,
2676 std::initializer_list<const char *> Set) {
2677 if (!ValidTarget) {
2678 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2679 << (Twine("-Wa,") + Equal.first + "=").str()
2680 << Triple.getTriple();
2681 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2682 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2683 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2684 }
2685 };
2686 switch (C.getDefaultToolChain().getArch()) {
2687 default:
2688 break;
2689 case llvm::Triple::x86:
2690 case llvm::Triple::x86_64:
2691 if (Equal.first == "-mrelax-relocations" ||
2692 Equal.first == "--mrelax-relocations") {
2693 UseRelaxRelocations = Equal.second == "yes";
2694 checkArg(IsELF, {"yes", "no"});
2695 continue;
2696 }
2697 if (Value == "-msse2avx") {
2698 CmdArgs.push_back(Elt: "-msse2avx");
2699 continue;
2700 }
2701 break;
2702 case llvm::Triple::wasm32:
2703 case llvm::Triple::wasm64:
2704 if (Value == "--no-type-check") {
2705 CmdArgs.push_back(Elt: "-mno-type-check");
2706 continue;
2707 }
2708 break;
2709 case llvm::Triple::thumb:
2710 case llvm::Triple::thumbeb:
2711 case llvm::Triple::arm:
2712 case llvm::Triple::armeb:
2713 if (Equal.first == "-mimplicit-it") {
2714 // Only store the value; the last value set takes effect.
2715 ImplicitIt = Equal.second;
2716 checkArg(true, {"always", "never", "arm", "thumb"});
2717 continue;
2718 }
2719 if (Value == "-mthumb")
2720 // -mthumb has already been processed in ComputeLLVMTriple()
2721 // recognize but skip over here.
2722 continue;
2723 break;
2724 case llvm::Triple::aarch64:
2725 case llvm::Triple::aarch64_be:
2726 case llvm::Triple::aarch64_32:
2727 if (Equal.first == "-mmapsyms") {
2728 ImplicitMapSyms = Equal.second == "implicit";
2729 checkArg(IsELF, {"default", "implicit"});
2730 continue;
2731 }
2732 break;
2733 case llvm::Triple::mips:
2734 case llvm::Triple::mipsel:
2735 case llvm::Triple::mips64:
2736 case llvm::Triple::mips64el:
2737 if (Value == "--trap") {
2738 CmdArgs.push_back(Elt: "-target-feature");
2739 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2740 continue;
2741 }
2742 if (Value == "--break") {
2743 CmdArgs.push_back(Elt: "-target-feature");
2744 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2745 continue;
2746 }
2747 if (Value.starts_with(Prefix: "-msoft-float")) {
2748 CmdArgs.push_back(Elt: "-target-feature");
2749 CmdArgs.push_back(Elt: "+soft-float");
2750 continue;
2751 }
2752 if (Value.starts_with(Prefix: "-mhard-float")) {
2753 CmdArgs.push_back(Elt: "-target-feature");
2754 CmdArgs.push_back(Elt: "-soft-float");
2755 continue;
2756 }
2757 if (Value == "-mmsa") {
2758 Msa = true;
2759 continue;
2760 }
2761 if (Value == "-mno-msa") {
2762 Msa = false;
2763 continue;
2764 }
2765 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2766 .Case(S: "-mips1", Value: "+mips1")
2767 .Case(S: "-mips2", Value: "+mips2")
2768 .Case(S: "-mips3", Value: "+mips3")
2769 .Case(S: "-mips4", Value: "+mips4")
2770 .Case(S: "-mips5", Value: "+mips5")
2771 .Case(S: "-mips32", Value: "+mips32")
2772 .Case(S: "-mips32r2", Value: "+mips32r2")
2773 .Case(S: "-mips32r3", Value: "+mips32r3")
2774 .Case(S: "-mips32r5", Value: "+mips32r5")
2775 .Case(S: "-mips32r6", Value: "+mips32r6")
2776 .Case(S: "-mips64", Value: "+mips64")
2777 .Case(S: "-mips64r2", Value: "+mips64r2")
2778 .Case(S: "-mips64r3", Value: "+mips64r3")
2779 .Case(S: "-mips64r5", Value: "+mips64r5")
2780 .Case(S: "-mips64r6", Value: "+mips64r6")
2781 .Default(Value: nullptr);
2782 if (MipsTargetFeature)
2783 continue;
2784 break;
2785
2786 case llvm::Triple::sparc:
2787 case llvm::Triple::sparcel:
2788 case llvm::Triple::sparcv9:
2789 if (Value == "--undeclared-regs") {
2790 // LLVM already allows undeclared use of G registers, so this option
2791 // becomes a no-op. This solely exists for GNU compatibility.
2792 // TODO implement --no-undeclared-regs
2793 continue;
2794 }
2795 SparcTargetFeatures =
2796 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2797 .Case(S: "-Av8", Value: {"-v8plus"})
2798 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2799 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2800 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2801 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2802 .Case(S: "-Av9", Value: {"+v9"})
2803 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2804 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2805 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2806 .Default(Value: {});
2807 if (!SparcTargetFeatures.empty())
2808 continue;
2809 break;
2810 }
2811
2812 if (Value == "-force_cpusubtype_ALL") {
2813 // Do nothing, this is the default and we don't support anything else.
2814 } else if (Value == "-L") {
2815 CmdArgs.push_back(Elt: "-msave-temp-labels");
2816 } else if (Value == "--fatal-warnings") {
2817 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2818 } else if (Value == "--no-warn" || Value == "-W") {
2819 CmdArgs.push_back(Elt: "-massembler-no-warn");
2820 } else if (Value == "--noexecstack") {
2821 UseNoExecStack = true;
2822 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2823 Value.starts_with(Prefix: "--compress-debug-sections") ||
2824 Value == "-nocompress-debug-sections" ||
2825 Value == "--nocompress-debug-sections") {
2826 CmdArgs.push_back(Elt: Value.data());
2827 } else if (Value == "--crel") {
2828 Crel = true;
2829 } else if (Value == "--no-crel") {
2830 Crel = false;
2831 } else if (Value == "--allow-experimental-crel") {
2832 ExperimentalCrel = true;
2833 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2834 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2835 } else if (Value.starts_with(Prefix: "-I")) {
2836 CmdArgs.push_back(Elt: Value.data());
2837 // We need to consume the next argument if the current arg is a plain
2838 // -I. The next arg will be the include directory.
2839 if (Value == "-I")
2840 TakeNextArg = true;
2841 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2842 // "-gdwarf-N" options are not cc1as options.
2843 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2844 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2845 CmdArgs.push_back(Elt: Value.data());
2846 } else {
2847 RenderDebugEnablingArgs(Args, CmdArgs,
2848 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2849 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2850 }
2851 } else if (Value == "--gsframe") {
2852 SFrame = true;
2853 } else if (Value == "--allow-experimental-sframe") {
2854 ExperimentalSFrame = true;
2855 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2856 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2857 // Do nothing, we'll validate it later.
2858 } else if (Value == "-defsym" || Value == "--defsym") {
2859 if (A->getNumValues() != 2) {
2860 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2861 break;
2862 }
2863 const char *S = A->getValue(N: 1);
2864 auto Pair = StringRef(S).split(Separator: '=');
2865 auto Sym = Pair.first;
2866 auto SVal = Pair.second;
2867
2868 if (Sym.empty() || SVal.empty()) {
2869 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2870 break;
2871 }
2872 int64_t IVal;
2873 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2874 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2875 break;
2876 }
2877 CmdArgs.push_back(Elt: "--defsym");
2878 TakeNextArg = true;
2879 } else if (Value == "-fdebug-compilation-dir") {
2880 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2881 TakeNextArg = true;
2882 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2883 // The flag is a -Wa / -Xassembler argument and Options doesn't
2884 // parse the argument, so this isn't automatically aliased to
2885 // -fdebug-compilation-dir (without '=') here.
2886 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2887 CmdArgs.push_back(Elt: Value.data());
2888 } else if (Value == "--version") {
2889 D.PrintVersion(C, OS&: llvm::outs());
2890 } else {
2891 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2892 << A->getSpelling() << Value;
2893 }
2894 }
2895 }
2896 if (ImplicitIt.size())
2897 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2898 if (Crel) {
2899 if (!ExperimentalCrel)
2900 D.Diag(DiagID: diag::err_drv_experimental_crel);
2901 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2902 CmdArgs.push_back(Elt: "--crel");
2903 } else {
2904 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2905 << "-Wa,--crel" << D.getTargetTriple();
2906 }
2907 }
2908 if (!RelocSectionSym.empty()) {
2909 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2910 RelocSectionSym != "none")
2911 D.Diag(DiagID: diag::err_drv_invalid_value)
2912 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2913 << RelocSectionSym;
2914 else if (Triple.isOSBinFormatELF())
2915 CmdArgs.push_back(
2916 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2917 else
2918 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2919 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2920 }
2921 if (SFrame) {
2922 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2923 if (!ExperimentalSFrame)
2924 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2925 else
2926 CmdArgs.push_back(Elt: "--gsframe");
2927 } else {
2928 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2929 << "-Wa,--gsframe" << D.getTargetTriple();
2930 }
2931 }
2932 if (ImplicitMapSyms)
2933 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2934 if (Msa)
2935 CmdArgs.push_back(Elt: "-mmsa");
2936 if (!UseRelaxRelocations)
2937 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2938 if (UseNoExecStack)
2939 CmdArgs.push_back(Elt: "-mnoexecstack");
2940 if (MipsTargetFeature != nullptr) {
2941 CmdArgs.push_back(Elt: "-target-feature");
2942 CmdArgs.push_back(Elt: MipsTargetFeature);
2943 }
2944
2945 for (const char *Feature : SparcTargetFeatures) {
2946 CmdArgs.push_back(Elt: "-target-feature");
2947 CmdArgs.push_back(Elt: Feature);
2948 }
2949
2950 // forward -fembed-bitcode to assmebler
2951 if (C.getDriver().embedBitcodeEnabled() ||
2952 C.getDriver().embedBitcodeMarkerOnly())
2953 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2954
2955 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2956 CmdArgs.push_back(Elt: "-as-secure-log-file");
2957 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2958 }
2959}
2960
2961static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2962 bool OFastEnabled, const ArgList &Args,
2963 ArgStringList &CmdArgs,
2964 const JobAction &JA) {
2965 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2966 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2967 llvm::StringLiteral("SLEEF")};
2968 bool NoMathErrnoWasImpliedByVecLib = false;
2969 const Arg *VecLibArg = nullptr;
2970 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2971 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2972
2973 // Handle various floating point optimization flags, mapping them to the
2974 // appropriate LLVM code generation flags. This is complicated by several
2975 // "umbrella" flags, so we do this by stepping through the flags incrementally
2976 // adjusting what we think is enabled/disabled, then at the end setting the
2977 // LLVM flags based on the final state.
2978 bool HonorINFs = true;
2979 bool HonorNaNs = true;
2980 bool ApproxFunc = false;
2981 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2982 bool MathErrno = TC.IsMathErrnoDefault();
2983 bool AssociativeMath = false;
2984 bool ReciprocalMath = false;
2985 bool SignedZeros = true;
2986 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2987 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2988 // overriden by ffp-exception-behavior?
2989 bool RoundingFPMath = false;
2990 // -ffp-model values: strict, fast, precise
2991 StringRef FPModel = "";
2992 // -ffp-exception-behavior options: strict, maytrap, ignore
2993 StringRef FPExceptionBehavior = "";
2994 // -ffp-eval-method options: double, extended, source
2995 StringRef FPEvalMethod = "";
2996 llvm::DenormalMode DenormalFPMath =
2997 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2998 llvm::DenormalMode DenormalFP32Math =
2999 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
3000
3001 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3002 // If one wasn't given by the user, don't pass it here.
3003 StringRef FPContract;
3004 StringRef LastSeenFfpContractOption;
3005 StringRef LastFpContractOverrideOption;
3006 bool SeenUnsafeMathModeOption = false;
3007 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
3008 !JA.isOffloading(OKind: Action::OFK_HIP))
3009 FPContract = "on";
3010 bool StrictFPModel = false;
3011 StringRef Float16ExcessPrecision = "";
3012 StringRef BFloat16ExcessPrecision = "";
3013 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
3014 std::string ComplexRangeStr;
3015 StringRef LastComplexRangeOption;
3016
3017 // Lambda to set fast-math options. This is also used by -ffp-model=fast
3018 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
3019 if (Aggressive) {
3020 HonorINFs = false;
3021 HonorNaNs = false;
3022 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3023 LastOpt&: LastComplexRangeOption, Range);
3024 } else {
3025 HonorINFs = true;
3026 HonorNaNs = true;
3027 setComplexRange(D, NewOpt: CallerOption,
3028 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
3029 LastOpt&: LastComplexRangeOption, Range);
3030 }
3031 MathErrno = false;
3032 AssociativeMath = true;
3033 ReciprocalMath = true;
3034 ApproxFunc = true;
3035 SignedZeros = false;
3036 TrappingMath = false;
3037 RoundingFPMath = false;
3038 FPExceptionBehavior = "";
3039 FPContract = "fast";
3040 SeenUnsafeMathModeOption = true;
3041 };
3042
3043 // Lambda to consolidate common handling for fp-contract
3044 auto restoreFPContractState = [&]() {
3045 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3046 // For other targets, if the state has been changed by one of the
3047 // unsafe-math umbrella options a subsequent -fno-fast-math or
3048 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3049 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3050 // option. If we have not seen an unsafe-math option or -ffp-contract,
3051 // we leave the FPContract state unchanged.
3052 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
3053 !JA.isOffloading(OKind: Action::OFK_HIP)) {
3054 if (LastSeenFfpContractOption != "")
3055 FPContract = LastSeenFfpContractOption;
3056 else if (SeenUnsafeMathModeOption)
3057 FPContract = "on";
3058 }
3059 // In this case, we're reverting to the last explicit fp-contract option
3060 // or the platform default
3061 LastFpContractOverrideOption = "";
3062 };
3063
3064 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
3065 CmdArgs.push_back(Elt: "-mlimit-float-precision");
3066 CmdArgs.push_back(Elt: A->getValue());
3067 }
3068
3069 for (const Arg *A : Args) {
3070 llvm::scope_exit CheckMathErrnoForVecLib(
3071 [&, MathErrnoBeforeArg = MathErrno] {
3072 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3073 ArgThatEnabledMathErrnoAfterVecLib = A;
3074 });
3075
3076 switch (A->getOption().getID()) {
3077 // If this isn't an FP option skip the claim below
3078 default: continue;
3079
3080 case options::OPT_fcx_limited_range:
3081 setComplexRange(D, NewOpt: A->getSpelling(),
3082 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3083 LastOpt&: LastComplexRangeOption, Range);
3084 break;
3085 case options::OPT_fno_cx_limited_range:
3086 setComplexRange(D, NewOpt: A->getSpelling(),
3087 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3088 LastOpt&: LastComplexRangeOption, Range);
3089 break;
3090 case options::OPT_fcx_fortran_rules:
3091 setComplexRange(D, NewOpt: A->getSpelling(),
3092 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
3093 LastOpt&: LastComplexRangeOption, Range);
3094 break;
3095 case options::OPT_fno_cx_fortran_rules:
3096 setComplexRange(D, NewOpt: A->getSpelling(),
3097 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3098 LastOpt&: LastComplexRangeOption, Range);
3099 break;
3100 case options::OPT_fcomplex_arithmetic_EQ: {
3101 LangOptions::ComplexRangeKind RangeVal;
3102 StringRef Val = A->getValue();
3103 if (Val == "full")
3104 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
3105 else if (Val == "improved")
3106 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
3107 else if (Val == "promoted")
3108 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
3109 else if (Val == "basic")
3110 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
3111 else {
3112 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3113 << A->getSpelling() << Val;
3114 break;
3115 }
3116 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
3117 LastOpt&: LastComplexRangeOption, Range);
3118 break;
3119 }
3120 case options::OPT_ffp_model_EQ: {
3121 // If -ffp-model= is seen, reset to fno-fast-math
3122 HonorINFs = true;
3123 HonorNaNs = true;
3124 ApproxFunc = false;
3125 // Turning *off* -ffast-math restores the toolchain default.
3126 MathErrno = TC.IsMathErrnoDefault();
3127 AssociativeMath = false;
3128 ReciprocalMath = false;
3129 SignedZeros = true;
3130
3131 StringRef Val = A->getValue();
3132 if (OFastEnabled && Val != "aggressive") {
3133 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3134 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3135 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
3136 break;
3137 }
3138 StrictFPModel = false;
3139 if (!FPModel.empty() && FPModel != Val)
3140 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3141 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
3142 << Args.MakeArgString(Str: "-ffp-model=" + Val);
3143 if (Val == "fast") {
3144 FPModel = Val;
3145 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
3146 // applyFastMath sets fp-contract="fast"
3147 LastFpContractOverrideOption = "-ffp-model=fast";
3148 } else if (Val == "aggressive") {
3149 FPModel = Val;
3150 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
3151 // applyFastMath sets fp-contract="fast"
3152 LastFpContractOverrideOption = "-ffp-model=aggressive";
3153 } else if (Val == "precise") {
3154 FPModel = Val;
3155 FPContract = "on";
3156 LastFpContractOverrideOption = "-ffp-model=precise";
3157 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3158 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3159 LastOpt&: LastComplexRangeOption, Range);
3160 } else if (Val == "strict") {
3161 StrictFPModel = true;
3162 FPExceptionBehavior = "strict";
3163 FPModel = Val;
3164 FPContract = "off";
3165 LastFpContractOverrideOption = "-ffp-model=strict";
3166 TrappingMath = true;
3167 RoundingFPMath = true;
3168 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3169 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3170 LastOpt&: LastComplexRangeOption, Range);
3171 } else
3172 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3173 << A->getSpelling() << Val;
3174 break;
3175 }
3176
3177 // Options controlling individual features
3178 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3179 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3180 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3181 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3182 case options::OPT_fapprox_func: ApproxFunc = true; break;
3183 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3184 case options::OPT_fmath_errno: MathErrno = true; break;
3185 case options::OPT_fno_math_errno: MathErrno = false; break;
3186 case options::OPT_fassociative_math: AssociativeMath = true; break;
3187 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3188 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3189 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3190 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3191 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3192 case options::OPT_ftrapping_math:
3193 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3194 FPExceptionBehavior != "strict")
3195 // Warn that previous value of option is overridden.
3196 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3197 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3198 FPExceptionBehavior)
3199 << "-ftrapping-math";
3200 TrappingMath = true;
3201 TrappingMathPresent = true;
3202 FPExceptionBehavior = "strict";
3203 break;
3204 case options::OPT_fveclib:
3205 VecLibArg = A;
3206 NoMathErrnoWasImpliedByVecLib =
3207 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3208 if (NoMathErrnoWasImpliedByVecLib)
3209 MathErrno = false;
3210 break;
3211 case options::OPT_fno_trapping_math:
3212 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3213 FPExceptionBehavior != "ignore")
3214 // Warn that previous value of option is overridden.
3215 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3216 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3217 FPExceptionBehavior)
3218 << "-fno-trapping-math";
3219 TrappingMath = false;
3220 TrappingMathPresent = true;
3221 FPExceptionBehavior = "ignore";
3222 break;
3223
3224 case options::OPT_frounding_math:
3225 RoundingFPMath = true;
3226 break;
3227
3228 case options::OPT_fno_rounding_math:
3229 RoundingFPMath = false;
3230 break;
3231
3232 case options::OPT_fdenormal_fp_math_EQ:
3233 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3234 DenormalFP32Math = DenormalFPMath;
3235 if (!DenormalFPMath.isValid()) {
3236 D.Diag(DiagID: diag::err_drv_invalid_value)
3237 << A->getAsString(Args) << A->getValue();
3238 }
3239 break;
3240
3241 case options::OPT_fdenormal_fp_math_f32_EQ:
3242 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3243 if (!DenormalFP32Math.isValid()) {
3244 D.Diag(DiagID: diag::err_drv_invalid_value)
3245 << A->getAsString(Args) << A->getValue();
3246 }
3247 break;
3248
3249 // Validate and pass through -ffp-contract option.
3250 case options::OPT_ffp_contract: {
3251 StringRef Val = A->getValue();
3252 if (Val == "fast" || Val == "on" || Val == "off" ||
3253 Val == "fast-honor-pragmas") {
3254 if (Val != FPContract && LastFpContractOverrideOption != "") {
3255 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3256 << LastFpContractOverrideOption
3257 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3258 }
3259
3260 FPContract = Val;
3261 LastSeenFfpContractOption = Val;
3262 LastFpContractOverrideOption = "";
3263 } else
3264 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3265 << A->getSpelling() << Val;
3266 break;
3267 }
3268
3269 // Validate and pass through -ffp-exception-behavior option.
3270 case options::OPT_ffp_exception_behavior_EQ: {
3271 StringRef Val = A->getValue();
3272 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3273 FPExceptionBehavior != Val)
3274 // Warn that previous value of option is overridden.
3275 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3276 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3277 FPExceptionBehavior)
3278 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3279 TrappingMath = TrappingMathPresent = false;
3280 if (Val == "ignore" || Val == "maytrap")
3281 FPExceptionBehavior = Val;
3282 else if (Val == "strict") {
3283 FPExceptionBehavior = Val;
3284 TrappingMath = TrappingMathPresent = true;
3285 } else
3286 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3287 << A->getSpelling() << Val;
3288 break;
3289 }
3290
3291 // Validate and pass through -ffp-eval-method option.
3292 case options::OPT_ffp_eval_method_EQ: {
3293 StringRef Val = A->getValue();
3294 if (Val == "double" || Val == "extended" || Val == "source")
3295 FPEvalMethod = Val;
3296 else
3297 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3298 << A->getSpelling() << Val;
3299 break;
3300 }
3301
3302 case options::OPT_fexcess_precision_EQ: {
3303 StringRef Val = A->getValue();
3304 const llvm::Triple::ArchType Arch = TC.getArch();
3305 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3306 if (Val == "standard" || Val == "fast")
3307 Float16ExcessPrecision = Val;
3308 // To make it GCC compatible, allow the value of "16" which
3309 // means disable excess precision, the same meaning than clang's
3310 // equivalent value "none".
3311 else if (Val == "16")
3312 Float16ExcessPrecision = "none";
3313 else
3314 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3315 << A->getSpelling() << Val;
3316 } else {
3317 if (!(Val == "standard" || Val == "fast"))
3318 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3319 << A->getSpelling() << Val;
3320 }
3321 BFloat16ExcessPrecision = Float16ExcessPrecision;
3322 break;
3323 }
3324 case options::OPT_ffinite_math_only:
3325 HonorINFs = false;
3326 HonorNaNs = false;
3327 break;
3328 case options::OPT_fno_finite_math_only:
3329 HonorINFs = true;
3330 HonorNaNs = true;
3331 break;
3332
3333 case options::OPT_funsafe_math_optimizations:
3334 AssociativeMath = true;
3335 ReciprocalMath = true;
3336 SignedZeros = false;
3337 ApproxFunc = true;
3338 TrappingMath = false;
3339 FPExceptionBehavior = "";
3340 FPContract = "fast";
3341 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3342 SeenUnsafeMathModeOption = true;
3343 break;
3344 case options::OPT_fno_unsafe_math_optimizations:
3345 AssociativeMath = false;
3346 ReciprocalMath = false;
3347 SignedZeros = true;
3348 ApproxFunc = false;
3349 restoreFPContractState();
3350 break;
3351
3352 case options::OPT_cl_fast_relaxed_math:
3353 applyFastMath(true, A->getSpelling());
3354 break;
3355
3356 case options::OPT_Ofast:
3357 // If -Ofast is the optimization level, then -ffast-math should be enabled
3358 if (!OFastEnabled)
3359 continue;
3360 [[fallthrough]];
3361 case options::OPT_ffast_math:
3362 applyFastMath(true, A->getSpelling());
3363 if (A->getOption().getID() == options::OPT_Ofast)
3364 LastFpContractOverrideOption = "-Ofast";
3365 else
3366 LastFpContractOverrideOption = "-ffast-math";
3367 break;
3368 case options::OPT_fno_fast_math:
3369 HonorINFs = true;
3370 HonorNaNs = true;
3371 // Turning on -ffast-math (with either flag) removes the need for
3372 // MathErrno. However, turning *off* -ffast-math merely restores the
3373 // toolchain default (which may be false).
3374 MathErrno = TC.IsMathErrnoDefault();
3375 AssociativeMath = false;
3376 ReciprocalMath = false;
3377 ApproxFunc = false;
3378 SignedZeros = true;
3379 restoreFPContractState();
3380 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3381 setComplexRange(D, NewOpt: A->getSpelling(),
3382 NewRange: LangOptions::ComplexRangeKind::CX_None,
3383 LastOpt&: LastComplexRangeOption, Range);
3384 else
3385 Range = LangOptions::ComplexRangeKind::CX_None;
3386 LastComplexRangeOption = "";
3387 LastFpContractOverrideOption = "";
3388 break;
3389 } // End switch (A->getOption().getID())
3390
3391 // The StrictFPModel local variable is needed to report warnings
3392 // in the way we intend. If -ffp-model=strict has been used, we
3393 // want to report a warning for the next option encountered that
3394 // takes us out of the settings described by fp-model=strict, but
3395 // we don't want to continue issuing warnings for other conflicting
3396 // options after that.
3397 if (StrictFPModel) {
3398 // If -ffp-model=strict has been specified on command line but
3399 // subsequent options conflict then emit warning diagnostic.
3400 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3401 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3402 FPContract == "off")
3403 // OK: Current Arg doesn't conflict with -ffp-model=strict
3404 ;
3405 else {
3406 StrictFPModel = false;
3407 FPModel = "";
3408 // The warning for -ffp-contract would have been reported by the
3409 // OPT_ffp_contract_EQ handler above. A special check here is needed
3410 // to avoid duplicating the warning.
3411 auto RHS = (A->getNumValues() == 0)
3412 ? A->getSpelling()
3413 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3414 if (A->getSpelling() != "-ffp-contract=") {
3415 if (RHS != "-ffp-model=strict")
3416 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3417 << "-ffp-model=strict" << RHS;
3418 }
3419 }
3420 }
3421
3422 // If we handled this option claim it
3423 A->claim();
3424 }
3425
3426 if (!HonorINFs)
3427 CmdArgs.push_back(Elt: "-menable-no-infs");
3428
3429 if (!HonorNaNs)
3430 CmdArgs.push_back(Elt: "-menable-no-nans");
3431
3432 if (ApproxFunc)
3433 CmdArgs.push_back(Elt: "-fapprox-func");
3434
3435 if (MathErrno) {
3436 CmdArgs.push_back(Elt: "-fmath-errno");
3437 if (NoMathErrnoWasImpliedByVecLib)
3438 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3439 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3440 << VecLibArg->getAsString(Args);
3441 }
3442
3443 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3444 !TrappingMath)
3445 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3446
3447 if (!SignedZeros)
3448 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3449
3450 if (AssociativeMath && !SignedZeros && !TrappingMath)
3451 CmdArgs.push_back(Elt: "-mreassociate");
3452
3453 if (ReciprocalMath)
3454 CmdArgs.push_back(Elt: "-freciprocal-math");
3455
3456 if (TrappingMath) {
3457 // FP Exception Behavior is also set to strict
3458 assert(FPExceptionBehavior == "strict");
3459 }
3460
3461 // The default is IEEE.
3462 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3463 llvm::SmallString<64> DenormFlag;
3464 llvm::raw_svector_ostream ArgStr(DenormFlag);
3465 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3466 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3467 }
3468
3469 // Add f32 specific denormal mode flag if it's different.
3470 if (DenormalFP32Math != DenormalFPMath) {
3471 llvm::SmallString<64> DenormFlag;
3472 llvm::raw_svector_ostream ArgStr(DenormFlag);
3473 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3474 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3475 }
3476
3477 if (!FPContract.empty())
3478 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3479
3480 if (RoundingFPMath)
3481 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3482 else
3483 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3484
3485 if (!FPExceptionBehavior.empty())
3486 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3487 FPExceptionBehavior));
3488
3489 if (!FPEvalMethod.empty())
3490 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3491
3492 if (!Float16ExcessPrecision.empty())
3493 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3494 Float16ExcessPrecision));
3495 if (!BFloat16ExcessPrecision.empty())
3496 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3497 BFloat16ExcessPrecision));
3498
3499 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3500 if (!Recip.empty())
3501 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3502
3503 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3504 // individual features enabled by -ffast-math instead of the option itself as
3505 // that's consistent with gcc's behaviour.
3506 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3507 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3508 CmdArgs.push_back(Elt: "-ffast-math");
3509
3510 // Handle __FINITE_MATH_ONLY__ similarly.
3511 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3512 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3513 // -menable-no-nans are set by the user.
3514 bool shouldAddFiniteMathOnly = false;
3515 if (!HonorINFs && !HonorNaNs) {
3516 shouldAddFiniteMathOnly = true;
3517 } else {
3518 bool InfValues = true;
3519 bool NanValues = true;
3520 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3521 StringRef ArgValue = Arg->getValue();
3522 if (ArgValue == "-menable-no-nans")
3523 NanValues = false;
3524 else if (ArgValue == "-menable-no-infs")
3525 InfValues = false;
3526 }
3527 if (!NanValues && !InfValues)
3528 shouldAddFiniteMathOnly = true;
3529 }
3530 if (shouldAddFiniteMathOnly) {
3531 CmdArgs.push_back(Elt: "-ffinite-math-only");
3532 }
3533 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3534 CmdArgs.push_back(Elt: "-mfpmath");
3535 CmdArgs.push_back(Elt: A->getValue());
3536 }
3537
3538 // Disable a codegen optimization for floating-point casts.
3539 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3540 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3541 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3542
3543 if (Range != LangOptions::ComplexRangeKind::CX_None)
3544 ComplexRangeStr = renderComplexRangeOption(Range);
3545 if (!ComplexRangeStr.empty()) {
3546 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3547 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3548 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3549 complexRangeKindToStr(Range)));
3550 }
3551 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3552 CmdArgs.push_back(Elt: "-fcx-limited-range");
3553 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3554 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3555 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3556 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3557 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3558 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3559}
3560
3561static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3562 const llvm::Triple &Triple,
3563 const InputInfo &Input) {
3564 // Add default argument set.
3565 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3566 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3567 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3568
3569 if (!Triple.isWindowsMSVCEnvironment()) {
3570 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3571 } else {
3572 // Enable "unix" checkers that also work on Windows.
3573 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3574 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3575 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3576 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3577 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3578 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3579 }
3580
3581 // Disable some unix checkers for PS4/PS5.
3582 if (Triple.isPS()) {
3583 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3584 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3585 }
3586
3587 if (Triple.isOSDarwin()) {
3588 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3589 CmdArgs.push_back(
3590 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3591 }
3592 else if (Triple.isOSFuchsia())
3593 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3594
3595 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3596
3597 if (types::isCXX(Id: Input.getType()))
3598 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3599
3600 if (!Triple.isPS()) {
3601 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3602 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3603 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3604 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3605 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3606 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3607 }
3608
3609 // Default nullability checks.
3610 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3611 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3612 }
3613
3614 // Set the output format. The default is plist, for (lame) historical reasons.
3615 CmdArgs.push_back(Elt: "-analyzer-output");
3616 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3617 CmdArgs.push_back(Elt: A->getValue());
3618 else
3619 CmdArgs.push_back(Elt: "plist");
3620
3621 // Disable the presentation of standard compiler warnings when using
3622 // --analyze. We only want to show static analyzer diagnostics or frontend
3623 // errors.
3624 CmdArgs.push_back(Elt: "-w");
3625
3626 // Add -Xanalyzer arguments when running as analyzer.
3627 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3628}
3629
3630static bool isValidSymbolName(StringRef S) {
3631 if (S.empty())
3632 return false;
3633
3634 if (std::isdigit(S[0]))
3635 return false;
3636
3637 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3638}
3639
3640static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3641 const ArgList &Args, ArgStringList &CmdArgs,
3642 bool KernelOrKext) {
3643 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3644
3645 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3646 // doesn't even have a stack!
3647 if (EffectiveTriple.isNVPTX())
3648 return;
3649
3650 // -stack-protector=0 is default.
3651 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3652 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3653 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3654
3655 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3656 Ids: options::OPT_fstack_protector_all,
3657 Ids: options::OPT_fstack_protector_strong,
3658 Ids: options::OPT_fstack_protector)) {
3659 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3660 StackProtectorLevel =
3661 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3662 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3663 StackProtectorLevel = LangOptions::SSPStrong;
3664 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3665 StackProtectorLevel = LangOptions::SSPReq;
3666
3667 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3668 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3669 << A->getSpelling() << EffectiveTriple.getTriple();
3670 StackProtectorLevel = DefaultStackProtectorLevel;
3671 }
3672 } else {
3673 StackProtectorLevel = DefaultStackProtectorLevel;
3674 }
3675
3676 if (StackProtectorLevel) {
3677 CmdArgs.push_back(Elt: "-stack-protector");
3678 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3679 }
3680
3681 // --param ssp-buffer-size=
3682 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3683 StringRef Str(A->getValue());
3684 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3685 if (StackProtectorLevel) {
3686 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3687 // FIXME: Verify the argument is a valid integer.
3688 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3689 }
3690 A->claim();
3691 }
3692 }
3693
3694 const std::string &TripleStr = EffectiveTriple.getTriple();
3695 StringRef GuardValue;
3696 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3697 GuardValue = A->getValue();
3698 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3699 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3700 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3701 !EffectiveTriple.isSystemZ())
3702 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3703 << A->getAsString(Args) << TripleStr;
3704 // z/OS only supports the tls mode.
3705 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3706 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3707 << A->getOption().getName() << GuardValue << "tls";
3708 return;
3709 }
3710 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3711 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3712 GuardValue != "tls" && GuardValue != "global") {
3713 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3714 << A->getOption().getName() << GuardValue << "tls global";
3715 return;
3716 }
3717 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3718 GuardValue == "tls") {
3719 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3720 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3721 << A->getAsString(Args);
3722 return;
3723 }
3724 // Check whether the target subarch supports the hardware TLS register
3725 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3726 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3727 << EffectiveTriple.getArchName();
3728 return;
3729 }
3730 // Check whether the user asked for something other than -mtp=cp15
3731 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3732 StringRef Value = A->getValue();
3733 if (Value != "cp15") {
3734 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3735 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3736 return;
3737 }
3738 }
3739 CmdArgs.push_back(Elt: "-target-feature");
3740 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3741 }
3742 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3743 GuardValue != "global") {
3744 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3745 << A->getOption().getName() << GuardValue << "sysreg global";
3746 return;
3747 }
3748 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3749 if (GuardValue != "tls" && GuardValue != "global") {
3750 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3751 << A->getOption().getName() << GuardValue << "tls global";
3752 return;
3753 }
3754 if (GuardValue == "tls") {
3755 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3756 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3757 << A->getAsString(Args);
3758 return;
3759 }
3760 }
3761 }
3762 A->render(Args, Output&: CmdArgs);
3763 }
3764
3765 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3766 StringRef Value = A->getValue();
3767 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3768 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3769 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3770 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3771 << A->getAsString(Args) << TripleStr;
3772 int Offset;
3773 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3774 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3775 return;
3776 }
3777 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3778 (Offset < 0 || Offset > 0xfffff)) {
3779 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3780 << A->getOption().getName() << Value;
3781 return;
3782 }
3783 A->render(Args, Output&: CmdArgs);
3784 }
3785
3786 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3787 StringRef Value = A->getValue();
3788 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3789 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3790 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3791 << A->getAsString(Args) << TripleStr;
3792 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3793 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3794 << A->getOption().getName() << Value << "fs gs";
3795 return;
3796 }
3797 if (EffectiveTriple.isAArch64() &&
3798 llvm::StringSwitch<bool>(Value)
3799 .Cases(CaseStrings: {"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3800 "tpidr_el2", "far_el1", "far_el2"},
3801 Value: false)
3802 .Default(Value: true)) {
3803 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3804 << A->getOption().getName() << Value
3805 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3806 return;
3807 }
3808 if (EffectiveTriple.isRISCV() && Value != "tp") {
3809 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3810 << A->getOption().getName() << Value << "tp";
3811 return;
3812 }
3813 if (EffectiveTriple.isPPC64() && Value != "r13") {
3814 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3815 << A->getOption().getName() << Value << "r13";
3816 return;
3817 }
3818 if (EffectiveTriple.isPPC32() && Value != "r2") {
3819 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3820 << A->getOption().getName() << Value << "r2";
3821 return;
3822 }
3823 A->render(Args, Output&: CmdArgs);
3824 }
3825
3826 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3827 StringRef Value = A->getValue();
3828 if (!isValidSymbolName(S: Value)) {
3829 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3830 << A->getOption().getName() << "legal symbol name";
3831 return;
3832 }
3833 A->render(Args, Output&: CmdArgs);
3834 }
3835
3836 if (Arg *A =
3837 Args.getLastArg(Ids: options::OPT_mstack_protector_guard_value_width_EQ)) {
3838 if (!EffectiveTriple.isAArch64())
3839 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3840 << A->getAsString(Args) << TripleStr;
3841 StringRef Value = A->getValue();
3842 unsigned Width;
3843 if (Value.getAsInteger(Radix: 10, Result&: Width)) {
3844 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3845 return;
3846 }
3847 if (Width != 4 && Width != 8) {
3848 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3849 << A->getOption().getName() << Value;
3850 }
3851 }
3852 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstackprotector_guard_record)) {
3853 if (!EffectiveTriple.isSystemZ()) {
3854 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3855 << A->getAsString(Args) << TripleStr;
3856 return;
3857 }
3858 if (GuardValue != "global") {
3859 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3860 << "-mstack-protector-guard-record"
3861 << "-mstack-protector-guard=global";
3862 return;
3863 }
3864 A->render(Args, Output&: CmdArgs);
3865 }
3866}
3867
3868static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3869 ArgStringList &CmdArgs) {
3870 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3871
3872 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3873 !EffectiveTriple.isOSFuchsia())
3874 return;
3875
3876 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3877 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3878 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3879 return;
3880
3881 if (Args.hasFlag(Pos: options::OPT_fstack_clash_protection,
3882 Neg: options::OPT_fno_stack_clash_protection,
3883 Default: EffectiveTriple.isAndroid()))
3884 CmdArgs.push_back(Elt: "-fstack-clash-protection");
3885}
3886
3887static void RenderTrivialAutoVarInitOptions(const Driver &D,
3888 const ToolChain &TC,
3889 const ArgList &Args,
3890 ArgStringList &CmdArgs) {
3891 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3892 StringRef TrivialAutoVarInit = "";
3893
3894 for (const Arg *A : Args) {
3895 switch (A->getOption().getID()) {
3896 default:
3897 continue;
3898 case options::OPT_ftrivial_auto_var_init: {
3899 A->claim();
3900 StringRef Val = A->getValue();
3901 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3902 TrivialAutoVarInit = Val;
3903 else
3904 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3905 << A->getSpelling() << Val;
3906 break;
3907 }
3908 }
3909 }
3910
3911 if (TrivialAutoVarInit.empty())
3912 switch (DefaultTrivialAutoVarInit) {
3913 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3914 break;
3915 case LangOptions::TrivialAutoVarInitKind::Pattern:
3916 TrivialAutoVarInit = "pattern";
3917 break;
3918 case LangOptions::TrivialAutoVarInitKind::Zero:
3919 TrivialAutoVarInit = "zero";
3920 break;
3921 }
3922
3923 if (!TrivialAutoVarInit.empty()) {
3924 CmdArgs.push_back(
3925 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3926 }
3927
3928 if (Arg *A =
3929 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3930 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3931 StringRef(
3932 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3933 "uninitialized")
3934 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3935 A->claim();
3936 StringRef Val = A->getValue();
3937 if (std::stoi(str: Val.str()) <= 0)
3938 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3939 CmdArgs.push_back(
3940 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3941 }
3942
3943 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3944 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3945 StringRef(
3946 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3947 "uninitialized")
3948 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3949 A->claim();
3950 StringRef Val = A->getValue();
3951 if (std::stoi(str: Val.str()) <= 0)
3952 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3953 CmdArgs.push_back(
3954 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3955 }
3956}
3957
3958static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3959 types::ID InputType) {
3960 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3961 // for denormal flushing handling based on the target.
3962 const unsigned ForwardedArguments[] = {
3963 options::OPT_cl_opt_disable,
3964 options::OPT_cl_strict_aliasing,
3965 options::OPT_cl_single_precision_constant,
3966 options::OPT_cl_finite_math_only,
3967 options::OPT_cl_kernel_arg_info,
3968 options::OPT_cl_unsafe_math_optimizations,
3969 options::OPT_cl_fast_relaxed_math,
3970 options::OPT_cl_mad_enable,
3971 options::OPT_cl_no_signed_zeros,
3972 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3973 options::OPT_cl_uniform_work_group_size
3974 };
3975
3976 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3977 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3978 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3979 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3980 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3981 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3982 }
3983
3984 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3985 CmdArgs.push_back(Elt: "-menable-no-infs");
3986 CmdArgs.push_back(Elt: "-menable-no-nans");
3987 }
3988
3989 for (const auto &Arg : ForwardedArguments)
3990 if (const auto *A = Args.getLastArg(Ids: Arg))
3991 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3992
3993 // Only add the default headers if we are compiling OpenCL sources.
3994 if ((types::isOpenCL(Id: InputType) ||
3995 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3996 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3997 CmdArgs.push_back(Elt: "-finclude-default-header");
3998 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3999 }
4000}
4001
4002static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
4003 ArgStringList &CmdArgs, types::ID InputType) {
4004 const unsigned ForwardedArguments[] = {
4005 options::OPT_hlsl_all_resources_bound,
4006 options::OPT_dxil_validator_version,
4007 options::OPT_res_may_alias,
4008 options::OPT_D,
4009 options::OPT_I,
4010 options::OPT_O,
4011 options::OPT_emit_llvm,
4012 options::OPT_emit_obj,
4013 options::OPT_disable_llvm_passes,
4014 options::OPT_fnative_half_type,
4015 options::OPT_fnative_int16_type,
4016 options::OPT_fmatrix_memory_layout_EQ,
4017 options::OPT_hlsl_entrypoint,
4018 options::OPT_fdx_rootsignature_define,
4019 options::OPT_fdx_rootsignature_version,
4020 options::OPT_fdx_semantic_signature_packing_mode_EQ,
4021 options::OPT_fhlsl_spv_use_unknown_image_format,
4022 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
4023 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
4024 options::OPT_fhlsl_spv_preserve_interface};
4025 if (!types::isHLSL(Id: InputType))
4026 return;
4027 for (const auto &Arg : ForwardedArguments)
4028 if (const auto *A = Args.getLastArg(Ids: Arg))
4029 A->renderAsInput(Args, Output&: CmdArgs);
4030 // Add the default headers if dxc_no_stdinc is not set.
4031 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
4032 !Args.hasArg(Ids: options::OPT_nostdinc))
4033 CmdArgs.push_back(Elt: "-finclude-default-header");
4034
4035 if (Args.hasArg(Ids: options::OPT_dxc_Zss)) {
4036 if (Args.hasArg(Ids: options::OPT_dxc_Zsb))
4037 D.Diag(DiagID: diag::err_drv_dxc_invalid_shader_hash);
4038 CmdArgs.push_back(Elt: "-mllvm");
4039 CmdArgs.push_back(Elt: "-dx-Zss");
4040 }
4041 if (Arg *A = Args.getLastArg(Ids: options::OPT_dxc_Zsb))
4042 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4043 if (Args.hasArg(Ids: options::OPT_dxc_source_in_debug_module)) {
4044 CmdArgs.push_back(Elt: "-mllvm");
4045 CmdArgs.push_back(Elt: "--dx-source-in-debug-module");
4046 }
4047 if (Args.hasArg(Ids: options::OPT_dxc_Qstrip_debug)) {
4048 CmdArgs.push_back(Elt: "-mllvm");
4049 CmdArgs.push_back(Elt: "--dx-strip-debug");
4050 }
4051 if (Args.hasArg(Ids: options::OPT_dxc_Qpdb_in_private)) {
4052 CmdArgs.push_back(Elt: "-mllvm");
4053 CmdArgs.push_back(Elt: "--dx-pdb-in-private");
4054 }
4055}
4056
4057static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4058 ArgStringList &CmdArgs, types::ID InputType) {
4059 if (!Args.hasArg(Ids: options::OPT_fopenacc))
4060 return;
4061
4062 CmdArgs.push_back(Elt: "-fopenacc");
4063}
4064
4065static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4066 const ArgList &Args, ArgStringList &CmdArgs) {
4067 // -fbuiltin is default unless -mkernel is used.
4068 bool UseBuiltins =
4069 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
4070 Default: !Args.hasArg(Ids: options::OPT_mkernel));
4071 if (!UseBuiltins)
4072 CmdArgs.push_back(Elt: "-fno-builtin");
4073
4074 // -ffreestanding implies -fno-builtin.
4075 if (Args.hasArg(Ids: options::OPT_ffreestanding))
4076 UseBuiltins = false;
4077
4078 // Process the -fno-builtin-* options.
4079 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
4080 A->claim();
4081
4082 // If -fno-builtin is specified, then there's no need to pass the option to
4083 // the frontend.
4084 if (UseBuiltins)
4085 A->render(Args, Output&: CmdArgs);
4086 }
4087}
4088
4089bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
4090 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
4091 Twine Path{Str};
4092 Path.toVector(Out&: Result);
4093 return Path.getSingleStringRef() != "";
4094 }
4095 if (llvm::sys::path::cache_directory(result&: Result)) {
4096 llvm::sys::path::append(path&: Result, a: "clang");
4097 llvm::sys::path::append(path&: Result, a: "ModuleCache");
4098 return true;
4099 }
4100 return false;
4101}
4102
4103llvm::SmallString<256>
4104clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
4105 const char *BaseInput) {
4106 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
4107 return StringRef(ModuleOutputEQ->getValue());
4108
4109 SmallString<256> OutputPath;
4110 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
4111 FinalOutput && Args.hasArg(Ids: options::OPT_c))
4112 OutputPath = FinalOutput->getValue();
4113 else {
4114 llvm::sys::fs::current_path(result&: OutputPath);
4115 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
4116 }
4117
4118 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
4119 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
4120 return OutputPath;
4121}
4122
4123static bool RenderModulesOptions(Compilation &C, const Driver &D,
4124 const ArgList &Args, const InputInfo &Input,
4125 const InputInfo &Output, bool HaveStd20,
4126 ArgStringList &CmdArgs) {
4127 const bool IsCXX = types::isCXX(Id: Input.getType());
4128 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4129 bool HaveModules = HaveStdCXXModules;
4130
4131 // -fmodules enables the use of precompiled modules (off by default).
4132 // Users can pass -fno-cxx-modules to turn off modules support for
4133 // C++/Objective-C++ programs.
4134 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
4135 Neg: options::OPT_fno_cxx_modules, Default: true);
4136 bool HaveClangModules = false;
4137 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
4138 if (AllowedInCXX || !IsCXX) {
4139 CmdArgs.push_back(Elt: "-fmodules");
4140 HaveClangModules = true;
4141 }
4142 }
4143
4144 HaveModules |= HaveClangModules;
4145
4146 if (HaveModules && !AllowedInCXX)
4147 CmdArgs.push_back(Elt: "-fno-cxx-modules");
4148
4149 // -fmodule-maps enables implicit reading of module map files. By default,
4150 // this is enabled if we are using Clang's flavor of precompiled modules.
4151 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
4152 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
4153 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
4154
4155 // -fmodules-decluse checks that modules used are declared so (off by default)
4156 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
4157 Neg: options::OPT_fno_modules_decluse);
4158
4159 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4160 // all #included headers are part of modules.
4161 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
4162 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
4163 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
4164
4165 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
4166 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
4167
4168 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4169 bool ImplicitModules = false;
4170 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
4171 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
4172 if (HaveModules)
4173 CmdArgs.push_back(Elt: "-fno-implicit-modules");
4174 } else if (HaveModules) {
4175 ImplicitModules = true;
4176 // -fmodule-cache-path specifies where our implicitly-built module files
4177 // should be written.
4178 SmallString<128> Path;
4179 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
4180 Path = A->getValue();
4181
4182 bool HasPath = true;
4183 if (C.isForDiagnostics()) {
4184 // When generating crash reports, we want to emit the modules along with
4185 // the reproduction sources, so we ignore any provided module path.
4186 Path = Output.getFilename();
4187 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
4188 llvm::sys::path::append(path&: Path, a: "modules");
4189 } else if (Path.empty()) {
4190 // No module path was provided: use the default.
4191 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
4192 }
4193
4194 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4195 // That being said, that failure is unlikely and not caching is harmless.
4196 if (HasPath) {
4197 const char Arg[] = "-fmodules-cache-path=";
4198 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
4199 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
4200 }
4201
4202 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
4203 }
4204
4205 if (HaveModules) {
4206 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
4207 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
4208 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
4209 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
4210 Neg: options::OPT_fno_modules_validate_input_files_content,
4211 Default: false))
4212 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
4213 }
4214
4215 // -fmodule-name specifies the module that is currently being built (or
4216 // used for header checking by -fmodule-maps).
4217 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
4218
4219 // -fmodule-map-file can be used to specify files containing module
4220 // definitions.
4221 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
4222
4223 // -fbuiltin-module-map can be used to load the clang
4224 // builtin headers modulemap file.
4225 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
4226 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4227 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
4228 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
4229 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
4230 CmdArgs.push_back(
4231 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
4232 }
4233
4234 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4235 // names to precompiled module files (the module is loaded only if used).
4236 // The -fmodule-file=<file> form can be used to unconditionally load
4237 // precompiled module files (whether used or not).
4238 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4239 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
4240
4241 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4242 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
4243 CmdArgs.push_back(Elt: Args.MakeArgString(
4244 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
4245 A->claim();
4246 }
4247 } else
4248 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
4249
4250 // When building modules and generating crashdumps, we need to dump a module
4251 // dependency VFS alongside the output.
4252 if (HaveClangModules && C.isForDiagnostics()) {
4253 SmallString<128> VFSDir(Output.getFilename());
4254 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
4255 // Add the cache directory as a temp so the crash diagnostics pick it up.
4256 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
4257
4258 llvm::sys::path::append(path&: VFSDir, a: "vfs");
4259 CmdArgs.push_back(Elt: "-module-dependency-dir");
4260 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
4261 }
4262
4263 if (HaveClangModules)
4264 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
4265
4266 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
4267 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_search_path);
4268 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
4269 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4270
4271 if (HaveClangModules) {
4272 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4273
4274 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4275 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4276 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4277 << A->getAsString(Args) << "-fbuild-session-timestamp";
4278
4279 llvm::sys::fs::file_status Status;
4280 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4281 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4282 CmdArgs.push_back(Elt: Args.MakeArgString(
4283 Str: "-fbuild-session-timestamp=" +
4284 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4285 d: Status.getLastModificationTime().time_since_epoch())
4286 .count())));
4287 }
4288
4289 if (Args.getLastArg(
4290 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4291 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4292 Ids: options::OPT_fbuild_session_file))
4293 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4294
4295 Args.AddLastArg(Output&: CmdArgs,
4296 Ids: options::OPT_fmodules_validate_once_per_build_session);
4297 }
4298
4299 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4300 Neg: options::OPT_fno_modules_validate_system_headers,
4301 Default: ImplicitModules))
4302 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4303
4304 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_directory_dependencies,
4305 Neg: options::OPT_fno_modules_validate_directory_dependencies,
4306 Default: false))
4307 CmdArgs.push_back(Elt: "-fmodules-validate-directory-dependencies");
4308
4309 Args.AddLastArg(Output&: CmdArgs,
4310 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4311 } else {
4312 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4313 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4314 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4315 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4316 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4317 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_directory_dependencies);
4318 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_directory_dependencies);
4319 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4320 }
4321
4322 // FIXME: We provisionally don't check ODR violations for decls in the global
4323 // module fragment.
4324 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4325
4326 if (Input.getType() == driver::types::TY_CXXModule ||
4327 Input.getType() == driver::types::TY_PP_CXXModule) {
4328 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4329 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4330
4331 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4332 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4333 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4334 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4335 Args.hasArg(Ids: options::OPT_fmodule_output))
4336 // If --precompile is specified, we will always generate a module file if
4337 // we're compiling an importable module unit. This is fine even if the
4338 // compilation process won't reach the point of generating the module file
4339 // (e.g., in the preprocessing mode), since the attached flag
4340 // '-fmodule-output' is useless.
4341 //
4342 // But if '--precompile' is specified, it might be annoying to always
4343 // generate the module file as '--precompile' will generate the module
4344 // file anyway.
4345 CmdArgs.push_back(Elt: Args.MakeArgString(
4346 Str: "-fmodule-output=" +
4347 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4348 }
4349
4350 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4351 Args.hasArg(Ids: options::OPT__precompile) &&
4352 (!Args.hasArg(Ids: options::OPT_o) ||
4353 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4354 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4355 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4356 }
4357
4358 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4359 // other translation units than module units. This is more user friendly to
4360 // allow end uers to enable this feature without asking for help from build
4361 // systems.
4362 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4363 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4364
4365 // We need to include the case the input file is a module file here.
4366 // Since the default compilation model for C++ module interface unit will
4367 // create temporary module file and compile the temporary module file
4368 // to get the object file. Then the `-fmodule-output` flag will be
4369 // brought to the second compilation process. So we have to claim it for
4370 // the case too.
4371 if (Input.getType() == driver::types::TY_CXXModule ||
4372 Input.getType() == driver::types::TY_PP_CXXModule ||
4373 Input.getType() == driver::types::TY_ModuleFile) {
4374 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4375 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4376 }
4377
4378 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4379 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4380
4381 return HaveModules;
4382}
4383
4384static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4385 ArgStringList &CmdArgs) {
4386 // -fsigned-char is default.
4387 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4388 Ids: options::OPT_fno_signed_char,
4389 Ids: options::OPT_funsigned_char,
4390 Ids: options::OPT_fno_unsigned_char)) {
4391 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4392 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4393 CmdArgs.push_back(Elt: "-fno-signed-char");
4394 }
4395 } else if (!isSignedCharDefault(Triple: T)) {
4396 CmdArgs.push_back(Elt: "-fno-signed-char");
4397 }
4398
4399 // The default depends on the language standard.
4400 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4401
4402 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4403 Ids: options::OPT_fno_short_wchar)) {
4404 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4405 CmdArgs.push_back(Elt: "-fwchar-type=short");
4406 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4407 } else {
4408 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4409 CmdArgs.push_back(Elt: "-fwchar-type=int");
4410 if (T.isOSzOS() ||
4411 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4412 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4413 else
4414 CmdArgs.push_back(Elt: "-fsigned-wchar");
4415 }
4416 } else if (T.isOSzOS())
4417 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4418}
4419
4420static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4421 const llvm::Triple &T, const ArgList &Args,
4422 ObjCRuntime &Runtime, bool InferCovariantReturns,
4423 const InputInfo &Input, ArgStringList &CmdArgs) {
4424 const llvm::Triple::ArchType Arch = TC.getArch();
4425
4426 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4427 // is the default. Except for deployment target of 10.5, next runtime is
4428 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4429 if (Runtime.isNonFragile()) {
4430 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4431 Neg: options::OPT_fno_objc_legacy_dispatch,
4432 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4433 if (TC.UseObjCMixedDispatch())
4434 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4435 else
4436 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4437 }
4438 }
4439
4440 // Forward -fobjc-direct-precondition-thunk to cc1
4441 // Defaults to false and needs explict turn on for now
4442 // TODO: switch to default true and needs explict turn off in the future.
4443 // TODO: add support for other runtimes
4444 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4445 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4446 if (Runtime.isNeXTFamily()) {
4447 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4448 } else {
4449 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4450 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4451 }
4452 }
4453
4454 if (types::isObjC(Id: Input.getType())) {
4455 // Pass down -fobjc-msgsend-selector-stubs if present.
4456 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4457 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4458 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4459
4460 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4461 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4462 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4463 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4464 }
4465
4466 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4467 // to do Array/Dictionary subscripting by default.
4468 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4469 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4470 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4471
4472 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4473 // NOTE: This logic is duplicated in ToolChains.cpp.
4474 if (isObjCAutoRefCount(Args)) {
4475 TC.CheckObjCARC();
4476
4477 CmdArgs.push_back(Elt: "-fobjc-arc");
4478
4479 // FIXME: It seems like this entire block, and several around it should be
4480 // wrapped in isObjC, but for now we just use it here as this is where it
4481 // was being used previously.
4482 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4483 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4484 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4485 else
4486 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4487 }
4488
4489 // Allow the user to enable full exceptions code emission.
4490 // We default off for Objective-C, on for Objective-C++.
4491 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4492 Neg: options::OPT_fno_objc_arc_exceptions,
4493 /*Default=*/types::isCXX(Id: Input.getType())))
4494 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4495 }
4496
4497 // Silence warning for full exception code emission options when explicitly
4498 // set to use no ARC.
4499 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4500 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4501 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4502 }
4503
4504 // Allow the user to control whether messages can be converted to runtime
4505 // functions.
4506 if (types::isObjC(Id: Input.getType())) {
4507 auto *Arg = Args.getLastArg(
4508 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4509 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4510 if (Arg &&
4511 Arg->getOption().matches(
4512 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4513 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4514 }
4515
4516 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4517 // rewriter.
4518 if (InferCovariantReturns)
4519 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4520
4521 // Pass down -fobjc-weak or -fno-objc-weak if present.
4522 if (types::isObjC(Id: Input.getType())) {
4523 auto WeakArg =
4524 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4525 if (!WeakArg) {
4526 // nothing to do
4527 } else if (!Runtime.allowsWeak()) {
4528 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4529 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4530 } else {
4531 WeakArg->render(Args, Output&: CmdArgs);
4532 }
4533 }
4534
4535 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4536 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4537
4538 // Forward constant literal flags to cc1.
4539 if (types::isObjC(Id: Input.getType())) {
4540 bool EnableConstantLiterals =
4541 Args.hasFlag(Pos: options::OPT_fobjc_constant_literals,
4542 Neg: options::OPT_fno_objc_constant_literals,
4543 /*default=*/Default: true) &&
4544 Runtime.hasConstantLiteralClasses();
4545 if (EnableConstantLiterals)
4546 CmdArgs.push_back(Elt: "-fobjc-constant-literals");
4547 if (Args.hasFlag(Pos: options::OPT_fconstant_nsnumber_literals,
4548 Neg: options::OPT_fno_constant_nsnumber_literals,
4549 /*default=*/Default: true) &&
4550 EnableConstantLiterals)
4551 CmdArgs.push_back(Elt: "-fconstant-nsnumber-literals");
4552 if (Args.hasFlag(Pos: options::OPT_fconstant_nsarray_literals,
4553 Neg: options::OPT_fno_constant_nsarray_literals,
4554 /*default=*/Default: true) &&
4555 EnableConstantLiterals)
4556 CmdArgs.push_back(Elt: "-fconstant-nsarray-literals");
4557 if (Args.hasFlag(Pos: options::OPT_fconstant_nsdictionary_literals,
4558 Neg: options::OPT_fno_constant_nsdictionary_literals,
4559 /*default=*/Default: true) &&
4560 EnableConstantLiterals)
4561 CmdArgs.push_back(Elt: "-fconstant-nsdictionary-literals");
4562 }
4563}
4564
4565static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4566 ArgStringList &CmdArgs) {
4567 bool CaretDefault = true;
4568 bool ColumnDefault = true;
4569
4570 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4571 Ids: options::OPT__SLASH_diagnostics_column,
4572 Ids: options::OPT__SLASH_diagnostics_caret)) {
4573 switch (A->getOption().getID()) {
4574 case options::OPT__SLASH_diagnostics_caret:
4575 CaretDefault = true;
4576 ColumnDefault = true;
4577 break;
4578 case options::OPT__SLASH_diagnostics_column:
4579 CaretDefault = false;
4580 ColumnDefault = true;
4581 break;
4582 case options::OPT__SLASH_diagnostics_classic:
4583 CaretDefault = false;
4584 ColumnDefault = false;
4585 break;
4586 }
4587 }
4588
4589 // -fcaret-diagnostics is default.
4590 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4591 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4592 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4593
4594 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4595 Neg: options::OPT_fno_diagnostics_fixit_info);
4596 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4597 Neg: options::OPT_fno_diagnostics_show_option);
4598
4599 if (const Arg *A =
4600 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4601 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4602 CmdArgs.push_back(Elt: A->getValue());
4603 }
4604
4605 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4606 Neg: options::OPT_fno_diagnostics_show_hotness);
4607
4608 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_safety_c,
4609 Neg: options::OPT_fno_lifetime_safety_c);
4610
4611 if (const Arg *A =
4612 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4613 std::string Opt =
4614 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4615 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4616 }
4617
4618 if (const Arg *A =
4619 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4620 std::string Opt =
4621 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4622 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4623 }
4624
4625 if (const Arg *A =
4626 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_inlining_chain,
4627 Ids: options::OPT_fno_diagnostics_show_inlining_chain)) {
4628 if (A->getOption().matches(ID: options::OPT_fdiagnostics_show_inlining_chain))
4629 CmdArgs.push_back(Elt: "-fdiagnostics-show-inlining-chain");
4630 else
4631 CmdArgs.push_back(Elt: "-fno-diagnostics-show-inlining-chain");
4632 }
4633
4634 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4635 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4636 CmdArgs.push_back(Elt: A->getValue());
4637 if (StringRef(A->getValue()) == "sarif" ||
4638 StringRef(A->getValue()) == "SARIF")
4639 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4640 }
4641
4642 if (const Arg *A = Args.getLastArg(
4643 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4644 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4645 const Option &O = A->getOption();
4646 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4647 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4648 else
4649 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4650 }
4651
4652 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4653
4654 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4655 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4656
4657 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4658 Neg: options::OPT_fno_show_source_location);
4659
4660 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4661 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4662
4663 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4664 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4665
4666 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4667 Default: ColumnDefault))
4668 CmdArgs.push_back(Elt: "-fno-show-column");
4669
4670 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4671 Neg: options::OPT_fno_spell_checking);
4672
4673 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4674}
4675
4676static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4677 const ArgList &Args, ArgStringList &CmdArgs,
4678 unsigned DwarfVersion) {
4679 auto *DwarfFormatArg =
4680 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4681 if (!DwarfFormatArg)
4682 return;
4683
4684 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4685 if (DwarfVersion < 3)
4686 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4687 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4688 else if (!T.isArch64Bit())
4689 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4690 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4691 else if (!T.isOSBinFormatELF())
4692 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4693 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4694 }
4695
4696 DwarfFormatArg->render(Args, Output&: CmdArgs);
4697}
4698
4699static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4700 const ArgList &Args) {
4701 bool NeedsSimpleTemplateNames =
4702 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4703 Neg: options::OPT_gno_simple_template_names,
4704 Default: TC.getDefaultDebugSimpleTemplateNames());
4705 if (!NeedsSimpleTemplateNames)
4706 return false;
4707
4708 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4709 if (!checkDebugInfoOption(A, Args, D, TC))
4710 return false;
4711
4712 return true;
4713}
4714
4715static void
4716renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4717 const ArgList &Args, types::ID InputType,
4718 ArgStringList &CmdArgs, const InputInfo &Output,
4719 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4720 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4721 bool IRInput = isLLVMIR(Id: InputType);
4722 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4723 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4724 !isOpenCL(Id: InputType);
4725
4726 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4727
4728 if (!Args.hasFlag(Pos: options::OPT_fdebug_record_sysroot,
4729 Neg: options::OPT_fno_debug_record_sysroot, Default: true))
4730 CmdArgs.push_back(Elt: "-fno-debug-record-sysroot");
4731
4732 // The 'g' groups options involve a somewhat intricate sequence of decisions
4733 // about what to pass from the driver to the frontend, but by the time they
4734 // reach cc1 they've been factored into three well-defined orthogonal choices:
4735 // * what level of debug info to generate
4736 // * what dwarf version to write
4737 // * what debugger tuning to use
4738 // This avoids having to monkey around further in cc1 other than to disable
4739 // codeview if not running in a Windows environment. Perhaps even that
4740 // decision should be made in the driver as well though.
4741 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4742
4743 bool SplitDWARFInlining =
4744 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4745 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4746
4747 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4748 // object file generation and no IR generation, -gN should not be needed. So
4749 // allow -gsplit-dwarf with either -gN or IR input.
4750 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4751 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4752 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4753 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4754 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4755 << TC.getTripleString();
4756 return;
4757 }
4758 Arg *SplitDWARFArg;
4759 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4760 if (DwarfFission != DwarfFissionKind::None &&
4761 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4762 DwarfFission = DwarfFissionKind::None;
4763 SplitDWARFInlining = false;
4764 }
4765 }
4766 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4767 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4768
4769 // If the last option explicitly specified a debug-info level, use it.
4770 if (checkDebugInfoOption(A, Args, D, TC) &&
4771 A->getOption().matches(ID: options::OPT_gN_Group)) {
4772 DebugInfoKind = debugLevelToInfoKind(A: *A);
4773 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4774 // complicated if you've disabled inline info in the skeleton CUs
4775 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4776 // line-tables-only, so let those compose naturally in that case.
4777 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4778 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4779 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4780 SplitDWARFInlining))
4781 DwarfFission = DwarfFissionKind::None;
4782 }
4783 }
4784
4785 // If a debugger tuning argument appeared, remember it.
4786 bool HasDebuggerTuning = false;
4787 if (const Arg *A =
4788 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4789 HasDebuggerTuning = true;
4790 if (checkDebugInfoOption(A, Args, D, TC)) {
4791 if (A->getOption().matches(ID: options::OPT_glldb))
4792 DebuggerTuning = llvm::DebuggerKind::LLDB;
4793 else if (A->getOption().matches(ID: options::OPT_gsce))
4794 DebuggerTuning = llvm::DebuggerKind::SCE;
4795 else if (A->getOption().matches(ID: options::OPT_gdbx))
4796 DebuggerTuning = llvm::DebuggerKind::DBX;
4797 else
4798 DebuggerTuning = llvm::DebuggerKind::GDB;
4799 }
4800 }
4801
4802 // If a -gdwarf argument appeared, remember it.
4803 bool EmitDwarf = false;
4804 if (const Arg *A = getDwarfNArg(Args))
4805 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4806
4807 bool EmitCodeView = false;
4808 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4809 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4810
4811 // If the user asked for debug info but did not explicitly specify -gcodeview
4812 // or -gdwarf, ask the toolchain for the default format.
4813 if (!EmitCodeView && !EmitDwarf &&
4814 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4815 switch (TC.getDefaultDebugFormat()) {
4816 case llvm::codegenoptions::DIF_CodeView:
4817 EmitCodeView = true;
4818 break;
4819 case llvm::codegenoptions::DIF_DWARF:
4820 EmitDwarf = true;
4821 break;
4822 }
4823 }
4824
4825 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4826 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4827 // be lower than what the user wanted.
4828 if (EmitDwarf) {
4829 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4830 // Clamp effective DWARF version to the max supported by the toolchain.
4831 EffectiveDWARFVersion =
4832 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4833 } else {
4834 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4835 }
4836
4837 // -gline-directives-only supported only for the DWARF debug info.
4838 if (RequestedDWARFVersion == 0 &&
4839 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4840 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4841
4842 // strict DWARF is set to false by default. But for DBX, we need it to be set
4843 // as true by default.
4844 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4845 (void)checkDebugInfoOption(A, Args, D, TC);
4846 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4847 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4848 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4849
4850 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4851 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4852
4853 // Column info is included by default for everything except SCE and
4854 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4855 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4856 // practice, however, the Microsoft debuggers don't handle missing end columns
4857 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4858 // it's better not to include any column info.
4859 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4860 (void)checkDebugInfoOption(A, Args, D, TC);
4861 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4862 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4863 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4864 DebuggerTuning != llvm::DebuggerKind::DBX)))
4865 CmdArgs.push_back(Elt: "-gno-column-info");
4866
4867 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4868 Neg: options::OPT_gno_call_site_info, Default: true))
4869 CmdArgs.push_back(Elt: "-gno-call-site-info");
4870
4871 // FIXME: Move backend command line options to the module.
4872 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4873 // If -gline-tables-only or -gline-directives-only is the last option it
4874 // wins.
4875 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4876 TC)) {
4877 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4878 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4879 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4880 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4881 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4882 }
4883 }
4884 }
4885
4886 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4887 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4888
4889 // After we've dealt with all combinations of things that could
4890 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4891 // figure out if we need to "upgrade" it to standalone debug info.
4892 // We parse these two '-f' options whether or not they will be used,
4893 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4894 bool NeedFullDebug = Args.hasFlag(
4895 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4896 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4897 TC.GetDefaultStandaloneDebug());
4898 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4899 (void)checkDebugInfoOption(A, Args, D, TC);
4900
4901 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4902 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4903 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4904 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4905 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4906 else if (NeedFullDebug)
4907 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4908 }
4909
4910 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4911 Default: false)) {
4912 // Source embedding is a vendor extension to DWARF v5. By now we have
4913 // checked if a DWARF version was stated explicitly, and have otherwise
4914 // fallen back to the target default, so if this is still not at least 5
4915 // we emit an error.
4916 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4917 if (RequestedDWARFVersion < 5)
4918 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4919 << A->getAsString(Args) << "-gdwarf-5";
4920 else if (EffectiveDWARFVersion < 5)
4921 // The toolchain has reduced allowed dwarf version, so we can't enable
4922 // -gembed-source.
4923 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4924 << A->getAsString(Args) << TC.getTripleString() << 5
4925 << EffectiveDWARFVersion;
4926 else if (checkDebugInfoOption(A, Args, D, TC))
4927 CmdArgs.push_back(Elt: "-gembed-source");
4928 }
4929
4930 // Enable Key Instructions by default if we're emitting DWARF, the language is
4931 // plain C or C++, and optimisations are enabled.
4932 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4933 bool KeyInstructionsOnByDefault =
4934 EmitDwarf && PlainCOrCXX && OptLevel &&
4935 !OptLevel->getOption().matches(ID: options::OPT_O0);
4936 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4937 Neg: options::OPT_gno_key_instructions,
4938 Default: KeyInstructionsOnByDefault))
4939 CmdArgs.push_back(Elt: "-gkey-instructions");
4940
4941 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4942 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4943 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4944
4945 if (Args.hasFlag(Pos: options::OPT_fdynamic_debugging,
4946 Neg: options::OPT_fno_dynamic_debugging, Default: false)) {
4947 // As this is an experimental feature we can afford to be strict about
4948 // supported configurations.
4949 // NOTE on adding target support, consider adding "tail-pad-to-size"
4950 // support in `llvm::prepareForDynamicDebugging`.
4951 if (!TC.getTriple().isX86())
4952 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4953 << Args.getLastArg(Ids: options::OPT_fdynamic_debugging)->getAsString(Args)
4954 << T.getTriple();
4955 if (IsUsingLTO)
4956 D.Diag(DiagID: diag::err_drv_dyndbg_lto);
4957 if (DwarfFission != DwarfFissionKind::None)
4958 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible)
4959 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getAsString(Args);
4960 // There's no fundamental reason why IR input should be incompatible, but
4961 // it would add some complexity, and reducing the test matrix is valuable.
4962 if (IRInput)
4963 D.Diag(DiagID: diag::err_drv_dyndbg_ir);
4964
4965 // Disable composition with sanitizers for now.
4966 if (auto *San = Args.getLastArg(Ids: options::OPT_fsanitize_EQ))
4967 D.Diag(DiagID: diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4968
4969 if (!EmitDwarf)
4970 D.Diag(DiagID: diag::warn_drv_dyndbg_req_debug);
4971 else
4972 CmdArgs.push_back(Elt: "-fdynamic-debugging");
4973 }
4974
4975 if (EmitCodeView) {
4976 CmdArgs.push_back(Elt: "-gcodeview");
4977
4978 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4979 Neg: options::OPT_gno_codeview_ghash);
4980
4981 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4982 Neg: options::OPT_gno_codeview_command_line);
4983 }
4984
4985 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4986 Neg: options::OPT_gno_inline_line_tables);
4987
4988 // When emitting remarks, we need at least debug lines in the output.
4989 if (willEmitRemarks(Args) &&
4990 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4991 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4992
4993 // Adjust the debug info kind for the given toolchain.
4994 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4995
4996 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4997 // set.
4998 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4999 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
5000 ? llvm::DebuggerKind::Default
5001 : DebuggerTuning);
5002
5003 // -fdebug-macro turns on macro debug info generation.
5004 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
5005 Default: false))
5006 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
5007 D, TC))
5008 CmdArgs.push_back(Elt: "-debug-info-macro");
5009
5010 // -ggnu-pubnames turns on gnu style pubnames in the backend.
5011 const auto *PubnamesArg =
5012 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
5013 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
5014 if (DwarfFission != DwarfFissionKind::None ||
5015 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
5016 const bool OptionSet =
5017 (PubnamesArg &&
5018 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
5019 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
5020 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
5021 (!PubnamesArg ||
5022 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
5023 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
5024 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
5025 ID: options::OPT_gpubnames)
5026 ? "-gpubnames"
5027 : "-ggnu-pubnames");
5028 }
5029
5030 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
5031 if (getDebugSimpleTemplateNames(TC, D, Args)) {
5032 ForwardTemplateParams = true;
5033 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
5034 }
5035
5036 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
5037 bool UseDebugTemplateAlias =
5038 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
5039 if (const auto *DebugTemplateAlias = Args.getLastArg(
5040 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
5041 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5042 // asks for it we should let them have it (if the target supports it).
5043 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
5044 const auto &Opt = DebugTemplateAlias->getOption();
5045 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
5046 }
5047 }
5048 if (UseDebugTemplateAlias)
5049 CmdArgs.push_back(Elt: "-gtemplate-alias");
5050
5051 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
5052 StringRef v = A->getValue();
5053 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
5054 }
5055
5056 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
5057 Neg: options::OPT_fno_debug_ranges_base_address);
5058
5059 // -gdwarf-aranges turns on the emission of the aranges section in the
5060 // backend.
5061 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
5062 A && checkDebugInfoOption(A, Args, D, TC)) {
5063 CmdArgs.push_back(Elt: "-mllvm");
5064 CmdArgs.push_back(Elt: "-generate-arange-section");
5065 }
5066
5067 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
5068 Neg: options::OPT_fno_force_dwarf_frame);
5069
5070 bool EnableTypeUnits = false;
5071 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
5072 Neg: options::OPT_fno_debug_types_section, Default: false)) {
5073 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5074 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5075 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
5076 ->getAsString(Args)
5077 << T.getTriple();
5078 } else if (checkDebugInfoOption(
5079 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
5080 TC)) {
5081 EnableTypeUnits = true;
5082 CmdArgs.push_back(Elt: "-mllvm");
5083 CmdArgs.push_back(Elt: "-generate-type-units");
5084 }
5085 }
5086
5087 if (const Arg *A =
5088 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
5089 Ids: options::OPT_gno_omit_unreferenced_methods))
5090 (void)checkDebugInfoOption(A, Args, D, TC);
5091 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
5092 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
5093 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5094 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5095 !EnableTypeUnits) {
5096 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
5097 }
5098
5099 // To avoid join/split of directory+filename, the integrated assembler prefers
5100 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5101 // form before DWARF v5.
5102 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
5103 Neg: options::OPT_fno_dwarf_directory_asm,
5104 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5105 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
5106
5107 // Decide how to render forward declarations of template instantiations.
5108 // SCE wants full descriptions, others just get them in the name.
5109 if (ForwardTemplateParams)
5110 CmdArgs.push_back(Elt: "-debug-forward-template-params");
5111
5112 // Do we need to explicitly import anonymous namespaces into the parent
5113 // scope?
5114 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5115 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
5116
5117 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
5118 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5119
5120 // This controls whether or not we perform JustMyCode instrumentation.
5121 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
5122 if (TC.getTriple().isOSBinFormatELF() ||
5123 TC.getTriple().isWindowsMSVCEnvironment()) {
5124 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5125 CmdArgs.push_back(Elt: "-fjmc");
5126 else if (D.IsCLMode())
5127 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5128 << "'/Zi', '/Z7'";
5129 else
5130 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5131 << "-g";
5132 } else {
5133 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
5134 }
5135 }
5136
5137 // Add in -fdebug-compilation-dir if necessary.
5138 const char *DebugCompilationDir =
5139 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
5140
5141 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5142
5143 // Add the output path to the object file for CodeView debug infos.
5144 if (EmitCodeView && Output.isFilename())
5145 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5146 OutputFileName: Output.getFilename());
5147}
5148
5149static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5150 ArgStringList &CmdArgs) {
5151 unsigned RTOptionID = options::OPT__SLASH_MT;
5152
5153 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5154 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5155 // but defining _DEBUG is sticky.
5156 RTOptionID = options::OPT__SLASH_MTd;
5157
5158 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
5159 RTOptionID = A->getOption().getID();
5160
5161 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5162 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5163 .Case(S: "static", Value: options::OPT__SLASH_MT)
5164 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
5165 .Case(S: "dll", Value: options::OPT__SLASH_MD)
5166 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
5167 .Default(Value: options::OPT__SLASH_MT);
5168 }
5169
5170 StringRef FlagForCRT;
5171 switch (RTOptionID) {
5172 case options::OPT__SLASH_MD:
5173 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5174 CmdArgs.push_back(Elt: "-D_DEBUG");
5175 CmdArgs.push_back(Elt: "-D_MT");
5176 CmdArgs.push_back(Elt: "-D_DLL");
5177 FlagForCRT = "--dependent-lib=msvcrt";
5178 break;
5179 case options::OPT__SLASH_MDd:
5180 CmdArgs.push_back(Elt: "-D_DEBUG");
5181 CmdArgs.push_back(Elt: "-D_MT");
5182 CmdArgs.push_back(Elt: "-D_DLL");
5183 FlagForCRT = "--dependent-lib=msvcrtd";
5184 break;
5185 case options::OPT__SLASH_MT:
5186 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5187 CmdArgs.push_back(Elt: "-D_DEBUG");
5188 CmdArgs.push_back(Elt: "-D_MT");
5189 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5190 FlagForCRT = "--dependent-lib=libcmt";
5191 break;
5192 case options::OPT__SLASH_MTd:
5193 CmdArgs.push_back(Elt: "-D_DEBUG");
5194 CmdArgs.push_back(Elt: "-D_MT");
5195 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5196 FlagForCRT = "--dependent-lib=libcmtd";
5197 break;
5198 default:
5199 llvm_unreachable("Unexpected option ID.");
5200 }
5201
5202 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5203 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
5204 } else {
5205 CmdArgs.push_back(Elt: FlagForCRT.data());
5206
5207 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5208 // users want. The /Za flag to cl.exe turns this off, but it's not
5209 // implemented in clang.
5210 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
5211 }
5212
5213 // SYCL: Add SYCL runtime library dependency
5214 // SYCL runtime is a required dependency similar to CRT, so we use
5215 // --dependent-lib to embed it in the object file metadata
5216 if (Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) &&
5217 !Args.hasArg(Ids: options::OPT_nolibsycl) &&
5218 !Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5219
5220 // Determine debug vs release based on CRT flags
5221 bool IsDebugBuild = false;
5222
5223 // Check -fms-runtime-lib=dll_dbg
5224 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5225 StringRef RuntimeVal = A->getValue();
5226 if (RuntimeVal == "dll_dbg")
5227 IsDebugBuild = true;
5228 }
5229
5230 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5231 // overriding options (e.g., /MDd /MD -> /MD wins)
5232 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group)) {
5233 if (A->getOption().matches(ID: options::OPT__SLASH_MDd))
5234 IsDebugBuild = true;
5235 }
5236
5237 // Add appropriate SYCL runtime library dependency
5238 CmdArgs.push_back(Elt: IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5239 : "--dependent-lib=LLVMSYCL");
5240 }
5241
5242 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5243 // even if the file doesn't actually refer to any of the routines because
5244 // the CRT itself has incomplete dependency markings.
5245 if (TC.getTriple().isWindowsArm64EC())
5246 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
5247}
5248
5249void Clang::ConstructJob(Compilation &C, const JobAction &JA,
5250 const InputInfo &Output, const InputInfoList &Inputs,
5251 const ArgList &Args, const char *LinkingOutput) const {
5252 const auto &TC = getToolChain();
5253 const llvm::Triple &RawTriple = TC.getTriple();
5254 const llvm::Triple &Triple = TC.getEffectiveTriple();
5255 const std::string &TripleStr = Triple.getTriple();
5256
5257 bool KernelOrKext =
5258 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
5259 const Driver &D = TC.getDriver();
5260 ArgStringList CmdArgs;
5261
5262 assert(Inputs.size() >= 1 && "Must have at least one input.");
5263 // CUDA/HIP compilation may have multiple inputs (source file + results of
5264 // device-side compilations). OpenMP device jobs also take the host IR as a
5265 // second input. Module precompilation accepts a list of header files to
5266 // include as part of the module. API extraction accepts a list of header
5267 // files whose API information is emitted in the output. All other jobs are
5268 // expected to have exactly one input. SYCL compilation only expects a
5269 // single input.
5270 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
5271 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
5272 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
5273 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
5274 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
5275 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
5276 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
5277 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
5278 bool UsesLLVMOffloading = Args.hasFlag(
5279 Pos: options::OPT_foffload_via_llvm, Neg: options::OPT_fno_offload_via_llvm, Default: false);
5280 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
5281 JA.isDeviceOffloading(OKind: Action::OFK_Host));
5282 bool IsHostOffloadingAction =
5283 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
5284 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
5285 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()));
5286
5287 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5288 bool IsRDCMode = Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
5289 /*Default=*/IsSYCL);
5290
5291 auto LTOMode = TC.getLTOMode(Args, Kind: JA.getOffloadingDeviceKind());
5292 bool IsUsingLTO = LTOMode != LTOK_None;
5293
5294 // Extract API doesn't have a main input file, so invent a fake one as a
5295 // placeholder.
5296 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5297 "extract-api");
5298
5299 const InputInfo &Input =
5300 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5301
5302 InputInfoList ExtractAPIInputs;
5303 InputInfoList HostOffloadingInputs;
5304 const InputInfo *OpenMPDeviceInput = nullptr;
5305 for (const InputInfo &I : Inputs) {
5306 if (&I == &Input || I.getType() == types::TY_Nothing) {
5307 // This is the primary input or contains nothing.
5308 } else if (IsExtractAPI) {
5309 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5310 if (I.getType() != ExpectedInputType) {
5311 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
5312 << I.getFilename() << types::getTypeName(Id: I.getType())
5313 << types::getTypeName(Id: ExpectedInputType);
5314 }
5315 ExtractAPIInputs.push_back(Elt: I);
5316 } else if (IsHostOffloadingAction) {
5317 HostOffloadingInputs.push_back(Elt: I);
5318 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5319 OpenMPDeviceInput = &I;
5320 } else {
5321 llvm_unreachable("unexpectedly given multiple inputs");
5322 }
5323 }
5324
5325 bool IsUEFI = RawTriple.isUEFI();
5326 bool IsIAMCU = RawTriple.isOSIAMCU();
5327
5328 // C++ is not supported for IAMCU.
5329 if (IsIAMCU && types::isCXX(Id: Input.getType()))
5330 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5331
5332 // Invoke ourselves in -cc1 mode.
5333 //
5334 // FIXME: Implement custom jobs for internal actions.
5335 CmdArgs.push_back(Elt: "-cc1");
5336
5337 // Add the "effective" target triple.
5338 CmdArgs.push_back(Elt: "-triple");
5339 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: TripleStr));
5340
5341 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5342
5343 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5344 if (AuxTriple) {
5345 CmdArgs.push_back(Elt: "-aux-triple");
5346 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTriple->str()));
5347
5348 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5349 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5350 // Windows), we need to pass Windows-specific flags to cc1.
5351 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5352 } else if (JA.getOffloadingHostActiveKinds() != Action::OFK_None) {
5353 // Figure out the device side triple for the host-side compilation.
5354 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5355 ++I) {
5356 Compilation::const_offload_toolchains_range OffloadToolChains =
5357 C.getOffloadToolChains(Kind: static_cast<Action::OffloadKind>(I));
5358 if (OffloadToolChains.first == OffloadToolChains.second)
5359 continue;
5360
5361 const llvm::Triple &DeviceAuxTriple =
5362 OffloadToolChains.first->second->getTriple();
5363 CmdArgs.push_back(Elt: "-aux-triple");
5364 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: DeviceAuxTriple.str()));
5365 break;
5366 }
5367 }
5368
5369 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
5370 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
5371 Args.ClaimAllArgs(Id0: options::OPT_MJ);
5372 } else if (const Arg *GenCDBFragment =
5373 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
5374 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
5375 Target: TripleStr, Output, Input, Args);
5376 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
5377 }
5378
5379 if ((getToolChain().getTriple().isAMDGPU() ||
5380 (getToolChain().getTriple().isSPIRV() &&
5381 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5382 // Device side compilation printf
5383 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5384 CmdArgs.push_back(Elt: Args.MakeArgString(
5385 Str: "-mprintf-kind=" +
5386 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5387 // Force compiler error on invalid conversion specifiers
5388 CmdArgs.push_back(
5389 Elt: Args.MakeArgStringRef(Str: "-Werror=format-invalid-specifier"));
5390 }
5391 }
5392
5393 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5394 // We need to figure out which CUDA version we're compiling for, as that
5395 // determines how we load and launch GPU kernels.
5396 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5397 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5398 assert(CTC && "Expected valid CUDA Toolchain.");
5399 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5400 CmdArgs.push_back(Elt: Args.MakeArgString(
5401 Str: Twine("-target-sdk-version=") +
5402 CudaVersionToString(V: CTC->CudaInstallation.version())));
5403 }
5404
5405 // Optimization level for CodeGen.
5406 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5407 if (A->getOption().matches(ID: options::OPT_O4)) {
5408 CmdArgs.push_back(Elt: "-O3");
5409 D.Diag(DiagID: diag::warn_O4_is_O3);
5410 } else {
5411 A->render(Args, Output&: CmdArgs);
5412 }
5413 }
5414
5415 // Unconditionally claim the printf option now to avoid unused diagnostic.
5416 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5417 PF->claim();
5418
5419 if (IsSYCL) {
5420 if (IsSYCLDevice) {
5421 // We want to compile sycl kernels.
5422 CmdArgs.push_back(Elt: "-fsycl-is-device");
5423
5424 // Set O2 optimization level by default
5425 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5426 CmdArgs.push_back(Elt: "-O2");
5427 } else {
5428 // Add any options that are needed specific to SYCL offload while
5429 // performing the host side compilation.
5430
5431 // Let the front-end host compilation flow know about SYCL offload
5432 // compilation.
5433 CmdArgs.push_back(Elt: "-fsycl-is-host");
5434 }
5435
5436 // Set options for both host and device.
5437 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5438 if (SYCLStdArg) {
5439 SYCLStdArg->render(Args, Output&: CmdArgs);
5440 } else {
5441 // Ensure the default version in SYCL mode is 2020.
5442 CmdArgs.push_back(Elt: "-sycl-std=2020");
5443 }
5444 }
5445
5446 if (Args.hasFlag(Pos: options::OPT_fclangir, Neg: options::OPT_fno_clangir, Default: false))
5447 CmdArgs.push_back(Elt: "-fclangir");
5448
5449 if (IsOpenMPDevice) {
5450 // We have to pass the triple of the host if compiling for an OpenMP device.
5451 const llvm::Triple &HostTriple =
5452 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5453 CmdArgs.push_back(Elt: "-aux-triple");
5454 CmdArgs.push_back(Elt: HostTriple.str().c_str());
5455 }
5456
5457 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5458 Triple.getArch() == llvm::Triple::thumb)) {
5459 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5460 unsigned Version = 0;
5461 bool Failure =
5462 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5463 if (Failure || Version < 7)
5464 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5465 << TripleStr;
5466 }
5467
5468 // Push all default warning arguments that are specific to
5469 // the given target. These come before user provided warning options
5470 // are provided.
5471 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5472
5473 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5474 if (Triple.isSPIR() || Triple.isSPIRV())
5475 CmdArgs.push_back(Elt: "-Wspir-compat");
5476
5477 // Select the appropriate action.
5478 RewriteKind rewriteKind = RK_None;
5479
5480 bool UnifiedLTO = false;
5481 if (IsUsingLTO) {
5482 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5483 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5484 if (UnifiedLTO)
5485 CmdArgs.push_back(Elt: "-funified-lto");
5486 }
5487
5488 if (Args.hasArg(Ids: options::OPT_fdefined_pointer_subtraction))
5489 CmdArgs.push_back(Elt: "-fdefined-pointer-subtraction");
5490
5491 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5492 // it claims when not running an assembler. Otherwise, clang would emit
5493 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5494 // flags while debugging something. That'd be somewhat inconvenient, and it's
5495 // also inconsistent with most other flags -- we don't warn on
5496 // -ffunction-sections not being used in -E mode either for example, even
5497 // though it's not really used either.
5498 if (!isa<AssembleJobAction>(Val: JA)) {
5499 // The args claimed here should match the args used in
5500 // CollectArgsForIntegratedAssembler().
5501 if (TC.useIntegratedAs()) {
5502 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5503 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5504 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5505 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5506 switch (C.getDefaultToolChain().getArch()) {
5507 case llvm::Triple::arm:
5508 case llvm::Triple::armeb:
5509 case llvm::Triple::thumb:
5510 case llvm::Triple::thumbeb:
5511 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5512 break;
5513 default:
5514 break;
5515 }
5516 }
5517 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5518 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5519 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5520 }
5521
5522 bool IsAMDSPIRVForHIPDevice =
5523 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5524 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5525
5526 if (isa<AnalyzeJobAction>(Val: JA)) {
5527 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5528 CmdArgs.push_back(Elt: "-analyze");
5529 } else if (isa<PreprocessJobAction>(Val: JA)) {
5530 if (Output.getType() == types::TY_Dependencies)
5531 CmdArgs.push_back(Elt: "-Eonly");
5532 else {
5533 CmdArgs.push_back(Elt: "-E");
5534 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5535 !Args.hasArg(Ids: options::OPT_g_Group))
5536 CmdArgs.push_back(Elt: "-P");
5537 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5538 CmdArgs.push_back(Elt: "-fdirectives-only");
5539 }
5540 } else if (isa<AssembleJobAction>(Val: JA)) {
5541 CmdArgs.push_back(Elt: "-emit-obj");
5542
5543 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5544
5545 // Also ignore explicit -force_cpusubtype_ALL option.
5546 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5547 } else if (isa<PrecompileJobAction>(Val: JA)) {
5548 if (JA.getType() == types::TY_Nothing)
5549 CmdArgs.push_back(Elt: "-fsyntax-only");
5550 else if (JA.getType() == types::TY_ModuleFile) {
5551 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi) ||
5552 ((Input.getType() == types::TY_CXXStdModule ||
5553 Input.getType() == types::TY_PP_CXXStdModule) &&
5554 !Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi)))
5555 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5556 else
5557 CmdArgs.push_back(Elt: "-emit-module-interface");
5558 } else if (JA.getType() == types::TY_HeaderUnit)
5559 CmdArgs.push_back(Elt: "-emit-header-unit");
5560 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5561 CmdArgs.push_back(Elt: "-emit-pch");
5562 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5563 CmdArgs.push_back(Elt: "-verify-pch");
5564 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5565 assert(JA.getType() == types::TY_API_INFO &&
5566 "Extract API actions must generate a API information.");
5567 CmdArgs.push_back(Elt: "-extract-api");
5568
5569 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5570 PrettySGFArg->render(Args, Output&: CmdArgs);
5571
5572 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5573
5574 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5575 ProductNameArg->render(Args, Output&: CmdArgs);
5576 if (Arg *ExtractAPIIgnoresFileArg =
5577 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5578 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5579 if (Arg *EmitExtensionSymbolGraphs =
5580 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5581 if (!SymbolGraphDirArg)
5582 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5583
5584 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5585 }
5586 if (SymbolGraphDirArg)
5587 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5588 } else {
5589 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5590 "Invalid action for clang tool.");
5591 if (JA.getType() == types::TY_Nothing) {
5592 CmdArgs.push_back(Elt: "-fsyntax-only");
5593 } else if (JA.getType() == types::TY_LLVM_IR ||
5594 JA.getType() == types::TY_LTO_IR) {
5595 CmdArgs.push_back(Elt: "-emit-llvm");
5596 } else if (JA.getType() == types::TY_LLVM_BC ||
5597 JA.getType() == types::TY_LTO_BC) {
5598 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5599 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5600 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5601 CmdArgs.push_back(Elt: "-emit-llvm");
5602 } else {
5603 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5604 }
5605 } else if (JA.getType() == types::TY_IFS ||
5606 JA.getType() == types::TY_IFS_CPP) {
5607 StringRef ArgStr =
5608 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5609 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5610 : "ifs-v1";
5611 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5612 CmdArgs.push_back(
5613 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr));
5614 } else if (JA.getType() == types::TY_PP_Asm) {
5615 CmdArgs.push_back(Elt: "-S");
5616 } else if (JA.getType() == types::TY_AST) {
5617 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5618 CmdArgs.push_back(Elt: "-emit-pch");
5619 } else if (JA.getType() == types::TY_ModuleFile) {
5620 CmdArgs.push_back(Elt: "-module-file-info");
5621 } else if (JA.getType() == types::TY_RewrittenObjC) {
5622 CmdArgs.push_back(Elt: "-rewrite-objc");
5623 rewriteKind = RK_NonFragile;
5624 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5625 CmdArgs.push_back(Elt: "-rewrite-objc");
5626 rewriteKind = RK_Fragile;
5627 } else if (JA.getType() == types::TY_CIR) {
5628 CmdArgs.push_back(Elt: "-emit-cir");
5629 } else if (JA.getType() == types::TY_CIRBC) {
5630 CmdArgs.push_back(Elt: "-emit-cir-bc");
5631 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5632 CmdArgs.push_back(Elt: "-emit-obj");
5633 } else {
5634 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5635 }
5636
5637 // Preserve use-list order by default when emitting bitcode, so that
5638 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5639 // same result as running passes here. For LTO, we don't need to preserve
5640 // the use-list order, since serialization to bitcode is part of the flow.
5641 if (JA.getType() == types::TY_LLVM_BC)
5642 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5643
5644 if (IsUsingLTO) {
5645 const Arg *LTOArg = Args.getLastArg(Ids: options::OPT_foffload_lto,
5646 Ids: options::OPT_foffload_lto_EQ);
5647 if (Triple.isNVPTX() && !IsRDCMode &&
5648 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5649 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5650 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5651 << "-fno-gpu-rdc";
5652 } else {
5653 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5654 CmdArgs.push_back(Elt: Args.MakeArgString(
5655 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5656 // PS4 uses the legacy LTO API, which does not support some of the
5657 // features enabled by -flto-unit.
5658 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5659 CmdArgs.push_back(Elt: "-flto-unit");
5660 }
5661 }
5662 }
5663
5664 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5665
5666 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5667 if (!types::isLLVMIR(Id: Input.getType()))
5668 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5669 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5670 }
5671
5672 if (Triple.isPPC())
5673 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5674 Neg: options::OPT_mno_regnames);
5675
5676 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5677 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5678
5679 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5680 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5681
5682 if (Args.getLastArg(Ids: options::OPT_save_dynamic_debugging_temps))
5683 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_dynamic_debugging_temps);
5684
5685 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5686 Ids: options::OPT_fmemory_profile_EQ,
5687 Ids: options::OPT_fno_memory_profile);
5688 if (MemProfArg &&
5689 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5690 MemProfArg->render(Args, Output&: CmdArgs);
5691
5692 if (auto *MemProfUseArg =
5693 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5694 if (MemProfArg)
5695 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5696 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5697 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5698 Ids: options::OPT_fprofile_generate_EQ))
5699 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5700 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5701 MemProfUseArg->render(Args, Output&: CmdArgs);
5702 }
5703
5704 auto *CopyProfArg =
5705 Args.getLastArg(Ids: options::OPT_fcopyprof, Ids: options::OPT_fno_copyprof);
5706 if (CopyProfArg &&
5707 !CopyProfArg->getOption().matches(ID: options::OPT_fno_copyprof)) {
5708 CopyProfArg->render(Args, Output&: CmdArgs);
5709 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcopyprof_static_size_threshold_EQ);
5710 }
5711
5712 // Embed-bitcode option.
5713 // Only white-listed flags below are allowed to be embedded.
5714 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5715 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5716 // Add flags implied by -fembed-bitcode.
5717 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5718 // Disable all llvm IR level optimizations.
5719 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5720
5721 // Render target options.
5722 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
5723 DeviceOffloadKind: JA.getOffloadingDeviceKind());
5724
5725 // reject options that shouldn't be supported in bitcode
5726 // also reject kernel/kext
5727 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5728 options::OPT_mkernel,
5729 options::OPT_fapple_kext,
5730 options::OPT_ffunction_sections,
5731 options::OPT_fno_function_sections,
5732 options::OPT_fdata_sections,
5733 options::OPT_fno_data_sections,
5734 options::OPT_fbasic_block_sections_EQ,
5735 options::OPT_funique_internal_linkage_names,
5736 options::OPT_fno_unique_internal_linkage_names,
5737 options::OPT_funique_section_names,
5738 options::OPT_fno_unique_section_names,
5739 options::OPT_funique_basic_block_section_names,
5740 options::OPT_fno_unique_basic_block_section_names,
5741 options::OPT_mrestrict_it,
5742 options::OPT_mno_restrict_it,
5743 options::OPT_mstackrealign,
5744 options::OPT_mno_stackrealign,
5745 options::OPT_mstack_alignment,
5746 options::OPT_mcmodel_EQ,
5747 options::OPT_mlong_calls,
5748 options::OPT_mno_long_calls,
5749 options::OPT_ggnu_pubnames,
5750 options::OPT_gdwarf_aranges,
5751 options::OPT_fdebug_types_section,
5752 options::OPT_fno_debug_types_section,
5753 options::OPT_fdwarf_directory_asm,
5754 options::OPT_fno_dwarf_directory_asm,
5755 options::OPT_mrelax_all,
5756 options::OPT_mno_relax_all,
5757 options::OPT_ftrap_function_EQ,
5758 options::OPT_ffixed_r9,
5759 options::OPT_mfix_cortex_a53_835769,
5760 options::OPT_mno_fix_cortex_a53_835769,
5761 options::OPT_ffixed_x18,
5762 options::OPT_mglobal_merge,
5763 options::OPT_mno_global_merge,
5764 options::OPT_mred_zone,
5765 options::OPT_mno_red_zone,
5766 options::OPT_Wa_COMMA,
5767 options::OPT_Xassembler,
5768 options::OPT_mllvm,
5769 options::OPT_mmlir,
5770 };
5771 for (const auto &A : Args)
5772 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5773 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5774
5775 // Render the CodeGen options that need to be passed.
5776 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5777 Neg: options::OPT_fno_optimize_sibling_calls);
5778
5779 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5780 CmdArgs, JA);
5781
5782 // Render ABI arguments
5783 switch (TC.getArch()) {
5784 default: break;
5785 case llvm::Triple::arm:
5786 case llvm::Triple::armeb:
5787 case llvm::Triple::thumbeb:
5788 RenderARMABI(D, Triple, Args, CmdArgs);
5789 break;
5790 case llvm::Triple::aarch64:
5791 case llvm::Triple::aarch64_32:
5792 case llvm::Triple::aarch64_be:
5793 RenderAArch64ABI(Triple, Args, CmdArgs);
5794 break;
5795 }
5796
5797 // Input/Output file.
5798 if (Output.getType() == types::TY_Dependencies) {
5799 // Handled with other dependency code.
5800 } else if (Output.isFilename()) {
5801 CmdArgs.push_back(Elt: "-o");
5802 CmdArgs.push_back(Elt: Output.getFilename());
5803 } else {
5804 assert(Output.isNothing() && "Input output.");
5805 }
5806
5807 for (const auto &II : Inputs) {
5808 addDashXForInput(Args, Input: II, CmdArgs);
5809 if (II.isFilename())
5810 CmdArgs.push_back(Elt: II.getFilename());
5811 else
5812 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5813 }
5814
5815 C.addCommand(Cmd: std::make_unique<Command>(
5816 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getDriverProgramPath(),
5817 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5818 return;
5819 }
5820
5821 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5822 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5823
5824 // We normally speed up the clang process a bit by skipping destructors at
5825 // exit, but when we're generating diagnostics we can rely on some of the
5826 // cleanup.
5827 if (!C.isForDiagnostics())
5828 CmdArgs.push_back(Elt: "-disable-free");
5829 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5830
5831#ifdef NDEBUG
5832 const bool IsAssertBuild = false;
5833#else
5834 const bool IsAssertBuild = true;
5835#endif
5836
5837 // Disable the verification pass in no-asserts builds unless otherwise
5838 // specified.
5839 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5840 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5841 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5842 }
5843
5844 // Discard value names in no-asserts builds unless otherwise specified.
5845 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5846 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild))
5847 CmdArgs.push_back(Elt: "-discard-value-names");
5848
5849 // Set the main file name, so that debug info works even with
5850 // -save-temps.
5851 CmdArgs.push_back(Elt: "-main-file-name");
5852 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5853
5854 // Some flags which affect the language (via preprocessor
5855 // defines).
5856 if (Args.hasArg(Ids: options::OPT_static))
5857 CmdArgs.push_back(Elt: "-static-define");
5858
5859 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5860
5861 if (Args.hasArg(Ids: options::OPT_municode))
5862 CmdArgs.push_back(Elt: "-DUNICODE");
5863
5864 if (isa<AnalyzeJobAction>(Val: JA))
5865 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5866
5867 if (isa<AnalyzeJobAction>(Val: JA) ||
5868 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5869 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5870
5871 // Enable compatilibily mode to avoid analyzer-config related errors.
5872 // Since we can't access frontend flags through hasArg, let's manually iterate
5873 // through them.
5874 bool FoundAnalyzerConfig = false;
5875 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5876 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5877 FoundAnalyzerConfig = true;
5878 break;
5879 }
5880 if (!FoundAnalyzerConfig)
5881 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5882 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5883 FoundAnalyzerConfig = true;
5884 break;
5885 }
5886 if (FoundAnalyzerConfig)
5887 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5888
5889 CheckCodeGenerationOptions(D, Args);
5890
5891 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5892 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5893 if (FunctionAlignment) {
5894 CmdArgs.push_back(Elt: "-function-alignment");
5895 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(FunctionAlignment)));
5896 }
5897
5898 if (const Arg *A =
5899 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5900 unsigned Value = 0;
5901 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5902 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5903 << A->getAsString(Args) << A->getValue();
5904 else if (!llvm::isPowerOf2_32(Value))
5905 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5906 << A->getAsString(Args) << A->getValue();
5907
5908 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5909 Twine(std::min(a: Value, b: 65536u))));
5910 }
5911
5912 // We support -falign-loops=N where N is a power of 2. GCC supports more
5913 // forms.
5914 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5915 unsigned Value = 0;
5916 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5917 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5918 << A->getAsString(Args) << A->getValue();
5919 else if (Value & (Value - 1))
5920 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5921 << A->getAsString(Args) << A->getValue();
5922 // Treat =0 as unspecified (use the target preference).
5923 if (Value)
5924 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5925 Twine(std::min(a: Value, b: 65536u))));
5926 }
5927
5928 if (Triple.isOSzOS()) {
5929 // On z/OS some of the system header feature macros need to
5930 // be defined to enable most cross platform projects to build
5931 // successfully. Ths include the libc++ library. A
5932 // complicating factor is that users can define these
5933 // macros to the same or different values. We need to add
5934 // the definition for these macros to the compilation command
5935 // if the user hasn't already defined them.
5936
5937 auto findMacroDefinition = [&](const std::string &Macro) {
5938 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5939 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5940 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5941 });
5942 };
5943
5944 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5945 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5946 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5947 // _OPEN_DEFAULT is required for XL compat
5948 if (!findMacroDefinition("_OPEN_DEFAULT"))
5949 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5950 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5951 // _XOPEN_SOURCE=600 is required for libcxx.
5952 if (!findMacroDefinition("_XOPEN_SOURCE"))
5953 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5954 }
5955 }
5956
5957 llvm::Reloc::Model RelocationModel;
5958 unsigned PICLevel;
5959 bool IsPIE;
5960 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5961 Arg *LastPICDataRelArg =
5962 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5963 Ids: options::OPT_mpic_data_is_text_relative);
5964 bool NoPICDataIsTextRelative = false;
5965 if (LastPICDataRelArg) {
5966 if (LastPICDataRelArg->getOption().matches(
5967 ID: options::OPT_mno_pic_data_is_text_relative)) {
5968 NoPICDataIsTextRelative = true;
5969 if (!PICLevel)
5970 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5971 << "-mno-pic-data-is-text-relative"
5972 << "-fpic/-fpie";
5973 }
5974 if (!Triple.isSystemZ())
5975 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5976 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5977 : "-mpic-data-is-text-relative")
5978 << RawTriple.str();
5979 }
5980
5981 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5982 RelocationModel == llvm::Reloc::ROPI_RWPI;
5983 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5984 RelocationModel == llvm::Reloc::ROPI_RWPI;
5985
5986 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5987 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5988 if (IsROPI)
5989 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5990 if (IsRWPI)
5991 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5992 }
5993
5994 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5995 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5996 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5997
5998 const char *RMName = RelocationModelName(Model: RelocationModel);
5999 if (RMName) {
6000 CmdArgs.push_back(Elt: "-mrelocation-model");
6001 CmdArgs.push_back(Elt: RMName);
6002 }
6003 if (PICLevel > 0) {
6004 CmdArgs.push_back(Elt: "-pic-level");
6005 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
6006 if (IsPIE)
6007 CmdArgs.push_back(Elt: "-pic-is-pie");
6008 if (NoPICDataIsTextRelative)
6009 CmdArgs.push_back(Elt: "-mcmodel=medium");
6010 }
6011
6012 if (RelocationModel == llvm::Reloc::ROPI ||
6013 RelocationModel == llvm::Reloc::ROPI_RWPI)
6014 CmdArgs.push_back(Elt: "-fropi");
6015 if (RelocationModel == llvm::Reloc::RWPI ||
6016 RelocationModel == llvm::Reloc::ROPI_RWPI)
6017 CmdArgs.push_back(Elt: "-frwpi");
6018
6019 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
6020 // values (e.g. 4, which has no triple representation, and invalid values).
6021 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
6022 StringRef Value = A->getValue();
6023 if (Value != "gnu" && Value != "5") {
6024 CmdArgs.push_back(Elt: "-meabi");
6025 CmdArgs.push_back(Elt: A->getValue());
6026 }
6027 }
6028
6029 // -fsemantic-interposition is forwarded to CC1: set the
6030 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
6031 // make default visibility external linkage definitions dso_preemptable.
6032 //
6033 // -fno-semantic-interposition: if the target supports .Lfoo$local local
6034 // aliases (make default visibility external linkage definitions dso_local).
6035 // This is the CC1 default for ELF to match COFF/Mach-O.
6036 //
6037 // Otherwise use Clang's traditional behavior: like
6038 // -fno-semantic-interposition but local aliases are not used. So references
6039 // can be interposed if not optimized out.
6040 if (Triple.isOSBinFormatELF()) {
6041 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
6042 Ids: options::OPT_fno_semantic_interposition);
6043 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6044 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6045 bool SupportsLocalAlias =
6046 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6047 if (!A)
6048 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
6049 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
6050 A->render(Args, Output&: CmdArgs);
6051 else if (!SupportsLocalAlias)
6052 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
6053 }
6054 }
6055
6056 {
6057 std::string Model;
6058 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
6059 if (!TC.isThreadModelSupported(Model: A->getValue()))
6060 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
6061 << A->getValue() << A->getAsString(Args);
6062 Model = A->getValue();
6063 } else
6064 Model = TC.getThreadModel();
6065 if (Model != "posix") {
6066 CmdArgs.push_back(Elt: "-mthread-model");
6067 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
6068 }
6069 }
6070
6071 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
6072 StringRef Name = A->getValue();
6073 if (Name == "SVML") {
6074 if (Triple.getArch() != llvm::Triple::x86 &&
6075 Triple.getArch() != llvm::Triple::x86_64)
6076 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6077 << Name << Triple.getArchName();
6078 } else if (Name == "AMDLIBM") {
6079 if (Triple.getArch() != llvm::Triple::x86 &&
6080 Triple.getArch() != llvm::Triple::x86_64)
6081 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6082 << Name << Triple.getArchName();
6083 } else if (Name == "libmvec") {
6084 if (Triple.getArch() != llvm::Triple::x86 &&
6085 Triple.getArch() != llvm::Triple::x86_64 &&
6086 Triple.getArch() != llvm::Triple::aarch64 &&
6087 Triple.getArch() != llvm::Triple::aarch64_be)
6088 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6089 << Name << Triple.getArchName();
6090 } else if (Name == "SLEEF" || Name == "ArmPL") {
6091 if (Triple.getArch() != llvm::Triple::aarch64 &&
6092 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6093 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6094 << Name << Triple.getArchName();
6095 }
6096 A->render(Args, Output&: CmdArgs);
6097 }
6098
6099 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
6100 Neg: options::OPT_fno_merge_all_constants, Default: false))
6101 CmdArgs.push_back(Elt: "-fmerge-all-constants");
6102
6103 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
6104 Neg: options::OPT_fno_delete_null_pointer_checks);
6105
6106 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
6107 Neg: options::OPT_fno_lifetime_dse);
6108
6109 // LLVM Code Generator Options.
6110
6111 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
6112 if (!Triple.isOSAIX() || Triple.isPPC32())
6113 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6114 << A->getSpelling() << RawTriple.str();
6115 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
6116 }
6117
6118 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
6119 // Emit the unsupported option error until the Clang's library integration
6120 // support for 128-bit long double is available for AIX.
6121 if (Triple.isOSAIX())
6122 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6123 << A->getSpelling() << RawTriple.str();
6124 }
6125
6126 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
6127 StringRef V = A->getValue(), V1 = V;
6128 unsigned Size;
6129 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
6130 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6131 << V << A->getOption().getName();
6132 else
6133 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
6134 }
6135
6136 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
6137 Neg: options::OPT_fno_jump_tables);
6138 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
6139 Neg: options::OPT_fno_profile_sample_accurate);
6140 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
6141 Neg: options::OPT_fno_preserve_as_comments);
6142
6143 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
6144 CmdArgs.push_back(Elt: "-mregparm");
6145 CmdArgs.push_back(Elt: A->getValue());
6146 }
6147
6148 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
6149 Ids: options::OPT_msvr4_struct_return)) {
6150 if (!TC.getTriple().isPPC32()) {
6151 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6152 << A->getSpelling() << RawTriple.str();
6153 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
6154 CmdArgs.push_back(Elt: "-maix-struct-return");
6155 } else {
6156 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6157 CmdArgs.push_back(Elt: "-msvr4-struct-return");
6158 }
6159 }
6160
6161 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
6162 Ids: options::OPT_freg_struct_return)) {
6163 if (TC.getArch() != llvm::Triple::x86) {
6164 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6165 << A->getSpelling() << RawTriple.str();
6166 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
6167 CmdArgs.push_back(Elt: "-fpcc-struct-return");
6168 } else {
6169 assert(A->getOption().matches(options::OPT_freg_struct_return));
6170 CmdArgs.push_back(Elt: "-freg-struct-return");
6171 }
6172 }
6173
6174 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
6175 if (Triple.getArch() == llvm::Triple::m68k)
6176 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
6177 else
6178 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
6179 }
6180
6181 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
6182 // enable-matrix is needed by both the LangOpts and by LLVM.
6183 CmdArgs.push_back(Elt: "-fenable-matrix");
6184 CmdArgs.push_back(Elt: "-mllvm");
6185 CmdArgs.push_back(Elt: "-enable-matrix");
6186 // Only handle default layout if matrix is enabled
6187 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
6188 StringRef Val = A->getValue();
6189 if (Val == "row-major" || Val == "column-major") {
6190 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
6191 CmdArgs.push_back(Elt: "-mllvm");
6192 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
6193
6194 } else {
6195 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6196 }
6197 }
6198 }
6199
6200 CodeGenOptions::FramePointerKind FPKeepKind =
6201 getFramePointerKind(Args, Triple: RawTriple);
6202 const char *FPKeepKindStr = nullptr;
6203 switch (FPKeepKind) {
6204 case CodeGenOptions::FramePointerKind::None:
6205 FPKeepKindStr = "-mframe-pointer=none";
6206 break;
6207 case CodeGenOptions::FramePointerKind::Reserved:
6208 FPKeepKindStr = "-mframe-pointer=reserved";
6209 break;
6210 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
6211 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6212 break;
6213 case CodeGenOptions::FramePointerKind::NonLeaf:
6214 FPKeepKindStr = "-mframe-pointer=non-leaf";
6215 break;
6216 case CodeGenOptions::FramePointerKind::All:
6217 FPKeepKindStr = "-mframe-pointer=all";
6218 break;
6219 }
6220 assert(FPKeepKindStr && "unknown FramePointerKind");
6221 CmdArgs.push_back(Elt: FPKeepKindStr);
6222
6223 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
6224 Neg: options::OPT_fno_zero_initialized_in_bss);
6225
6226 bool OFastEnabled = isOptimizationLevelFast(Args);
6227 if (Args.hasArg(Ids: options::OPT_Ofast))
6228 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
6229 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6230 // enabled. This alias option is being used to simplify the hasFlag logic.
6231 OptSpecifier StrictAliasingAliasOption =
6232 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6233 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6234 // doesn't do any TBAA.
6235 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
6236 Neg: options::OPT_fno_strict_aliasing,
6237 Default: !IsWindowsMSVC && !IsUEFI))
6238 CmdArgs.push_back(Elt: "-relaxed-aliasing");
6239 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
6240 Default: false))
6241 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
6242 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
6243 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
6244 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
6245
6246 if (Arg *A = Args.getLastArg(Ids: options::OPT_fstrict_bool,
6247 Ids: options::OPT_fno_strict_bool,
6248 Ids: options::OPT_fno_strict_bool_EQ)) {
6249 StringRef BFM = "";
6250 if (A->getOption().matches(ID: options::OPT_fstrict_bool))
6251 BFM = "strict";
6252 else if (A->getOption().matches(ID: options::OPT_fno_strict_bool))
6253 BFM = "nonstrict";
6254 else if (A->getValue() == StringRef("truncate"))
6255 BFM = "truncate";
6256 else if (A->getValue() == StringRef("nonzero"))
6257 BFM = "nonzero";
6258 else
6259 D.Diag(DiagID: diag::err_drv_invalid_value)
6260 << A->getAsString(Args) << A->getValue();
6261 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-load-bool-from-mem=" + BFM));
6262 } else if (KernelOrKext) {
6263 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6264 CmdArgs.push_back(Elt: "-load-bool-from-mem=truncate");
6265 }
6266
6267 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
6268 Neg: options::OPT_fno_strict_enums);
6269 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
6270 Neg: options::OPT_fno_strict_return);
6271 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
6272 Neg: options::OPT_fno_allow_editor_placeholders);
6273 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
6274 Neg: options::OPT_fno_strict_vtable_pointers);
6275 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
6276 Neg: options::OPT_fno_force_emit_vtables);
6277 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
6278 Neg: options::OPT_fno_optimize_sibling_calls);
6279 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
6280 Neg: options::OPT_fno_escaping_block_tail_calls);
6281
6282 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
6283 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
6284
6285 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6286 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6287
6288 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6289 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6290
6291 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
6292 Ids: options::OPT_fno_disable_block_signature_string);
6293
6294 // Handle segmented stacks.
6295 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
6296 Neg: options::OPT_fno_split_stack);
6297
6298 // -fprotect-parens=0 is default.
6299 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
6300 Neg: options::OPT_fno_protect_parens, Default: false))
6301 CmdArgs.push_back(Elt: "-fprotect-parens");
6302
6303 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6304
6305 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
6306 Neg: options::OPT_fno_atomic_remote_memory);
6307 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
6308 Neg: options::OPT_fno_atomic_fine_grained_memory);
6309 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
6310 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
6311
6312 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
6313 const llvm::Triple::ArchType Arch = TC.getArch();
6314 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6315 StringRef V = A->getValue();
6316 if (V == "64")
6317 CmdArgs.push_back(Elt: "-fextend-arguments=64");
6318 else if (V != "32")
6319 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6320 << A->getValue() << A->getOption().getName();
6321 } else
6322 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6323 << A->getOption().getName() << TripleStr;
6324 }
6325
6326 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
6327 if (TC.getArch() == llvm::Triple::avr)
6328 A->render(Args, Output&: CmdArgs);
6329 else
6330 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6331 << A->getAsString(Args) << TripleStr;
6332 }
6333
6334 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
6335 if (TC.getTriple().isX86())
6336 A->render(Args, Output&: CmdArgs);
6337 else if (TC.getTriple().isPPC() &&
6338 (A->getOption().getID() != options::OPT_mlong_double_80))
6339 A->render(Args, Output&: CmdArgs);
6340 else
6341 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6342 << A->getAsString(Args) << TripleStr;
6343 }
6344
6345 // Decide whether to use verbose asm. Verbose assembly is the default on
6346 // toolchains which have the integrated assembler on by default.
6347 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6348 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
6349 Default: IsIntegratedAssemblerDefault))
6350 CmdArgs.push_back(Elt: "-fno-verbose-asm");
6351
6352 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6353 // use that to indicate the MC default in the backend.
6354 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
6355 StringRef V = A->getValue();
6356 unsigned Num;
6357 if (V == "none")
6358 A->render(Args, Output&: CmdArgs);
6359 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
6360 (V.empty() || (V.consume_front(Prefix: ".") &&
6361 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
6362 A->render(Args, Output&: CmdArgs);
6363 else
6364 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6365 << A->getValue() << A->getOption().getName();
6366 }
6367
6368 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6369 // option to disable integrated-as explicitly.
6370 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
6371 CmdArgs.push_back(Elt: "-no-integrated-as");
6372
6373 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
6374 CmdArgs.push_back(Elt: "-mdebug-pass");
6375 CmdArgs.push_back(Elt: "Structure");
6376 }
6377 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
6378 CmdArgs.push_back(Elt: "-mdebug-pass");
6379 CmdArgs.push_back(Elt: "Arguments");
6380 }
6381
6382 // Enable -mconstructor-aliases except on darwin, where we have to work around
6383 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6384 // code, where aliases aren't supported.
6385 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6386 CmdArgs.push_back(Elt: "-mconstructor-aliases");
6387
6388 // Darwin's kernel doesn't support guard variables; just die if we
6389 // try to use them.
6390 if (KernelOrKext && RawTriple.isOSDarwin())
6391 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6392
6393 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6394 Ids: options::OPT_mno_ms_bitfields)) {
6395 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6396 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6397 else
6398 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6399 }
6400
6401 if (Triple.isOSCygMing()) {
6402 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6403 Neg: options::OPT_fno_auto_import);
6404 }
6405
6406 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6407 Default: Triple.isX86() && IsWindowsMSVC))
6408 CmdArgs.push_back(Elt: "-fms-volatile");
6409
6410 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6411 // defaults to -fno-direct-access-external-data. Pass the option if different
6412 // from the default.
6413 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6414 Ids: options::OPT_fno_direct_access_external_data)) {
6415 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6416 (PICLevel == 0))
6417 A->render(Args, Output&: CmdArgs);
6418 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6419 // Some targets default to -fno-direct-access-external-data even for
6420 // -fno-pic.
6421 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6422 }
6423
6424 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6425 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6426
6427 // -fhosted is default.
6428 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6429 // use Freestanding.
6430 bool Freestanding =
6431 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6432 KernelOrKext;
6433 if (Freestanding)
6434 CmdArgs.push_back(Elt: "-ffreestanding");
6435
6436 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6437
6438 BoundArch OffloadArch = JA.getOffloadingArch();
6439 auto SanitizeArgs =
6440 TC.getSanitizerArgs(JobArgs: Args, BA: OffloadArch, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6441 Args.AddLastArg(Output&: CmdArgs,
6442 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6443
6444 // This is a coarse approximation of what llvm-gcc actually does, both
6445 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6446 // complicated ways.
6447 bool IsAsyncUnwindTablesDefault =
6448 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6449 bool IsSyncUnwindTablesDefault =
6450 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6451
6452 bool AsyncUnwindTables = Args.hasFlag(
6453 Pos: options::OPT_fasynchronous_unwind_tables,
6454 Neg: options::OPT_fno_asynchronous_unwind_tables,
6455 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6456 !Freestanding);
6457 bool UnwindTables =
6458 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6459 Default: IsSyncUnwindTablesDefault && !Freestanding);
6460 if (AsyncUnwindTables)
6461 CmdArgs.push_back(Elt: "-funwind-tables=2");
6462 else if (UnwindTables)
6463 CmdArgs.push_back(Elt: "-funwind-tables=1");
6464
6465 // Sframe unwind tables are independent of the other types. Although also
6466 // defined for aarch64, only x86_64 support is implemented at the moment.
6467 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6468 if (Triple.isOSBinFormatELF() && Triple.isX86())
6469 CmdArgs.push_back(Elt: "--gsframe");
6470 else
6471 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6472 << A->getOption().getName() << TripleStr;
6473 }
6474
6475 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6476 // `--gpu-use-aux-triple-only` is specified.
6477 if (AuxTriple && !Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only)) {
6478 const ArgList &HostArgs =
6479 C.getArgsForToolChain(TC: nullptr, BA: BoundArch(), DeviceOffloadKind: Action::OFK_None);
6480 std::string HostCPU = getCPUName(D, Args: HostArgs, T: *AuxTriple, /*FromAs*/ false);
6481 if (!HostCPU.empty()) {
6482 CmdArgs.push_back(Elt: "-aux-target-cpu");
6483 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6484 }
6485 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6486 /*ForAS*/ false, /*IsAux*/ true);
6487 }
6488
6489 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
6490 DeviceOffloadKind: JA.getOffloadingDeviceKind());
6491
6492 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6493
6494 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6495 StringRef Value = A->getValue();
6496 unsigned TLSSize = 0;
6497 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6498 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6499 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6500 << A->getOption().getName() << TripleStr;
6501 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6502 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6503 << A->getOption().getName() << Value;
6504 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6505 }
6506
6507 if (isTLSDESCEnabled(TC, Args))
6508 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6509
6510 // Add the target cpu
6511 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6512 if (!CPU.empty()) {
6513 CmdArgs.push_back(Elt: "-target-cpu");
6514 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6515 }
6516
6517 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6518
6519 // Add clang-cl arguments.
6520 types::ID InputType = Input.getType();
6521 if (D.IsCLMode())
6522 AddClangCLArgs(Args, InputType, CmdArgs);
6523
6524 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6525 llvm::codegenoptions::NoDebugInfo;
6526 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6527 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6528 DebugInfoKind, DwarfFission, IsUsingLTO);
6529
6530 // Add the split debug info name to the command lines here so we
6531 // can propagate it to the backend.
6532 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6533 (TC.getTriple().isOSBinFormatELF() ||
6534 TC.getTriple().isOSBinFormatWasm() ||
6535 TC.getTriple().isOSBinFormatCOFF()) &&
6536 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6537 isa<BackendJobAction>(Val: JA));
6538 if (SplitDWARF) {
6539 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6540 CmdArgs.push_back(Elt: "-split-dwarf-file");
6541 CmdArgs.push_back(Elt: SplitDWARFOut);
6542 if (DwarfFission == DwarfFissionKind::Split) {
6543 CmdArgs.push_back(Elt: "-split-dwarf-output");
6544 CmdArgs.push_back(Elt: SplitDWARFOut);
6545 }
6546 }
6547
6548 // Pass the linker version in use.
6549 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6550 CmdArgs.push_back(Elt: "-target-linker-version");
6551 CmdArgs.push_back(Elt: A->getValue());
6552 }
6553
6554 // Explicitly error on some things we know we don't support and can't just
6555 // ignore.
6556 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6557 Arg *Unsupported;
6558 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6559 TC.getArch() == llvm::Triple::x86) {
6560 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6561 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6562 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6563 << Unsupported->getOption().getName();
6564 }
6565 // The faltivec option has been superseded by the maltivec option.
6566 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6567 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6568 << Unsupported->getOption().getName()
6569 << "please use -maltivec and include altivec.h explicitly";
6570 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6571 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6572 << Unsupported->getOption().getName() << "please use -mno-altivec";
6573 }
6574
6575 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6576
6577 if (Args.getLastArg(Ids: options::OPT_H)) {
6578 CmdArgs.push_back(Elt: "-H");
6579 CmdArgs.push_back(Elt: "-sys-header-deps");
6580 }
6581 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6582
6583 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6584 CmdArgs.push_back(Elt: "-header-include-file");
6585 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6586 ? D.CCPrintHeadersFilename.c_str()
6587 : "-");
6588 CmdArgs.push_back(Elt: "-sys-header-deps");
6589 CmdArgs.push_back(Elt: Args.MakeArgString(
6590 Str: "-header-include-format=" +
6591 Twine(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6592 CmdArgs.push_back(Elt: Args.MakeArgString(
6593 Str: "-header-include-filtering=" +
6594 Twine(headerIncludeFilteringKindToString(K: D.CCPrintHeadersFiltering))));
6595 }
6596 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6597 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6598
6599 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6600 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6601 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6602 ? D.CCLogDiagnosticsFilename.c_str()
6603 : "-");
6604 }
6605
6606 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6607 // crashes.
6608 if (D.CCGenDiagnostics)
6609 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6610
6611 // Allow backend to put its diagnostic files in the same place as frontend
6612 // crash diagnostics files.
6613 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6614 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6615 CmdArgs.push_back(Elt: "-mllvm");
6616 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6617 }
6618
6619 addSeparateSectionFlags(Triple, Args, CmdArgs);
6620
6621 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6622 Ids: options::OPT_fno_basic_block_address_map)) {
6623 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6624 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6625 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6626 A->render(Args, Output&: CmdArgs);
6627 } else {
6628 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6629 << A->getAsString(Args) << TripleStr;
6630 }
6631 }
6632
6633 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6634 StringRef Val = A->getValue();
6635 if (Val == "labels") {
6636 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6637 << A->getAsString(Args) << /*hasReplacement=*/true
6638 << "-fbasic-block-address-map";
6639 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6640 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6641 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6642 D.Diag(DiagID: diag::err_drv_invalid_value)
6643 << A->getAsString(Args) << A->getValue();
6644 else
6645 A->render(Args, Output&: CmdArgs);
6646 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6647 // "all" is not supported on AArch64 since branch relaxation creates new
6648 // basic blocks for some cross-section branches.
6649 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6650 D.Diag(DiagID: diag::err_drv_invalid_value)
6651 << A->getAsString(Args) << A->getValue();
6652 else
6653 A->render(Args, Output&: CmdArgs);
6654 } else if (Triple.isNVPTX()) {
6655 // Do not pass the option to the GPU compilation. We still want it enabled
6656 // for the host-side compilation, so seeing it here is not an error.
6657 } else if (Val != "none") {
6658 // =none is allowed everywhere. It's useful for overriding the option
6659 // and is the same as not specifying the option.
6660 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6661 << A->getAsString(Args) << TripleStr;
6662 }
6663 }
6664
6665 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6666 Neg: options::OPT_fno_unique_section_names);
6667 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6668 Neg: options::OPT_fno_separate_named_sections);
6669 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6670 Neg: options::OPT_fno_unique_internal_linkage_names);
6671 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6672 Neg: options::OPT_fno_unique_basic_block_section_names);
6673
6674 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6675
6676 if (Arg *A =
6677 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6678 Ids: options::OPT_fno_partition_static_data_sections)) {
6679 if (!A->getOption().matches(
6680 ID: options::OPT_fno_partition_static_data_sections)) {
6681 // This codegen pass is only available on x86 and AArch64 ELF targets.
6682 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6683 A->render(Args, Output&: CmdArgs);
6684 CmdArgs.push_back(Elt: "-mllvm");
6685 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6686 } else
6687 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6688 << A->getAsString(Args) << TripleStr;
6689 }
6690 }
6691
6692 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6693 Ids: options::OPT_finstrument_functions_after_inlining,
6694 Ids: options::OPT_finstrument_function_entry_bare);
6695 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6696 Ids: options::OPT_fno_convergent_functions);
6697
6698 // NVPTX doesn't support PGO or coverage
6699 if (!Triple.isNVPTX())
6700 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6701
6702 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6703
6704 if (getLastProfileSampleUseArg(Args) &&
6705 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6706 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6707 CmdArgs.push_back(Elt: "-mllvm");
6708 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6709 }
6710
6711 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6712 if (RawTriple.isPS() &&
6713 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6714 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6715 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6716 }
6717
6718 // Pass options for controlling the default header search paths.
6719 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6720 CmdArgs.push_back(Elt: "-nostdsysteminc");
6721 CmdArgs.push_back(Elt: "-nobuiltininc");
6722 } else {
6723 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6724 CmdArgs.push_back(Elt: "-nostdsysteminc");
6725 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6726 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6727 }
6728
6729 // Pass the path to compiler resource files.
6730 CmdArgs.push_back(Elt: "-resource-dir");
6731 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6732
6733 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6734
6735 // Add preprocessing options like -I, -D, etc. if we are using the
6736 // preprocessor.
6737 //
6738 // FIXME: Support -fpreprocessed
6739 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6740 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6741
6742 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6743 // that "The compiler can only warn and ignore the option if not recognized".
6744 // When building with ccache, it will pass -D options to clang even on
6745 // preprocessed inputs and configure concludes that -fPIC is not supported.
6746 Args.ClaimAllArgs(Id0: options::OPT_D);
6747
6748 // Warn about ignored options to clang.
6749 for (const Arg *A :
6750 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6751 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6752 A->claim();
6753 }
6754
6755 for (const Arg *A :
6756 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6757 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6758 A->claim();
6759 }
6760
6761 claimNoWarnArgs(Args);
6762
6763 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6764
6765 for (const Arg *A :
6766 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6767 A->claim();
6768 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6769 unsigned WarningNumber;
6770 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6771 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6772 << A->getAsString(Args) << A->getValue();
6773 continue;
6774 }
6775
6776 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6777 CmdArgs.push_back(Elt: Args.MakeArgString(
6778 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6779 }
6780 continue;
6781 }
6782 A->render(Args, Output&: CmdArgs);
6783 }
6784
6785 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6786
6787 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6788 CmdArgs.push_back(Elt: "-pedantic");
6789 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6790 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6791
6792 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6793 Neg: options::OPT_fno_fixed_point);
6794
6795 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6796 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6797
6798 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6799 A->render(Args, Output&: CmdArgs);
6800
6801 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6802 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6803
6804 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6805 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6806
6807 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6808 A->render(Args, Output&: CmdArgs);
6809
6810 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6811 // (-ansi is equivalent to -std=c89 or -std=c++98).
6812 //
6813 // If a std is supplied, only add -trigraphs if it follows the
6814 // option.
6815 bool ImplyVCPPCVer = false;
6816 bool ImplyVCPPCXXVer = false;
6817 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6818 if (Std) {
6819 if (Std->getOption().matches(ID: options::OPT_ansi))
6820 if (types::isCXX(Id: InputType))
6821 CmdArgs.push_back(Elt: "-std=c++98");
6822 else
6823 CmdArgs.push_back(Elt: "-std=c89");
6824 else {
6825 if (IsSYCL) {
6826 const LangStandard *LangStd =
6827 LangStandard::getLangStandardForName(Name: Std->getValue());
6828 if (LangStd) {
6829 // Use of -std= with 'C' is not supported for SYCL.
6830 if (LangStd->getLanguage() == Language::C)
6831 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
6832 << Std->getAsString(Args) << "-fsycl";
6833 // SYCL requires C++17 or later.
6834 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6835 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6836 }
6837 }
6838 Std->render(Args, Output&: CmdArgs);
6839 }
6840
6841 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6842 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6843 Ids: options::OPT_ftrigraphs,
6844 Ids: options::OPT_fno_trigraphs))
6845 if (A != Std)
6846 A->render(Args, Output&: CmdArgs);
6847 } else {
6848 // Honor -std-default.
6849 //
6850 // FIXME: Clang doesn't correctly handle -std= when the input language
6851 // doesn't match. For the time being just ignore this for C++ inputs;
6852 // eventually we want to do all the standard defaulting here instead of
6853 // splitting it between the driver and clang -cc1.
6854 if (!types::isCXX(Id: InputType)) {
6855 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6856 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6857 /*Joined=*/true);
6858 } else
6859 ImplyVCPPCVer = true;
6860 }
6861 else if (IsWindowsMSVC)
6862 ImplyVCPPCXXVer = true;
6863
6864 if (IsSYCL && types::isCXX(Id: InputType) &&
6865 !Args.hasArg(Ids: options::OPT__SLASH_std) && !IsWindowsMSVC)
6866 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6867 // on the command line will override. On Windows MSVC, this is handled
6868 // by the ImplyVCPPCXXVer path below.
6869 CmdArgs.push_back(Elt: "-std=c++17");
6870
6871 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6872 Ids: options::OPT_fno_trigraphs);
6873 }
6874
6875 // GCC's behavior for -Wwrite-strings is a bit strange:
6876 // * In C, this "warning flag" changes the types of string literals from
6877 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6878 // for the discarded qualifier.
6879 // * In C++, this is just a normal warning flag.
6880 //
6881 // Implementing this warning correctly in C is hard, so we follow GCC's
6882 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6883 // a non-const char* in C, rather than using this crude hack.
6884 if (!types::isCXX(Id: InputType)) {
6885 // FIXME: This should behave just like a warning flag, and thus should also
6886 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6887 Arg *WriteStrings =
6888 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6889 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6890 if (WriteStrings &&
6891 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6892 CmdArgs.push_back(Elt: "-fconst-strings");
6893 }
6894
6895 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6896 // during C++ compilation, which it is by default. GCC keeps this define even
6897 // in the presence of '-w', match this behavior bug-for-bug.
6898 if (types::isCXX(Id: InputType) &&
6899 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6900 Default: true)) {
6901 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6902 }
6903
6904 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6905 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6906 if (Asm->getOption().matches(ID: options::OPT_fasm))
6907 CmdArgs.push_back(Elt: "-fgnu-keywords");
6908 else
6909 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6910 }
6911
6912 if (!ShouldEnableAutolink(Args, TC, JA))
6913 CmdArgs.push_back(Elt: "-fno-autolink");
6914
6915 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6916 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6917 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6918 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6919
6920 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6921
6922 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6923 Args.ClaimAllArgs(Id0: options::OPT_fexperimental_new_constant_interpreter);
6924 Args.AddLastArg(Output&: CmdArgs,
6925 Ids: options::OPT_fno_experimental_new_constant_interpreter);
6926 } else {
6927 Args.ClaimAllArgs(Id0: options::OPT_fno_experimental_new_constant_interpreter);
6928 Args.AddLastArg(Output&: CmdArgs,
6929 Ids: options::OPT_fexperimental_new_constant_interpreter);
6930 }
6931
6932 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6933 CmdArgs.push_back(Elt: "-fbracket-depth");
6934 CmdArgs.push_back(Elt: A->getValue());
6935 }
6936
6937 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6938 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6939 if (A->getNumValues()) {
6940 StringRef bytes = A->getValue();
6941 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6942 } else
6943 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6944 }
6945
6946 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6947 CmdArgs.push_back(Elt: "-relocatable-pch");
6948
6949 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6950 static const char *kCFABIs[] = {
6951 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6952 };
6953
6954 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6955 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6956 else
6957 A->render(Args, Output&: CmdArgs);
6958 }
6959
6960 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6961 CmdArgs.push_back(Elt: "-fconstant-string-class");
6962 CmdArgs.push_back(Elt: A->getValue());
6963 }
6964
6965 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_array_class_EQ)) {
6966 CmdArgs.push_back(Elt: "-fconstant-array-class");
6967 CmdArgs.push_back(Elt: A->getValue());
6968 }
6969 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_dictionary_class_EQ)) {
6970 CmdArgs.push_back(Elt: "-fconstant-dictionary-class");
6971 CmdArgs.push_back(Elt: A->getValue());
6972 }
6973 if (Arg *A =
6974 Args.getLastArg(Ids: options::OPT_fconstant_integer_number_class_EQ)) {
6975 CmdArgs.push_back(Elt: "-fconstant-integer-number-class");
6976 CmdArgs.push_back(Elt: A->getValue());
6977 }
6978 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_float_number_class_EQ)) {
6979 CmdArgs.push_back(Elt: "-fconstant-float-number-class");
6980 CmdArgs.push_back(Elt: A->getValue());
6981 }
6982 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_double_number_class_EQ)) {
6983 CmdArgs.push_back(Elt: "-fconstant-double-number-class");
6984 CmdArgs.push_back(Elt: A->getValue());
6985 }
6986
6987 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6988 CmdArgs.push_back(Elt: "-ftabstop");
6989 CmdArgs.push_back(Elt: A->getValue());
6990 }
6991
6992 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6993 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6994 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6995
6996 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6997 Neg: options::OPT_fno_stack_size_section);
6998
6999 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
7000 CmdArgs.push_back(Elt: "-stack-usage-file");
7001
7002 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
7003 SmallString<128> OutputFilename(OutputOpt->getValue());
7004 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
7005 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
7006 } else
7007 CmdArgs.push_back(
7008 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
7009 }
7010
7011 CmdArgs.push_back(Elt: "-ferror-limit");
7012 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
7013 CmdArgs.push_back(Elt: A->getValue());
7014 else
7015 CmdArgs.push_back(Elt: "19");
7016
7017 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
7018 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
7019 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
7020 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
7021 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
7022
7023 // Pass -fmessage-length=.
7024 unsigned MessageLength = 0;
7025 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
7026 StringRef V(A->getValue());
7027 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
7028 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7029 << V << A->getOption().getName();
7030 } else {
7031 // If -fmessage-length=N was not specified, determine whether this is a
7032 // terminal and, if so, implicitly define -fmessage-length appropriately.
7033 MessageLength = llvm::sys::Process::StandardErrColumns();
7034 }
7035 if (MessageLength != 0)
7036 CmdArgs.push_back(
7037 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
7038
7039 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
7040 CmdArgs.push_back(
7041 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
7042
7043 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
7044 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
7045 Twine(A->getValue(N: 0))));
7046
7047 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7048 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
7049 Ids: options::OPT_fvisibility_ms_compat)) {
7050 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
7051 A->render(Args, Output&: CmdArgs);
7052 } else {
7053 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7054 CmdArgs.push_back(Elt: "-fvisibility=hidden");
7055 CmdArgs.push_back(Elt: "-ftype-visibility=default");
7056 }
7057 } else if (IsOpenMPDevice) {
7058 // When compiling for the OpenMP device we want protected visibility by
7059 // default. This prevents the device from accidentally preempting code on
7060 // the host, makes the system more robust, and improves performance.
7061 CmdArgs.push_back(Elt: "-fvisibility=protected");
7062 }
7063
7064 // PS4/PS5 process these options in addClangTargetOptions.
7065 if (!RawTriple.isPS()) {
7066 if (const Arg *A =
7067 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
7068 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
7069 if (A->getOption().matches(
7070 ID: options::OPT_fvisibility_from_dllstorageclass)) {
7071 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
7072 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
7073 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
7074 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
7075 Args.AddLastArg(Output&: CmdArgs,
7076 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7077 }
7078 }
7079 }
7080
7081 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
7082 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
7083 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
7084
7085 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
7086 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
7087
7088 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7089 // -fvisibility-global-new-delete=force-hidden.
7090 if (const Arg *A =
7091 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7092 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
7093 << A->getAsString(Args) << /*hasReplacement=*/true
7094 << "-fvisibility-global-new-delete=force-hidden";
7095 }
7096
7097 if (const Arg *A =
7098 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
7099 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7100 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
7101 A->render(Args, Output&: CmdArgs);
7102 } else {
7103 assert(A->getOption().matches(
7104 options::OPT_fvisibility_global_new_delete_hidden));
7105 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
7106 }
7107 }
7108
7109 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
7110
7111 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
7112 Neg: options::OPT_fno_new_infallible, Default: false))
7113 CmdArgs.push_back(Elt: "-fnew-infallible");
7114
7115 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
7116 Neg: options::OPT_foperator_names, Default: false))
7117 CmdArgs.push_back(Elt: "-fno-operator-names");
7118
7119 // Forward -f (flag) options which we can pass directly.
7120 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
7121 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
7122 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
7123 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
7124 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
7125 Ids: options::OPT_fno_raw_string_literals);
7126
7127 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
7128 Default: Triple.hasDefaultEmulatedTLS()))
7129 CmdArgs.push_back(Elt: "-femulated-tls");
7130
7131 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
7132 Neg: options::OPT_fno_check_new);
7133
7134 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
7135 // FIXME: There's no reason for this to be restricted to some backend.
7136 // The backend code needs to be changed to include the appropriate function
7137 // calls automatically.
7138 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7139 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7140 << A->getAsString(Args) << TripleStr;
7141 }
7142
7143 // AltiVec-like language extensions aren't relevant for assembling.
7144 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
7145 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
7146
7147 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
7148 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
7149
7150 // Forward flags for OpenMP. We don't do this if the current action is an
7151 // device offloading action other than OpenMP.
7152 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
7153 Neg: options::OPT_fno_openmp, Default: false) &&
7154 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7155 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
7156 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
7157 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
7158
7159 // Determine if target-fast optimizations should be enabled
7160 bool TargetFastUsed =
7161 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
7162 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
7163 switch (D.getOpenMPRuntime(Args)) {
7164 case Driver::OMPRT_OMP:
7165 case Driver::OMPRT_IOMP5:
7166 // Clang can generate useful OpenMP code for these two runtime libraries.
7167 CmdArgs.push_back(Elt: "-fopenmp");
7168
7169 // If no option regarding the use of TLS in OpenMP codegeneration is
7170 // given, decide a default based on the target. Otherwise rely on the
7171 // options and pass the right information to the frontend.
7172 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
7173 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7174 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
7175 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7176 Ids: options::OPT_fno_openmp_simd);
7177 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
7178 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7179 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
7180 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
7181 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
7182 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
7183 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7184 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7185 // effect: the teams reduction buffer is sized at kernel launch by the
7186 // offload plugin to match the actual number of teams. Honoring a
7187 // smaller user-supplied value would silently truncate the buffer for
7188 // larger launches.
7189 if (Arg *A = Args.getLastArg(
7190 Ids: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7191 D.Diag(DiagID: diag::warn_drv_deprecated_custom)
7192 << A->getAsString(Args)
7193 << "the value is ignored; the teams reduction buffer is sized "
7194 "automatically at kernel launch";
7195 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
7196 Neg: options::OPT_fno_openmp_optimistic_collapse,
7197 /*Default=*/false))
7198 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
7199
7200 // When in OpenMP offloading mode with NVPTX target, forward
7201 // cuda-mode flag
7202 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
7203 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7204 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
7205
7206 // When in OpenMP offloading mode, enable debugging on the device.
7207 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
7208 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
7209 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
7210 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
7211
7212 // When in OpenMP offloading mode, forward assumptions information about
7213 // thread and team counts in the device.
7214 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
7215 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
7216 /*Default=*/TargetFastUsed))
7217 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
7218 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
7219 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
7220 /*Default=*/TargetFastUsed))
7221 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
7222
7223 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7224 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
7225 Neg: options::OPT_fno_openmp_assume_no_thread_state,
7226 /*Default=*/TargetFastUsed))
7227 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
7228
7229 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7230 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
7231 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
7232 /*Default=*/TargetFastUsed))
7233 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
7234
7235 // Handle -fopenmp-target-atomic-reduction.
7236 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_atomic_reduction,
7237 Neg: options::OPT_fno_openmp_target_atomic_reduction,
7238 /*Default=*/false))
7239 CmdArgs.push_back(Elt: "-fopenmp-target-atomic-reduction");
7240
7241 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
7242 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
7243 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
7244 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
7245 break;
7246 default:
7247 // By default, if Clang doesn't know how to generate useful OpenMP code
7248 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7249 // down to the actual compilation.
7250 // FIXME: It would be better to have a mode which *only* omits IR
7251 // generation based on the OpenMP support so that we get consistent
7252 // semantic analysis, etc.
7253 break;
7254 }
7255 } else {
7256 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7257 Ids: options::OPT_fno_openmp_simd);
7258 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7259 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
7260 Neg: options::OPT_fno_openmp_extensions);
7261 }
7262 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7263 // runtime.
7264 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7265 Neg: options::OPT_fno_offload_via_llvm, Default: false))
7266 CmdArgs.push_back(Elt: "-foffload-via-llvm");
7267
7268 const XRayArgs &XRay = TC.getXRayArgs(Args);
7269 XRay.addArgs(TC, Args, CmdArgs, InputType);
7270
7271 for (const auto &Filename :
7272 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
7273 if (D.getVFS().exists(Path: Filename))
7274 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
7275 else
7276 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
7277 }
7278
7279 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
7280 StringRef S0 = A->getValue(), S = S0;
7281 unsigned Size, Offset = 0;
7282 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7283 !Triple.isX86() && !Triple.isSystemZ() &&
7284 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7285 Triple.getArch() == llvm::Triple::ppc64 ||
7286 Triple.getArch() == llvm::Triple::ppc64le)))
7287 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7288 << A->getAsString(Args) << TripleStr;
7289 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
7290 (!S.empty() &&
7291 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
7292 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
7293 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7294 << S0 << A->getOption().getName();
7295 else if (Size < Offset)
7296 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
7297 else {
7298 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
7299 CmdArgs.push_back(Elt: Args.MakeArgString(
7300 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
7301 if (!S.empty())
7302 CmdArgs.push_back(
7303 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
7304 }
7305 }
7306
7307 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
7308
7309 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
7310 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
7311
7312 for (const auto &A :
7313 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
7314 CmdArgs.push_back(
7315 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
7316
7317 if (TC.SupportsProfiling()) {
7318 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
7319
7320 llvm::Triple::ArchType Arch = TC.getArch();
7321 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
7322 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7323 A->render(Args, Output&: CmdArgs);
7324 else
7325 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7326 << A->getAsString(Args) << TripleStr;
7327 }
7328 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
7329 if (Arch == llvm::Triple::systemz)
7330 A->render(Args, Output&: CmdArgs);
7331 else
7332 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7333 << A->getAsString(Args) << TripleStr;
7334 }
7335 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
7336 if (Arch == llvm::Triple::systemz)
7337 A->render(Args, Output&: CmdArgs);
7338 else
7339 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7340 << A->getAsString(Args) << TripleStr;
7341 }
7342 }
7343
7344 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
7345 if (TC.getTriple().isOSzOS()) {
7346 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7347 << A->getAsString(Args) << TripleStr;
7348 }
7349 }
7350 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
7351 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7352 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7353 << A->getAsString(Args) << TripleStr;
7354 }
7355 }
7356 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
7357 if (A->getOption().matches(ID: options::OPT_p)) {
7358 A->claim();
7359 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
7360 CmdArgs.push_back(Elt: "-pg");
7361 }
7362 }
7363
7364 // Reject AIX-specific link options on other targets.
7365 if (!TC.getTriple().isOSAIX()) {
7366 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
7367 Ids: options::OPT_mxcoff_build_id_EQ)) {
7368 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7369 << A->getSpelling() << TripleStr;
7370 }
7371 }
7372
7373 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
7374 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
7375 CmdArgs.push_back(Elt: "-fapple-kext");
7376
7377 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
7378 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
7379 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
7380 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
7381 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
7382 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
7383 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
7384 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
7385 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
7386 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
7387 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
7388
7389 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
7390 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
7391 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
7392 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
7393 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_compress_EQ);
7394 }
7395
7396 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
7397 CmdArgs.push_back(Elt: "-ftrapv-handler");
7398 CmdArgs.push_back(Elt: A->getValue());
7399 }
7400
7401 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
7402
7403 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
7404 Ids: options::OPT_fno_finite_loops);
7405
7406 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
7407 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
7408 Ids: options::OPT_fno_unroll_loops);
7409 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
7410 Ids: options::OPT_fno_loop_interchange);
7411 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
7412 Neg: options::OPT_fno_experimental_loop_fusion);
7413
7414 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
7415
7416 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
7417
7418 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
7419 Neg: options::OPT_mno_speculative_load_hardening);
7420
7421 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7422 RenderSCPOptions(TC, Args, CmdArgs);
7423 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7424
7425 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7426
7427 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7428 Neg: options::OPT_mno_stackrealign);
7429
7430 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7431 StringRef Value = A->getValue();
7432 int64_t Alignment = 0;
7433 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7434 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7435 << Value << A->getOption().getName();
7436 else if (Alignment & (Alignment - 1))
7437 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7438 << A->getAsString(Args) << Value;
7439 else
7440 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7441 }
7442
7443 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7444 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7445
7446 if (!Size.empty())
7447 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7448 else
7449 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7450 }
7451
7452 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7453 Neg: options::OPT_mno_stack_arg_probe);
7454
7455 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7456 Ids: options::OPT_mno_restrict_it)) {
7457 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7458 CmdArgs.push_back(Elt: "-mllvm");
7459 CmdArgs.push_back(Elt: "-arm-restrict-it");
7460 } else {
7461 CmdArgs.push_back(Elt: "-mllvm");
7462 CmdArgs.push_back(Elt: "-arm-default-it");
7463 }
7464 }
7465
7466 // Forward -cl options to -cc1
7467 RenderOpenCLOptions(Args, CmdArgs, InputType);
7468
7469 // Forward hlsl options to -cc1
7470 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7471
7472 // Forward OpenACC options to -cc1
7473 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7474
7475 if (IsHIP) {
7476 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7477 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7478 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7479 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7480 Neg: options::OPT_fno_gpu_allow_device_init);
7481 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7482 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7483 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7484 Neg: options::OPT_fno_hip_kernel_arg_name);
7485 if (TC.getTriple().isSPIRV() &&
7486 TC.getTriple().getVendor() == llvm::Triple::VendorType::AMD)
7487 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fenable_spirv_size_optimization);
7488 }
7489
7490 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7491 CmdArgs.push_back(Elt: "-fgpu-rdc");
7492
7493 if (IsCuda || IsHIP) {
7494 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7495 Neg: options::OPT_fno_gpu_defer_diag);
7496 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7497 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7498 Default: false)) {
7499 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7500 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7501 }
7502 }
7503
7504 // Forward --no-offloadlib to -cc1.
7505 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7506 CmdArgs.push_back(Elt: "--no-offloadlib");
7507
7508 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7509 CmdArgs.push_back(
7510 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7511
7512 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7513 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7514 SA->getValue()));
7515 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7516 // Emit IBT endbr64 instructions by default
7517 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7518 // jump-table can generate indirect jumps, which are not permitted
7519 CmdArgs.push_back(Elt: "-fno-jump-tables");
7520 }
7521
7522 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7523 CmdArgs.push_back(
7524 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7525
7526 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7527
7528 // Forward -f options with positive and negative forms; we translate these by
7529 // hand. Do not propagate PGO options to the GPU-side compilations as the
7530 // profile info is for the host-side compilation only.
7531 if (!(IsCudaDevice || IsHIPDevice)) {
7532 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7533 auto *PGOArg = Args.getLastArg(
7534 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7535 Ids: options::OPT_fcs_profile_generate,
7536 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7537 Ids: options::OPT_fprofile_use_EQ);
7538 if (PGOArg)
7539 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7540 << "SampleUse with PGO options";
7541
7542 StringRef fname = A->getValue();
7543 if (!llvm::sys::fs::exists(Path: fname))
7544 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7545 else
7546 A->render(Args, Output&: CmdArgs);
7547 }
7548 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7549
7550 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7551 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7552 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7553 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7554 // off.
7555 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7556 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7557 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7558 }
7559 }
7560 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7561
7562 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7563 Neg: options::OPT_fno_assume_sane_operator_new);
7564
7565 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7566 CmdArgs.push_back(Elt: "-fapinotes");
7567 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7568 Neg: options::OPT_fno_apinotes_modules, Default: false))
7569 CmdArgs.push_back(Elt: "-fapinotes-modules");
7570 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7571
7572 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7573 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7574 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7575
7576 // -fblocks=0 is default.
7577 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7578 Default: TC.IsBlocksDefault()) ||
7579 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7580 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7581 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7582 CmdArgs.push_back(Elt: "-fblocks");
7583
7584 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7585 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7586 }
7587
7588 // -fencode-extended-block-signature=1 is default.
7589 if (TC.IsEncodeExtendedBlockSignatureDefault())
7590 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7591
7592 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7593 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7594 types::isCXX(Id: InputType))
7595 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7596
7597 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7598 /*Default=*/false))
7599 CmdArgs.push_back(Elt: "-fdefer-ts");
7600
7601 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7602 Ids: options::OPT_fno_double_square_bracket_attributes);
7603
7604 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7605 Neg: options::OPT_fno_access_control);
7606 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7607 Neg: options::OPT_fno_elide_constructors);
7608
7609 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7610
7611 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7612 (RTTIMode == ToolChain::RM_Disabled)))
7613 CmdArgs.push_back(Elt: "-fno-rtti");
7614
7615 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7616 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7617 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7618 CmdArgs.push_back(Elt: "-fshort-enums");
7619
7620 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7621
7622 // -fuse-cxa-atexit is default.
7623 if (!Args.hasFlag(
7624 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7625 Default: !RawTriple.isOSAIX() &&
7626 (!RawTriple.isOSWindows() ||
7627 RawTriple.isWindowsCygwinEnvironment()) &&
7628 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7629 RawTriple.hasEnvironment())) ||
7630 KernelOrKext)
7631 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7632
7633 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7634 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7635 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7636 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7637
7638 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7639 Neg: options::OPT_fno_use_line_directives);
7640
7641 // -fno-minimize-whitespace is default.
7642 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7643 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7644 types::ID InputType = Inputs[0].getType();
7645 if (!isDerivedFromC(Id: InputType))
7646 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7647 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7648 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7649 }
7650
7651 // -fno-keep-system-includes is default.
7652 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7653 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7654 types::ID InputType = Inputs[0].getType();
7655 if (!isDerivedFromC(Id: InputType))
7656 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7657 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7658 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7659 }
7660
7661 // -fms-extensions=0 is default.
7662 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7663 Default: IsWindowsMSVC || IsUEFI))
7664 CmdArgs.push_back(Elt: "-fms-extensions");
7665
7666 // -fms-compatibility=0 is default.
7667 bool IsMSVCCompat = Args.hasFlag(
7668 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7669 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7670 Neg: options::OPT_fno_ms_extensions, Default: true)));
7671 if (IsMSVCCompat) {
7672 CmdArgs.push_back(Elt: "-fms-compatibility");
7673 if (!types::isCXX(Id: Input.getType()) &&
7674 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7675 CmdArgs.push_back(Elt: "-fms-define-stdc");
7676 }
7677
7678 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7679 // clang and flang.
7680 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7681
7682 // -fms-anonymous-structs is disabled by default.
7683 // Determine whether to enable Microsoft named anonymous struct/union support.
7684 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7685 // where the feature can be:
7686 // - Explicitly enabled via -fms-anonymous-structs.
7687 // - Explicitly disabled via fno-ms-anonymous-structs
7688 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7689 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7690 //
7691 // When multiple relevent options are present, the last option on the command
7692 // line takes precedence. This allows users to selectively override implicit
7693 // enablement. Examples:
7694 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7695 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7696 auto MSAnonymousStructsOptionToUseOrNull =
7697 [](const ArgList &Args) -> const char * {
7698 const char *Option = nullptr;
7699 constexpr const char *Enable = "-fms-anonymous-structs";
7700 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7701
7702 // Iterate through all arguments in order to implement "last flag wins".
7703 for (const Arg *A : Args) {
7704 switch (A->getOption().getID()) {
7705 case options::OPT_fms_anonymous_structs:
7706 A->claim();
7707 Option = Enable;
7708 break;
7709 case options::OPT_fno_ms_anonymous_structs:
7710 A->claim();
7711 Option = Disable;
7712 break;
7713 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7714 // feature.
7715 case options::OPT_fms_extensions:
7716 case options::OPT_fms_compatibility:
7717 Option = Enable;
7718 break;
7719 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7720 // disables the feature.
7721 case options::OPT_fno_ms_extensions:
7722 case options::OPT_fno_ms_compatibility:
7723 Option = Disable;
7724 break;
7725 default:
7726 break;
7727 }
7728 }
7729 return Option;
7730 };
7731
7732 // Only pass a flag to CC1 if a relevant option was seen
7733 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7734 CmdArgs.push_back(Elt: MSAnonOpt);
7735
7736 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7737 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7738 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7739
7740 // Handle -fgcc-version, if present.
7741 VersionTuple GNUCVer;
7742 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7743 // Check that the version has 1 to 3 components and the minor and patch
7744 // versions fit in two decimal digits.
7745 StringRef Val = A->getValue();
7746 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7747 bool Invalid = GNUCVer.tryParse(string: Val);
7748 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7749 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7750 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7751 D.Diag(DiagID: diag::err_drv_invalid_value)
7752 << A->getAsString(Args) << A->getValue();
7753 }
7754 } else if (!IsMSVCCompat) {
7755 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7756 GNUCVer = VersionTuple(4, 2, 1);
7757 }
7758 if (!GNUCVer.empty()) {
7759 CmdArgs.push_back(
7760 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7761 }
7762
7763 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7764 if (!MSVT.empty())
7765 CmdArgs.push_back(
7766 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7767
7768 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7769 if (ImplyVCPPCVer) {
7770 StringRef LanguageStandard;
7771 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7772 Std = StdArg;
7773 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7774 .Case(S: "c11", Value: "-std=c11")
7775 .Case(S: "c17", Value: "-std=c17")
7776 // If you add cases below for spellings that are
7777 // not in LangStandards.def, update
7778 // TransferableCommand::tryParseStdArg() in
7779 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7780 // to match.
7781 // TODO: add c23 when MSVC supports it.
7782 .Case(S: "clatest", Value: "-std=c23")
7783 .Default(Value: "");
7784 if (LanguageStandard.empty())
7785 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7786 << StdArg->getAsString(Args);
7787 }
7788 CmdArgs.push_back(Elt: LanguageStandard.data());
7789 }
7790 if (ImplyVCPPCXXVer) {
7791 StringRef LanguageStandard;
7792 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7793 Std = StdArg;
7794 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7795 .Case(S: "c++14", Value: "-std=c++14")
7796 .Case(S: "c++17", Value: "-std=c++17")
7797 .Case(S: "c++20", Value: "-std=c++20")
7798 .Case(S: "c++23", Value: "-std=c++23")
7799 // If you add cases below for spellings that are
7800 // not in LangStandards.def, update
7801 // TransferableCommand::tryParseStdArg() in
7802 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7803 // to match.
7804 // TODO add c++26, c++29 when MSVC supports
7805 // it.
7806 .Case(S: "c++23preview", Value: "-std=c++23")
7807 .Case(S: "c++26preview", Value: "-std=c++26")
7808 .Case(S: "c++latest", Value: "-std=c++2d")
7809 .Default(Value: "");
7810 if (IsSYCL) {
7811 const LangStandard *LangStd =
7812 LangStandard::getLangStandardForName(Name: StdArg->getValue());
7813 if (LangStd) {
7814 // Use of /std: with 'C' is not supported for SYCL.
7815 if (LangStd->getLanguage() == Language::C)
7816 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7817 << StdArg->getAsString(Args) << "-fsycl";
7818 // SYCL requires C++17 or later.
7819 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7820 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17)
7821 << StdArg->getAsString(Args);
7822 }
7823 }
7824 if (LanguageStandard.empty())
7825 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7826 << StdArg->getAsString(Args);
7827 }
7828
7829 if (LanguageStandard.empty()) {
7830 if (IsSYCL)
7831 // For SYCL, C++17 is the default.
7832 LanguageStandard = "-std=c++17";
7833 else if (IsMSVC2015Compatible)
7834 LanguageStandard = "-std=c++14";
7835 else
7836 LanguageStandard = "-std=c++11";
7837 }
7838
7839 CmdArgs.push_back(Elt: LanguageStandard.data());
7840 }
7841
7842 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7843 Neg: options::OPT_fno_borland_extensions);
7844
7845 // -fno-declspec is default, except for PS4/PS5.
7846 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7847 Default: RawTriple.isPS()))
7848 CmdArgs.push_back(Elt: "-fdeclspec");
7849 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7850 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7851
7852 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7853 // than 19.
7854 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7855 Neg: options::OPT_fno_threadsafe_statics,
7856 Default: !types::isOpenCL(Id: InputType) &&
7857 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7858 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7859
7860 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7861 Default: true))
7862 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7863
7864 // Add -fno-assumptions, if it was specified.
7865 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7866 Default: true))
7867 CmdArgs.push_back(Elt: "-fno-assumptions");
7868
7869 // -fgnu-keywords default varies depending on language; only pass if
7870 // specified.
7871 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7872 Ids: options::OPT_fno_gnu_keywords);
7873
7874 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7875 Neg: options::OPT_fno_gnu89_inline);
7876
7877 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7878 Ids: options::OPT_finline_hint_functions,
7879 Ids: options::OPT_fno_inline_functions);
7880 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7881 if (A->getOption().matches(ID: options::OPT_fno_inline))
7882 A->render(Args, Output&: CmdArgs);
7883 } else if (InlineArg) {
7884 InlineArg->render(Args, Output&: CmdArgs);
7885 }
7886
7887 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7888
7889 // FIXME: Find a better way to determine whether we are in C++20.
7890 bool HaveCxx20 =
7891 Std &&
7892 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7893 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7894 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7895 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7896 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7897 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7898 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++26preview") ||
7899 Std->containsValue(Value: "c++2d") || Std->containsValue(Value: "gnu++2d") ||
7900 Std->containsValue(Value: "c++latest") || Std->containsValue(Value: "gnu++latest"));
7901 bool HaveModules =
7902 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7903
7904 // -fdelayed-template-parsing is default when targeting MSVC.
7905 // Many old Windows SDK versions require this to parse.
7906 //
7907 // According to
7908 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7909 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7910 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7911 // not enable -fdelayed-template-parsing by default after C++20.
7912 //
7913 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7914 // able to disable this by default at some point.
7915 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7916 Neg: options::OPT_fno_delayed_template_parsing,
7917 Default: IsWindowsMSVC && !HaveCxx20)) {
7918 if (HaveCxx20)
7919 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7920
7921 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7922 }
7923
7924 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7925 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7926 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7927 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7928 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7929 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7930 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7931 Default: false))
7932 CmdArgs.push_back(Elt: "-fmodules-codegen");
7933 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7934 Default: false))
7935 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7936
7937 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7938 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7939 Input, CmdArgs);
7940
7941 if (types::isObjC(Id: Input.getType()) &&
7942 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7943 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7944 Default: !Runtime.isNeXTFamily()))
7945 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7946
7947 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7948 Neg: options::OPT_fno_application_extension, Default: false))
7949 CmdArgs.push_back(Elt: "-fapplication-extension");
7950
7951 // Handle GCC-style exception args.
7952 bool EH = false;
7953 if (!C.getDriver().IsCLMode())
7954 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7955 IsDeviceOffloadAction, objcRuntime: Runtime, CmdArgs);
7956
7957 // Handle exception personalities
7958 Arg *A = Args.getLastArg(
7959 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7960 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions,
7961 Ids: options::OPT_femscripten_exceptions);
7962 if (A) {
7963 const Option &Opt = A->getOption();
7964 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7965 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7966 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7967 CmdArgs.push_back(Elt: "-exception-model=seh");
7968 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7969 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7970 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7971 CmdArgs.push_back(Elt: "-exception-model=wasm");
7972 if (Opt.matches(ID: options::OPT_femscripten_exceptions))
7973 CmdArgs.push_back(Elt: "-exception-model=emscripten");
7974 } else {
7975 switch (TC.GetExceptionModel(Args)) {
7976 default:
7977 break;
7978 case llvm::ExceptionHandling::DwarfCFI:
7979 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7980 break;
7981 case llvm::ExceptionHandling::SjLj:
7982 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7983 break;
7984 case llvm::ExceptionHandling::WinEH:
7985 CmdArgs.push_back(Elt: "-exception-model=seh");
7986 break;
7987 }
7988 }
7989
7990 // Unwind information version for x64 Windows.
7991 // Forward the new unified flag if present, otherwise translate legacy flags.
7992 if (const Arg *A = Args.getLastArg(Ids: options::OPT_winx64_eh_unwind_EQ)) {
7993 A->claim();
7994 CmdArgs.push_back(
7995 Elt: Args.MakeArgString(Str: Twine("-fwinx64-eh-unwind=") + A->getValue()));
7996 } else if (const Arg *A =
7997 Args.getLastArg(Ids: options::OPT_winx64_eh_unwindv2_EQ)) {
7998 A->claim();
7999 StringRef Val = A->getValue();
8000 if (Val == "best-effort")
8001 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
8002 else if (Val == "required")
8003 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
8004 // "disabled" maps to v1 default, nothing to forward.
8005 else if (Val != "disabled")
8006 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
8007 }
8008
8009 // Control Flow Guard mechanism for Windows.
8010 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_win_cfg_mechanism);
8011
8012 // C++ "sane" operator new.
8013 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
8014 Neg: options::OPT_fno_assume_sane_operator_new);
8015
8016 // -fassume-unique-vtables is on by default.
8017 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
8018 Neg: options::OPT_fno_assume_unique_vtables);
8019
8020 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
8021 // by default.
8022 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
8023 Ids: options::OPT_fno_sized_deallocation);
8024
8025 // -faligned-allocation is on by default in C++17 onwards and otherwise off
8026 // by default.
8027 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
8028 Ids: options::OPT_fno_aligned_allocation,
8029 Ids: options::OPT_faligned_new_EQ)) {
8030 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
8031 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
8032 else
8033 CmdArgs.push_back(Elt: "-faligned-allocation");
8034 }
8035
8036 // The default new alignment can be specified using a dedicated option or via
8037 // a GCC-compatible option that also turns on aligned allocation.
8038 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
8039 Ids: options::OPT_faligned_new_EQ))
8040 CmdArgs.push_back(
8041 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
8042
8043 // -fconstant-cfstrings is default, and may be subject to argument translation
8044 // on Darwin.
8045 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
8046 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
8047 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
8048 Neg: options::OPT_mno_constant_cfstrings, Default: true))
8049 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
8050
8051 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
8052 Neg: options::OPT_fno_pascal_strings);
8053
8054 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8055 // -fno-pack-struct doesn't apply to -fpack-struct=.
8056 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
8057 CmdArgs.push_back(
8058 Elt: Args.MakeArgString(Str: "-fpack-struct=" + Twine(A->getValue())));
8059 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
8060 Neg: options::OPT_fno_pack_struct, Default: false)) {
8061 CmdArgs.push_back(Elt: "-fpack-struct=1");
8062 }
8063
8064 // Handle -fmax-type-align=N and -fno-type-align
8065 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
8066 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
8067 if (!SkipMaxTypeAlign) {
8068 std::string MaxTypeAlignStr = "-fmax-type-align=";
8069 MaxTypeAlignStr += A->getValue();
8070 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8071 }
8072 } else if (RawTriple.isOSDarwin()) {
8073 if (!SkipMaxTypeAlign) {
8074 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8075 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
8076 }
8077 }
8078
8079 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
8080 CmdArgs.push_back(Elt: "-Qn");
8081
8082 // -fno-common is the default, set -fcommon only when that flag is set.
8083 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
8084
8085 // -fsigned-bitfields is default, and clang doesn't yet support
8086 // -funsigned-bitfields.
8087 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
8088 Neg: options::OPT_funsigned_bitfields, Default: true))
8089 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
8090 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
8091
8092 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8093 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
8094 D.Diag(DiagID: diag::err_drv_clang_unsupported)
8095 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
8096
8097 // -finput_charset=UTF-8 is default. Reject others
8098 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
8099 StringRef value = inputCharset->getValue();
8100 if (!value.equals_insensitive(RHS: "utf-8"))
8101 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8102 << value;
8103 }
8104
8105 // -fexec_charset=UTF-8 is default. Reject others
8106 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
8107 StringRef value = execCharset->getValue();
8108 if (!value.equals_insensitive(RHS: "utf-8"))
8109 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8110 << value;
8111 }
8112
8113 RenderDiagnosticsOptions(D, Args, CmdArgs);
8114
8115 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
8116 Neg: options::OPT_fno_asm_blocks);
8117
8118 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
8119 Neg: options::OPT_fno_gnu_inline_asm);
8120
8121 handleVectorizeLoopsArgs(Args, CmdArgs);
8122 handleVectorizeSLPArgs(Args, CmdArgs);
8123
8124 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
8125 if (!VecWidth.empty())
8126 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
8127
8128 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
8129 Args.AddLastArg(Output&: CmdArgs,
8130 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
8131
8132 // -fdollars-in-identifiers default varies depending on platform and
8133 // language; only pass if specified.
8134 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
8135 Ids: options::OPT_fno_dollars_in_identifiers)) {
8136 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
8137 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
8138 else
8139 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
8140 }
8141
8142 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
8143 Neg: options::OPT_fno_apple_pragma_pack);
8144
8145 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8146 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8147 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8148
8149 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
8150 Neg: options::OPT_fno_rewrite_imports, Default: false);
8151 if (RewriteImports)
8152 CmdArgs.push_back(Elt: "-frewrite-imports");
8153
8154 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
8155 Neg: options::OPT_fno_directives_only);
8156
8157 // Enable rewrite includes if the user's asked for it or if we're generating
8158 // diagnostics.
8159 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8160 // nice to enable this when doing a crashdump for modules as well.
8161 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
8162 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
8163 (C.isForDiagnostics() && !HaveModules))
8164 CmdArgs.push_back(Elt: "-frewrite-includes");
8165
8166 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
8167 Neg: options::OPT_fno_zos_extensions, Default: false))
8168 CmdArgs.push_back(Elt: "-fzos-extensions");
8169 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
8170 CmdArgs.push_back(Elt: "-fno-zos-extensions");
8171
8172 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8173 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
8174 Ids: options::OPT_traditional_cpp)) {
8175 if (isa<PreprocessJobAction>(Val: JA))
8176 CmdArgs.push_back(Elt: "-traditional-cpp");
8177 else
8178 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
8179 }
8180
8181 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
8182 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
8183 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
8184
8185 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
8186
8187 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
8188 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
8189 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_compilation_unit_id);
8190 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_include_local_entities);
8191 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_no_extract_from_system_headers);
8192 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_source_transformation);
8193 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_global_scope_analysis_result);
8194 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_link_unit_id);
8195 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_src_edit_file);
8196 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_transformation_report_file);
8197
8198 // Handle serialized diagnostics.
8199 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
8200 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
8201 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
8202 }
8203
8204 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
8205 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
8206
8207 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
8208 A->render(Args, Output&: CmdArgs);
8209 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
8210 A && A->containsValue(Value: "g")) {
8211 // Set -fextend-variable-liveness=all by default at -Og.
8212 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
8213 }
8214
8215 // Forward -fcomment-block-commands to -cc1.
8216 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
8217 // Forward -fparse-all-comments to -cc1.
8218 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
8219 // Forward -fretain-comments to -cc1.
8220 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fretain_comments);
8221
8222 // Turn -fplugin=name.so into -load name.so
8223 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
8224 CmdArgs.push_back(Elt: "-load");
8225 CmdArgs.push_back(Elt: A->getValue());
8226 A->claim();
8227 }
8228
8229 // Turn -fplugin-arg-pluginname-key=value into
8230 // -plugin-arg-pluginname key=value
8231 // GCC has an actual plugin_argument struct with key/value pairs that it
8232 // passes to its plugins, but we don't, so just pass it on as-is.
8233 //
8234 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8235 // argument key are allowed to contain dashes. GCC therefore only
8236 // allows dashes in the key. We do the same.
8237 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
8238 auto ArgValue = StringRef(A->getValue());
8239 auto FirstDashIndex = ArgValue.find(C: '-');
8240 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
8241 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
8242
8243 A->claim();
8244 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8245 if (PluginName.empty()) {
8246 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8247 } else {
8248 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
8249 << PluginName << A->getAsString(Args);
8250 }
8251 continue;
8252 }
8253
8254 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
8255 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
8256 }
8257
8258 // Forward -fpass-plugin=name.so to -cc1.
8259 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
8260 CmdArgs.push_back(
8261 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
8262 A->claim();
8263 }
8264
8265 // Forward --vfsoverlay to -cc1.
8266 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
8267 CmdArgs.push_back(Elt: "--vfsoverlay");
8268 CmdArgs.push_back(Elt: A->getValue());
8269 A->claim();
8270 }
8271
8272 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
8273 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
8274
8275 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
8276 Neg: options::OPT_fno_experimental_late_parse_attributes);
8277
8278 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
8279 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
8280 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
8281 A->render(Args, Output&: CmdArgs);
8282 else
8283 CmdArgs.push_back(Elt: Args.MakeArgString(
8284 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8285 }
8286
8287 if (Args.hasFlag(
8288 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
8289 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8290 Default: false) ||
8291 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8292 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
8293 Default: false))
8294 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
8295
8296 if (!IsCudaDevice) {
8297 Args.addOptInFlag(
8298 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8299 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
8300 Args.addOptInFlag(
8301 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
8302 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
8303 }
8304
8305 // Setup statistics file output.
8306 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8307 if (!StatsFile.empty()) {
8308 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
8309 if (D.CCPrintInternalStats)
8310 CmdArgs.push_back(Elt: "-stats-file-append");
8311 }
8312
8313 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8314 // parser.
8315 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
8316 Arg->claim();
8317 // -finclude-default-header flag is for preprocessor,
8318 // do not pass it to other cc1 commands when save-temps is enabled
8319 if (C.getDriver().isSaveTempsEnabled() &&
8320 !isa<PreprocessJobAction>(Val: JA)) {
8321 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8322 continue;
8323 }
8324 CmdArgs.push_back(Elt: Arg->getValue());
8325 }
8326 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
8327 A->claim();
8328
8329 // We translate this by hand to the -cc1 argument, since nightly test uses
8330 // it and developers have been trained to spell it with -mllvm. Both
8331 // spellings are now deprecated and should be removed.
8332 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
8333 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
8334 } else {
8335 A->render(Args, Output&: CmdArgs);
8336 }
8337 }
8338
8339 // This needs to run after -Xclang argument forwarding to pick up the target
8340 // features enabled through -Xclang -target-feature flags.
8341 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8342
8343 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
8344
8345#if CLANG_ENABLE_CIR
8346 // Forward -mmlir arguments to to the MLIR option parser.
8347 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8348 A->claim();
8349 A->render(Args, CmdArgs);
8350 }
8351#endif // CLANG_ENABLE_CIR
8352
8353 // With -save-temps, we want to save the unoptimized bitcode output from the
8354 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8355 // by the frontend.
8356 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8357 // has slightly different breakdown between stages.
8358 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8359 // pristine IR generated by the frontend. Ideally, a new compile action should
8360 // be added so both IR can be captured.
8361 if ((C.getDriver().isSaveTempsEnabled() ||
8362 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
8363 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8364 isa<CompileJobAction>(Val: JA))
8365 CmdArgs.push_back(Elt: "-disable-llvm-passes");
8366
8367 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
8368
8369 const char *Exec = D.getDriverProgramPath();
8370
8371 // Optionally embed the -cc1 level arguments into the debug info or a
8372 // section, for build analysis.
8373 // Also record command line arguments into the debug info if
8374 // -grecord-gcc-switches options is set on.
8375 // By default, -gno-record-gcc-switches is set on and no recording.
8376 auto GRecordSwitches = false;
8377 auto FRecordSwitches = false;
8378 bool DXRecordSwitches = false;
8379 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches,
8380 DXRecordCommandLine&: DXRecordSwitches)) {
8381 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8382 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8383 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8384 CmdArgs.push_back(Elt: FlagsArgString);
8385 }
8386 if (FRecordSwitches) {
8387 CmdArgs.push_back(Elt: "-record-command-line");
8388 CmdArgs.push_back(Elt: FlagsArgString);
8389 }
8390 if (DXRecordSwitches) {
8391 CmdArgs.push_back(Elt: "-fdx-record-command-line");
8392 CmdArgs.push_back(Elt: FlagsArgString);
8393 }
8394 }
8395
8396 // Host-side offloading compilation receives all device-side outputs. Include
8397 // them in the host compilation depending on the target.
8398 if (!HostOffloadingInputs.empty()) {
8399 bool UseOffloadIncludeBinary =
8400 (IsCuda || IsHIP) &&
8401 (!IsRDCMode || Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi)) &&
8402 !UsesLLVMOffloading;
8403 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8404 if (UseOffloadIncludeBinary) {
8405 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8406 CmdArgs.push_back(Elt: "-foffload-include-binary");
8407 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
8408 } else {
8409 for (const InputInfo Input : HostOffloadingInputs)
8410 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
8411 TC.getInputFilename(Input)));
8412 }
8413 }
8414
8415 if (IsCuda) {
8416 if (Args.hasArg(Ids: options::OPT_cuda_emit_nvcc_abi))
8417 CmdArgs.push_back(Elt: "--cuda-emit-nvcc-abi");
8418 }
8419
8420 if (IsCuda || IsHIP) {
8421 // Determine the original source input.
8422 const Action *SourceAction = &JA;
8423 while (SourceAction->getKind() != Action::InputClass) {
8424 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8425 SourceAction = SourceAction->getInputs()[0];
8426 }
8427 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
8428 if (!CUID.empty())
8429 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
8430
8431 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8432 // be overriden by -fno-gpu-approx-transcendentals.
8433 bool UseApproxTranscendentals = Args.hasFlag(
8434 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
8435 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
8436 Neg: options::OPT_fno_gpu_approx_transcendentals,
8437 Default: UseApproxTranscendentals))
8438 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
8439 } else {
8440 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
8441 Ids: options::OPT_fno_gpu_approx_transcendentals);
8442 }
8443
8444 if (IsHIP) {
8445 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
8446 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
8447 }
8448
8449 Args.AddAllArgs(Output&: CmdArgs,
8450 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8451
8452 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
8453 Ids: options::OPT_fno_offload_uniform_block);
8454
8455 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
8456 Ids: options::OPT_fno_offload_implicit_host_device_templates);
8457
8458 if (IsCudaDevice || IsHIPDevice) {
8459 StringRef InlineThresh =
8460 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
8461 if (!InlineThresh.empty()) {
8462 std::string ArgStr =
8463 std::string("-inline-threshold=") + InlineThresh.str();
8464 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
8465 }
8466 }
8467
8468 if (IsHIPDevice)
8469 Args.addOptOutFlag(Output&: CmdArgs,
8470 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8471 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8472
8473 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8474 // to specify the result of the compile phase on the host, so the meaningful
8475 // device declarations can be identified. Also, -fopenmp-is-target-device is
8476 // passed along to tell the frontend that it is generating code for a device,
8477 // so that only the relevant declarations are emitted.
8478 if (IsOpenMPDevice) {
8479 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
8480 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8481 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
8482 CmdArgs.push_back(Elt: "-fcuda-is-device");
8483
8484 if (OpenMPDeviceInput) {
8485 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
8486 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
8487 }
8488 }
8489
8490 if (Triple.isAMDGPU() ||
8491 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8492 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8493
8494 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8495 Neg: options::OPT_mno_unsafe_fp_atomics);
8496 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8497 Neg: options::OPT_mno_amdgpu_ieee);
8498 }
8499
8500 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8501
8502 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8503 Neg: options::OPT_fno_devirtualize_speculatively,
8504 /*Default value*/ Default: false))
8505 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8506
8507 bool VirtualFunctionElimination =
8508 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8509 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8510 if (VirtualFunctionElimination) {
8511 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8512 // in the future).
8513 if (LTOMode != LTOK_Full)
8514 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8515 << "-fvirtual-function-elimination"
8516 << "-flto=full";
8517
8518 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8519 }
8520
8521 // VFE requires whole-program-vtables, and enables it by default.
8522 bool WholeProgramVTables = Args.hasFlag(
8523 Pos: options::OPT_fwhole_program_vtables,
8524 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8525 if (VirtualFunctionElimination && !WholeProgramVTables) {
8526 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8527 << "-fno-whole-program-vtables"
8528 << "-fvirtual-function-elimination";
8529 }
8530
8531 if (WholeProgramVTables) {
8532 // PS4 uses the legacy LTO API, which does not support this feature in
8533 // ThinLTO mode.
8534 bool IsPS4 = getToolChain().getTriple().isPS4();
8535
8536 // Check if we passed LTO options but they were suppressed because this is a
8537 // device offloading action, or we passed device offload LTO options which
8538 // were suppressed because this is not the device offload action.
8539 // Check if we are using PS4 in regular LTO mode.
8540 // Otherwise, issue an error.
8541
8542 auto OtherLTOMode = TC.getLTOMode(
8543 Args, Kind: IsDeviceOffloadAction ? Action::OFK_None
8544 : static_cast<Action::OffloadKind>(
8545 C.getActiveOffloadKinds()));
8546 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8547
8548 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8549 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8550 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8551 << "-fwhole-program-vtables"
8552 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8553
8554 // Propagate -fwhole-program-vtables if this is an LTO compile.
8555 if (IsUsingLTO)
8556 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8557 }
8558
8559 bool DefaultsSplitLTOUnit =
8560 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8561 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8562 (!Triple.isPS4() && UnifiedLTO);
8563 bool SplitLTOUnit =
8564 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8565 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8566 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8567 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8568 << "-fsanitize=cfi";
8569 if (SplitLTOUnit)
8570 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8571
8572 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8573 Ids: options::OPT_fno_fat_lto_objects)) {
8574 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8575 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8576 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8577 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8578 << A->getAsString(Args) << TC.getTripleString();
8579 }
8580 CmdArgs.push_back(Elt: Args.MakeArgString(
8581 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8582 CmdArgs.push_back(Elt: "-flto-unit");
8583 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8584 A->render(Args, Output&: CmdArgs);
8585 }
8586 }
8587
8588 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8589
8590 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8591 Ids: options::OPT_fno_force_enable_int128)) {
8592 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8593 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8594 }
8595
8596 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8597 Neg: options::OPT_fno_keep_static_consts);
8598 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8599 Neg: options::OPT_fno_keep_persistent_storage_variables);
8600 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_inline_functions,
8601 Neg: options::OPT_fno_keep_inline_functions);
8602 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8603 Neg: options::OPT_fno_complete_member_pointers);
8604 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8605 A->render(Args, Output&: CmdArgs);
8606
8607 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8608
8609 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8610
8611 if (Triple.isAArch64() &&
8612 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8613 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8614 // Disable Function Multiversioning on AArch64 target.
8615 CmdArgs.push_back(Elt: "-target-feature");
8616 CmdArgs.push_back(Elt: "-fmv");
8617 }
8618
8619 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8620 Default: (TC.getTriple().isOSBinFormatELF() ||
8621 TC.getTriple().isOSBinFormatCOFF()) &&
8622 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8623 !TC.getTriple().isOSNetBSD() &&
8624 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8625 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8626 CmdArgs.push_back(Elt: "-faddrsig");
8627
8628 const bool HasDefaultDwarf2CFIASM =
8629 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8630 (EH || UnwindTables || AsyncUnwindTables ||
8631 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8632 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8633 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8634 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8635
8636 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8637 std::string Str = A->getAsString(Args);
8638 if (!TC.getTriple().isOSBinFormatELF())
8639 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8640 << Str << TC.getTripleString();
8641 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8642 }
8643
8644 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8645 // the -cc1 command easier to edit when reproducing compiler crashes.
8646 if (Output.getType() == types::TY_Dependencies) {
8647 // Handled with other dependency code.
8648 } else if (Output.isFilename()) {
8649 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8650 Output.getType() == clang::driver::types::TY_IFS) {
8651 SmallString<128> OutputFilename(Output.getFilename());
8652 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8653 CmdArgs.push_back(Elt: "-o");
8654 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8655 } else {
8656 CmdArgs.push_back(Elt: "-o");
8657 CmdArgs.push_back(Elt: Output.getFilename());
8658 }
8659 } else {
8660 assert(Output.isNothing() && "Invalid output.");
8661 }
8662
8663 addDashXForInput(Args, Input, CmdArgs);
8664
8665 ArrayRef<InputInfo> FrontendInputs = Input;
8666 if (IsExtractAPI)
8667 FrontendInputs = ExtractAPIInputs;
8668 else if (Input.isNothing())
8669 FrontendInputs = {};
8670
8671 for (const InputInfo &Input : FrontendInputs) {
8672 if (Input.isFilename())
8673 CmdArgs.push_back(Elt: Input.getFilename());
8674 else
8675 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8676 }
8677
8678 if (D.CC1Main && !D.CCGenDiagnostics) {
8679 // Invoke the CC1 directly in this process
8680 C.addCommand(Cmd: std::make_unique<CC1Command>(
8681 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8682 args: Output, args: D.getPrependArg()));
8683 } else {
8684 C.addCommand(Cmd: std::make_unique<Command>(
8685 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8686 args: Output, args: D.getPrependArg()));
8687 }
8688
8689 // Make the compile command echo its inputs for /showFilenames.
8690 if (Output.getType() == types::TY_Object &&
8691 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8692 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8693 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8694 }
8695
8696 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8697 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8698 !Args.hasArg(Ids: options::OPT_mfentry))
8699 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8700 << A->getAsString(Args);
8701
8702 // Claim some arguments which clang supports automatically.
8703
8704 // -fpch-preprocess is used with gcc to add a special marker in the output to
8705 // include the PCH file.
8706 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8707
8708 // Claim some arguments which clang doesn't support, but we don't
8709 // care to warn the user about.
8710 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8711 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8712
8713 // Disable warnings for clang -E -emit-llvm foo.c
8714 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8715}
8716
8717Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8718 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8719 // as it is for other tools. Some operations on a Tool actually test
8720 // whether that tool is Clang based on the Tool's Name as a string.
8721 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8722
8723Clang::~Clang() {}
8724
8725/// Add options related to the Objective-C runtime/ABI.
8726///
8727/// Returns true if the runtime is non-fragile.
8728ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8729 const InputInfoList &inputs,
8730 ArgStringList &cmdArgs,
8731 RewriteKind rewriteKind) const {
8732 // Look for the controlling runtime option.
8733 Arg *runtimeArg =
8734 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8735 Ids: options::OPT_fobjc_runtime_EQ);
8736
8737 // Just forward -fobjc-runtime= to the frontend. This supercedes
8738 // options about fragility.
8739 if (runtimeArg &&
8740 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8741 ObjCRuntime runtime;
8742 StringRef value = runtimeArg->getValue();
8743 if (runtime.tryParse(input: value)) {
8744 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8745 << value;
8746 }
8747 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8748 (runtime.getVersion() >= VersionTuple(2, 0)))
8749 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8750 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8751 !getToolChain().getTriple().isOSBinFormatWasm()) {
8752 getToolChain().getDriver().Diag(
8753 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8754 << runtime.getVersion().getMajor();
8755 }
8756
8757 runtimeArg->render(Args: args, Output&: cmdArgs);
8758 return runtime;
8759 }
8760
8761 // Otherwise, we'll need the ABI "version". Version numbers are
8762 // slightly confusing for historical reasons:
8763 // 1 - Traditional "fragile" ABI
8764 // 2 - Non-fragile ABI, version 1
8765 // 3 - Non-fragile ABI, version 2
8766 unsigned objcABIVersion = 1;
8767 // If -fobjc-abi-version= is present, use that to set the version.
8768 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8769 StringRef value = abiArg->getValue();
8770 if (value == "1")
8771 objcABIVersion = 1;
8772 else if (value == "2")
8773 objcABIVersion = 2;
8774 else if (value == "3")
8775 objcABIVersion = 3;
8776 else
8777 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8778 } else {
8779 // Otherwise, determine if we are using the non-fragile ABI.
8780 bool nonFragileABIIsDefault =
8781 (rewriteKind == RK_NonFragile ||
8782 (rewriteKind == RK_None &&
8783 getToolChain().IsObjCNonFragileABIDefault()));
8784 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8785 Neg: options::OPT_fno_objc_nonfragile_abi,
8786 Default: nonFragileABIIsDefault)) {
8787// Determine the non-fragile ABI version to use.
8788#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8789 unsigned nonFragileABIVersion = 1;
8790#else
8791 unsigned nonFragileABIVersion = 2;
8792#endif
8793
8794 if (Arg *abiArg =
8795 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8796 StringRef value = abiArg->getValue();
8797 if (value == "1")
8798 nonFragileABIVersion = 1;
8799 else if (value == "2")
8800 nonFragileABIVersion = 2;
8801 else
8802 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8803 << value;
8804 }
8805
8806 objcABIVersion = 1 + nonFragileABIVersion;
8807 } else {
8808 objcABIVersion = 1;
8809 }
8810 }
8811
8812 // We don't actually care about the ABI version other than whether
8813 // it's non-fragile.
8814 bool isNonFragile = objcABIVersion != 1;
8815
8816 // If we have no runtime argument, ask the toolchain for its default runtime.
8817 // However, the rewriter only really supports the Mac runtime, so assume that.
8818 ObjCRuntime runtime;
8819 if (!runtimeArg) {
8820 switch (rewriteKind) {
8821 case RK_None:
8822 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8823 break;
8824 case RK_Fragile:
8825 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8826 break;
8827 case RK_NonFragile:
8828 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8829 break;
8830 }
8831
8832 // -fnext-runtime
8833 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8834 // On Darwin, make this use the default behavior for the toolchain.
8835 if (getToolChain().getTriple().isOSDarwin()) {
8836 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8837
8838 // Otherwise, build for a generic macosx port.
8839 } else {
8840 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8841 }
8842
8843 // -fgnu-runtime
8844 } else {
8845 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8846 // Legacy behaviour is to target the gnustep runtime if we are in
8847 // non-fragile mode or the GCC runtime in fragile mode.
8848 if (isNonFragile)
8849 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8850 else
8851 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8852 }
8853
8854 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8855 return types::isObjC(Id: input.getType());
8856 }))
8857 cmdArgs.push_back(
8858 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8859 return runtime;
8860}
8861
8862static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8863 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8864 I += HaveDash;
8865 return !HaveDash;
8866}
8867
8868namespace {
8869struct EHFlags {
8870 bool Synch = false;
8871 bool Asynch = false;
8872 bool NoUnwindC = false;
8873};
8874} // end anonymous namespace
8875
8876/// /EH controls whether to run destructor cleanups when exceptions are
8877/// thrown. There are three modifiers:
8878/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8879/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8880/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8881/// - c: Assume that extern "C" functions are implicitly nounwind.
8882/// The default is /EHs-c-, meaning cleanups are disabled.
8883static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8884 bool isWindowsMSVC) {
8885 EHFlags EH;
8886
8887 std::vector<std::string> EHArgs =
8888 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8889 for (const auto &EHVal : EHArgs) {
8890 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8891 switch (EHVal[I]) {
8892 case 'a':
8893 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8894 if (EH.Asynch) {
8895 // Async exceptions are Windows MSVC only.
8896 if (!isWindowsMSVC) {
8897 EH.Asynch = false;
8898 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8899 continue;
8900 }
8901 EH.Synch = false;
8902 }
8903 continue;
8904 case 'c':
8905 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8906 continue;
8907 case 's':
8908 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8909 if (EH.Synch)
8910 EH.Asynch = false;
8911 continue;
8912 default:
8913 break;
8914 }
8915 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8916 break;
8917 }
8918 }
8919 // The /GX, /GX- flags are only processed if there are not /EH flags.
8920 // The default is that /GX is not specified.
8921 if (EHArgs.empty() &&
8922 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8923 /*Default=*/false)) {
8924 EH.Synch = true;
8925 EH.NoUnwindC = true;
8926 }
8927
8928 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8929 EH.Synch = false;
8930 EH.NoUnwindC = false;
8931 EH.Asynch = false;
8932 }
8933
8934 return EH;
8935}
8936
8937void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8938 ArgStringList &CmdArgs) const {
8939 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8940
8941 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8942
8943 if (Arg *ShowIncludes =
8944 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8945 Ids: options::OPT__SLASH_showIncludes_user)) {
8946 CmdArgs.push_back(Elt: "--show-includes");
8947 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8948 CmdArgs.push_back(Elt: "-sys-header-deps");
8949 }
8950
8951 // This controls whether or not we emit RTTI data for polymorphic types.
8952 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8953 /*Default=*/false))
8954 CmdArgs.push_back(Elt: "-fno-rtti-data");
8955
8956 // This controls whether or not we emit stack-protector instrumentation.
8957 // In MSVC, Buffer Security Check (/GS) is on by default.
8958 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8959 /*Default=*/true)) {
8960 CmdArgs.push_back(Elt: "-stack-protector");
8961 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8962 }
8963
8964 const Driver &D = getToolChain().getDriver();
8965
8966 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8967 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8968 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8969 if (types::isCXX(Id: InputType))
8970 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8971 CmdArgs.push_back(Elt: "-fexceptions");
8972 if (EH.Asynch)
8973 CmdArgs.push_back(Elt: "-fasync-exceptions");
8974 }
8975 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8976 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8977
8978 // /EP should expand to -E -P.
8979 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8980 CmdArgs.push_back(Elt: "-E");
8981 CmdArgs.push_back(Elt: "-P");
8982 }
8983
8984 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8985 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8986 Default: false)) {
8987 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8988 }
8989
8990 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8991 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8992 CmdArgs.push_back(Elt: "-fno-wchar");
8993 }
8994
8995 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8996 llvm::Triple::ArchType Arch = getToolChain().getArch();
8997 std::vector<std::string> Values =
8998 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8999 if (!Values.empty()) {
9000 llvm::SmallSet<std::string, 4> SupportedArches;
9001 if (Arch == llvm::Triple::x86)
9002 SupportedArches.insert(V: "IA32");
9003
9004 for (auto &V : Values)
9005 if (!SupportedArches.contains(V))
9006 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9007 << std::string("/arch:").append(str: V) << "/kernel";
9008 }
9009
9010 CmdArgs.push_back(Elt: "-fno-rtti");
9011 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
9012 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
9013 << "/kernel";
9014 }
9015
9016 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
9017 Ids: options::OPT__SLASH_vlen_EQ_256,
9018 Ids: options::OPT__SLASH_vlen_EQ_512)) {
9019 llvm::Triple::ArchType AT = getToolChain().getArch();
9020 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
9021 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
9022 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
9023 "AVX10.2"};
9024
9025 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
9026 if (Arch512.contains(V: Arch))
9027 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
9028 else
9029 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
9030 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
9031 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
9032 if (Arch512.contains(V: Arch))
9033 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9034 else if (Arch != "AVX" && Arch != "AVX2")
9035 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
9036 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
9037 } else {
9038 if (Arch == "AVX10.1" || Arch == "AVX10.2")
9039 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9040 }
9041 } else {
9042 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
9043 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
9044 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
9045 CmdArgs.push_back(Elt: "-target-feature");
9046 CmdArgs.push_back(Elt: "-amx-tile");
9047 }
9048 if (Arch == "AVX10.2") {
9049 CmdArgs.push_back(Elt: "-target-feature");
9050 CmdArgs.push_back(Elt: "+avx10.2");
9051 }
9052 }
9053
9054 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
9055 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
9056 if (MostGeneralArg && BestCaseArg)
9057 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
9058 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9059
9060 if (MostGeneralArg) {
9061 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
9062 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
9063 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
9064
9065 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9066 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9067 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9068 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
9069 << FirstConflict->getAsString(Args)
9070 << SecondConflict->getAsString(Args);
9071
9072 if (SingleArg)
9073 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
9074 else if (MultipleArg)
9075 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
9076 else
9077 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
9078 }
9079
9080 if (Args.hasArg(Ids: options::OPT_regcall4))
9081 CmdArgs.push_back(Elt: "-regcall4");
9082
9083 // Parse the default calling convention options.
9084 if (Arg *CCArg =
9085 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
9086 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
9087 Ids: options::OPT__SLASH_Gregcall)) {
9088 unsigned DCCOptId = CCArg->getOption().getID();
9089 const char *DCCFlag = nullptr;
9090 bool ArchSupported = !isNVPTX;
9091 llvm::Triple::ArchType Arch = getToolChain().getArch();
9092 switch (DCCOptId) {
9093 case options::OPT__SLASH_Gd:
9094 DCCFlag = "-fdefault-calling-conv=cdecl";
9095 break;
9096 case options::OPT__SLASH_Gr:
9097 ArchSupported = Arch == llvm::Triple::x86;
9098 DCCFlag = "-fdefault-calling-conv=fastcall";
9099 break;
9100 case options::OPT__SLASH_Gz:
9101 ArchSupported = Arch == llvm::Triple::x86;
9102 DCCFlag = "-fdefault-calling-conv=stdcall";
9103 break;
9104 case options::OPT__SLASH_Gv:
9105 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9106 DCCFlag = "-fdefault-calling-conv=vectorcall";
9107 break;
9108 case options::OPT__SLASH_Gregcall:
9109 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9110 DCCFlag = "-fdefault-calling-conv=regcall";
9111 break;
9112 }
9113
9114 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9115 if (ArchSupported && DCCFlag)
9116 CmdArgs.push_back(Elt: DCCFlag);
9117 }
9118
9119 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
9120 CmdArgs.push_back(Elt: "-regcall4");
9121
9122 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
9123
9124 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
9125 CmdArgs.push_back(Elt: "-fdiagnostics-format");
9126 CmdArgs.push_back(Elt: "msvc");
9127 }
9128
9129 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
9130 CmdArgs.push_back(Elt: "-fms-kernel");
9131
9132 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9133 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9134 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
9135 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
9136 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
9137 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
9138
9139 // Handle the various /guard options. We don't immediately push back clang
9140 // args since there are /d2 args that can modify the behavior of /guard:cf.
9141 bool HasCFGuard = false;
9142 bool HasCFGuardNoChecks = false;
9143 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
9144 StringRef GuardArgs = A->getValue();
9145 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9146 // "ehcont-".
9147 if (GuardArgs.equals_insensitive(RHS: "cf")) {
9148 // Emit CFG instrumentation and the table of address-taken functions.
9149 HasCFGuard = true;
9150 HasCFGuardNoChecks = false;
9151 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
9152 // Emit only the table of address-taken functions.
9153 HasCFGuard = false;
9154 HasCFGuardNoChecks = true;
9155 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
9156 // Emit EH continuation table.
9157 CmdArgs.push_back(Elt: "-ehcontguard");
9158 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
9159 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
9160 // Do nothing, but we might want to emit a security warning in future.
9161 } else {
9162 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9163 }
9164 A->claim();
9165 }
9166
9167 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9168 // If CFG is not enabled, it is a no-op.
9169 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
9170 if (HasCFGuard) {
9171 HasCFGuard = false;
9172 HasCFGuardNoChecks = true;
9173 }
9174 }
9175
9176 if (HasCFGuard)
9177 CmdArgs.push_back(Elt: "-cfguard");
9178 else if (HasCFGuardNoChecks)
9179 CmdArgs.push_back(Elt: "-cfguard-no-checks");
9180
9181 // Control Flow Guard mechanism for Windows.
9182 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch_))
9183 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=check");
9184 else if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch))
9185 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=dispatch");
9186
9187 for (const auto &FuncOverride :
9188 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
9189 CmdArgs.push_back(Elt: Args.MakeArgString(
9190 Str: Twine("-loader-replaceable-function=") + FuncOverride));
9191 }
9192
9193 if (Args.hasArg(Ids: options::OPT__SLASH_experimental_deterministic)) {
9194 CmdArgs.push_back(Elt: "-Wdate-time");
9195
9196 if (Args.hasArg(Ids: options::OPT_mincremental_linker_compatible)) {
9197 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9198 << "/experimental:deterministic"
9199 << "/Brepro-";
9200 }
9201 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9202 // deterministic result, but we force this timestamp to 0, which also
9203 // produces deterministic result.
9204 CmdArgs.push_back(Elt: "-mno-incremental-linker-compatible");
9205 }
9206
9207 bool HasNoDateTime = Args.hasFlag(Pos: options::OPT__SLASH_d1nodatetime,
9208 Neg: options::OPT__SLASH_d1nodatetime_, Default: false);
9209
9210 if (HasNoDateTime)
9211 CmdArgs.push_back(Elt: "-init-datetime-macros=undefined");
9212
9213 // /Brepro is an alias for -mincremental-linker-compatible option.
9214 if (!Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
9215 Neg: options::OPT_mno_incremental_linker_compatible,
9216 Default: getToolChain()
9217 .getTriple()
9218 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9219 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9220 // This option does not allow the user redefinitions for these macros.
9221 if (!HasNoDateTime)
9222 CmdArgs.push_back(Elt: "-init-datetime-macros=literalone");
9223 }
9224}
9225
9226const char *Clang::getBaseInputName(const ArgList &Args,
9227 const InputInfo &Input) {
9228 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
9229}
9230
9231const char *Clang::getBaseInputStem(const ArgList &Args,
9232 const InputInfoList &Inputs) {
9233 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
9234
9235 if (const char *End = strrchr(s: Str, c: '.'))
9236 return Args.MakeArgString(Str: std::string(Str, End));
9237
9238 return Str;
9239}
9240
9241const char *Clang::getDependencyFileName(const ArgList &Args,
9242 const InputInfoList &Inputs) {
9243 // FIXME: Think about this more.
9244
9245 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
9246 SmallString<128> OutputFilename(OutputOpt->getValue());
9247 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
9248 return Args.MakeArgString(Str: OutputFilename);
9249 }
9250
9251 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
9252}
9253
9254// Begin ClangAs
9255
9256void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9257 ArgStringList &CmdArgs) const {
9258 StringRef CPUName;
9259 StringRef ABIName;
9260 const llvm::Triple &Triple = getToolChain().getTriple();
9261 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9262
9263 CmdArgs.push_back(Elt: "-target-abi");
9264 CmdArgs.push_back(Elt: ABIName.data());
9265}
9266
9267void ClangAs::AddX86TargetArgs(const ArgList &Args,
9268 ArgStringList &CmdArgs) const {
9269 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
9270 /*IsLTO=*/false);
9271
9272 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
9273 StringRef Value = A->getValue();
9274 if (Value == "intel" || Value == "att") {
9275 CmdArgs.push_back(Elt: "-mllvm");
9276 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
9277 } else {
9278 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
9279 << A->getSpelling() << Value;
9280 }
9281 }
9282}
9283
9284void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9285 ArgStringList &CmdArgs) const {
9286 CmdArgs.push_back(Elt: "-target-abi");
9287 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
9288 Triple: getToolChain().getTriple())
9289 .data());
9290}
9291
9292void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9293 ArgStringList &CmdArgs) const {
9294 const llvm::Triple &Triple = getToolChain().getTriple();
9295 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9296
9297 CmdArgs.push_back(Elt: "-target-abi");
9298 CmdArgs.push_back(Elt: ABIName.data());
9299
9300 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9301 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9302 CmdArgs.push_back(Elt: "-mllvm");
9303 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
9304 }
9305}
9306
9307void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
9308 const InputInfo &Output, const InputInfoList &Inputs,
9309 const ArgList &Args,
9310 const char *LinkingOutput) const {
9311 ArgStringList CmdArgs;
9312
9313 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9314 const InputInfo &Input = Inputs[0];
9315
9316 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9317 const std::string &TripleStr = Triple.getTriple();
9318 const auto &D = getToolChain().getDriver();
9319
9320 // Don't warn about "clang -w -c foo.s"
9321 Args.ClaimAllArgs(Id0: options::OPT_w);
9322 // and "clang -emit-llvm -c foo.s"
9323 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
9324
9325 claimNoWarnArgs(Args);
9326
9327 // Invoke ourselves in -cc1as mode.
9328 //
9329 // FIXME: Implement custom jobs for internal actions.
9330 CmdArgs.push_back(Elt: "-cc1as");
9331
9332 // Add the "effective" target triple.
9333 CmdArgs.push_back(Elt: "-triple");
9334 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
9335
9336 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
9337
9338 // Set the output mode, we currently only expect to be used as a real
9339 // assembler.
9340 CmdArgs.push_back(Elt: "-filetype");
9341 CmdArgs.push_back(Elt: "obj");
9342
9343 // Set the main file name, so that debug info works even with
9344 // -save-temps or preprocessed assembly.
9345 CmdArgs.push_back(Elt: "-main-file-name");
9346 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
9347
9348 // Add the target cpu
9349 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
9350 if (!CPU.empty()) {
9351 CmdArgs.push_back(Elt: "-target-cpu");
9352 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
9353 }
9354
9355 // Add the target features
9356 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
9357
9358 // Ignore explicit -force_cpusubtype_ALL option.
9359 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
9360
9361 // Pass along any -I options so we get proper .include search paths.
9362 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
9363
9364 // Pass along any --embed-dir or similar options so we get proper embed paths.
9365 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
9366
9367 // Determine the original source input.
9368 auto FindSource = [](const Action *S) -> const Action * {
9369 while (S->getKind() != Action::InputClass) {
9370 assert(!S->getInputs().empty() && "unexpected root action!");
9371 S = S->getInputs()[0];
9372 }
9373 return S;
9374 };
9375 const Action *SourceAction = FindSource(&JA);
9376
9377 // Forward -g and handle debug info related flags, assuming we are dealing
9378 // with an actual assembly file.
9379 bool WantDebug = false;
9380 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
9381 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
9382 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
9383 !A->getOption().matches(ID: options::OPT_ggdb0);
9384
9385 // If a -gdwarf argument appeared, remember it.
9386 bool EmitDwarf = false;
9387 if (const Arg *A = getDwarfNArg(Args))
9388 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9389
9390 bool EmitCodeView = false;
9391 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
9392 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9393
9394 // If the user asked for debug info but did not explicitly specify -gcodeview
9395 // or -gdwarf, ask the toolchain for the default format.
9396 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9397 switch (getToolChain().getDefaultDebugFormat()) {
9398 case llvm::codegenoptions::DIF_CodeView:
9399 EmitCodeView = true;
9400 break;
9401 case llvm::codegenoptions::DIF_DWARF:
9402 EmitDwarf = true;
9403 break;
9404 }
9405 }
9406
9407 // If the arguments don't imply DWARF, don't emit any debug info here.
9408 if (!EmitDwarf)
9409 WantDebug = false;
9410
9411 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9412 llvm::codegenoptions::NoDebugInfo;
9413
9414 // Add the -fdebug-compilation-dir flag if needed.
9415 const char *DebugCompilationDir =
9416 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
9417
9418 if (SourceAction->getType() == types::TY_Asm ||
9419 SourceAction->getType() == types::TY_PP_Asm) {
9420 // You might think that it would be ok to set DebugInfoKind outside of
9421 // the guard for source type, however there is a test which asserts
9422 // that some assembler invocation receives no -debug-info-kind,
9423 // and it's not clear whether that test is just overly restrictive.
9424 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9425 : llvm::codegenoptions::NoDebugInfo);
9426
9427 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
9428 CmdArgs);
9429
9430 // Set the AT_producer to the clang version when using the integrated
9431 // assembler on assembly source files.
9432 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
9433 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
9434
9435 // And pass along -I options
9436 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
9437 }
9438 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
9439 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9440 DebuggerTuning: llvm::DebuggerKind::Default);
9441 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
9442 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
9443
9444 // Handle -fPIC et al -- the relocation-model affects the assembler
9445 // for some targets.
9446 llvm::Reloc::Model RelocationModel;
9447 unsigned PICLevel;
9448 bool IsPIE;
9449 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
9450 ParsePICArgs(ToolChain: getToolChain(), Args);
9451
9452 const char *RMName = RelocationModelName(Model: RelocationModel);
9453 if (RMName) {
9454 CmdArgs.push_back(Elt: "-mrelocation-model");
9455 CmdArgs.push_back(Elt: RMName);
9456 }
9457
9458 // Optionally embed the -cc1as level arguments into the debug info, for build
9459 // analysis.
9460 if (getToolChain().UseDwarfDebugFlags()) {
9461 ArgStringList OriginalArgs;
9462 for (const auto &Arg : Args)
9463 Arg->render(Args, Output&: OriginalArgs);
9464
9465 SmallString<256> Flags;
9466 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9467 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
9468 for (const char *OriginalArg : OriginalArgs) {
9469 SmallString<128> EscapedArg;
9470 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
9471 Flags += " ";
9472 Flags += EscapedArg;
9473 }
9474 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
9475 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
9476 }
9477
9478 // FIXME: Add -static support, once we have it.
9479
9480 // Add target specific flags.
9481 switch (getToolChain().getArch()) {
9482 default:
9483 break;
9484
9485 case llvm::Triple::mips:
9486 case llvm::Triple::mipsel:
9487 case llvm::Triple::mips64:
9488 case llvm::Triple::mips64el:
9489 AddMIPSTargetArgs(Args, CmdArgs);
9490 break;
9491
9492 case llvm::Triple::x86:
9493 case llvm::Triple::x86_64:
9494 AddX86TargetArgs(Args, CmdArgs);
9495 break;
9496
9497 case llvm::Triple::arm:
9498 case llvm::Triple::armeb:
9499 case llvm::Triple::thumb:
9500 case llvm::Triple::thumbeb:
9501 // This isn't in AddARMTargetArgs because we want to do this for assembly
9502 // only, not C/C++.
9503 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9504 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9505 CmdArgs.push_back(Elt: "-mllvm");
9506 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
9507 }
9508 break;
9509
9510 case llvm::Triple::aarch64:
9511 case llvm::Triple::aarch64_32:
9512 case llvm::Triple::aarch64_be:
9513 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
9514 CmdArgs.push_back(Elt: "-mllvm");
9515 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
9516 }
9517 break;
9518
9519 case llvm::Triple::loongarch32:
9520 case llvm::Triple::loongarch64:
9521 AddLoongArchTargetArgs(Args, CmdArgs);
9522 break;
9523
9524 case llvm::Triple::riscv32:
9525 case llvm::Triple::riscv64:
9526 case llvm::Triple::riscv32be:
9527 case llvm::Triple::riscv64be:
9528 AddRISCVTargetArgs(Args, CmdArgs);
9529 break;
9530
9531 case llvm::Triple::hexagon:
9532 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9533 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9534 CmdArgs.push_back(Elt: "-mllvm");
9535 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
9536 }
9537 break;
9538 }
9539
9540 // Consume all the warning flags. Usually this would be handled more
9541 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9542 // doesn't handle that so rather than warning about unused flags that are
9543 // actually used, we'll lie by omission instead.
9544 // FIXME: Stop lying and consume only the appropriate driver flags
9545 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9546
9547 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9548 D: getToolChain().getDriver());
9549
9550 // Forward -Xclangas arguments to -cc1as
9551 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9552 Arg->claim();
9553 CmdArgs.push_back(Elt: Arg->getValue());
9554 }
9555
9556 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9557
9558 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9559 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9560 OutputFileName: Output.getFilename());
9561
9562 // Fixup any previous commands that use -object-file-name because when we
9563 // generated them, the final .obj name wasn't yet known.
9564 for (Command &J : C.getJobs()) {
9565 if (SourceAction != FindSource(&J.getSource()))
9566 continue;
9567 auto &JArgs = J.getArguments();
9568 for (unsigned I = 0; I < JArgs.size(); ++I) {
9569 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9570 Output.isFilename()) {
9571 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9572 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9573 OutputFileName: Output.getFilename());
9574 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9575 J.replaceArguments(List: NewArgs);
9576 break;
9577 }
9578 }
9579 }
9580
9581 assert(Output.isFilename() && "Unexpected lipo output.");
9582 CmdArgs.push_back(Elt: "-o");
9583 CmdArgs.push_back(Elt: Output.getFilename());
9584
9585 const llvm::Triple &T = getToolChain().getTriple();
9586 Arg *A;
9587 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9588 T.isOSBinFormatELF()) {
9589 CmdArgs.push_back(Elt: "-split-dwarf-output");
9590 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9591 }
9592
9593 if (Triple.isAMDGPU())
9594 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9595
9596 assert(Input.isFilename() && "Invalid input.");
9597 CmdArgs.push_back(Elt: Input.getFilename());
9598
9599 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9600 if (D.CC1Main && !D.CCGenDiagnostics) {
9601 // Invoke cc1as directly in this process.
9602 C.addCommand(Cmd: std::make_unique<CC1Command>(
9603 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9604 args: Output, args: D.getPrependArg()));
9605 } else {
9606 C.addCommand(Cmd: std::make_unique<Command>(
9607 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9608 args: Output, args: D.getPrependArg()));
9609 }
9610}
9611
9612// Begin OffloadBundler
9613void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9614 const InputInfo &Output,
9615 const InputInfoList &Inputs,
9616 const llvm::opt::ArgList &TCArgs,
9617 const char *LinkingOutput) const {
9618 // The version with only one output is expected to refer to a bundling job.
9619 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9620
9621 // The bundling command looks like this:
9622 // clang-offload-bundler -type=bc
9623 // -targets=host-triple,openmp-triple1,openmp-triple2
9624 // -output=output_file
9625 // -input=unbundle_file_host
9626 // -input=unbundle_file_tgt1
9627 // -input=unbundle_file_tgt2
9628
9629 ArgStringList CmdArgs;
9630
9631 // Get the type.
9632 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9633 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9634
9635 assert(JA.getInputs().size() == Inputs.size() &&
9636 "Not have inputs for all dependence actions??");
9637
9638 // Get the targets.
9639 SmallString<128> Triples;
9640 Triples += "-targets=";
9641 for (unsigned I = 0; I < Inputs.size(); ++I) {
9642 if (I)
9643 Triples += ',';
9644
9645 // Find ToolChain for this input.
9646 Action::OffloadKind CurKind = Action::OFK_Host;
9647 const ToolChain *CurTC = &getToolChain();
9648 const Action *CurDep = JA.getInputs()[I];
9649
9650 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9651 CurTC = nullptr;
9652 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) {
9653 assert(CurTC == nullptr && "Expected one dependence!");
9654 CurKind = A->getOffloadingDeviceKind();
9655 CurTC = TC;
9656 });
9657 }
9658 Triples += Action::GetOffloadKindName(Kind: CurKind);
9659 Triples += '-';
9660 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9661 Args: TCArgs, BA: CurDep->getOffloadingArch()))
9662 .normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9663
9664 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9665 Triples += '-';
9666 Triples += CurDep->getOffloadingArch().ArchName;
9667 }
9668 }
9669 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9670
9671 // Get bundled file command.
9672 CmdArgs.push_back(
9673 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9674
9675 // Get unbundled files command.
9676 for (unsigned I = 0; I < Inputs.size(); ++I) {
9677 SmallString<128> UB;
9678 UB += "-input=";
9679
9680 // Find ToolChain for this input.
9681 const ToolChain *CurTC = &getToolChain();
9682 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9683 CurTC = nullptr;
9684 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, BoundArch) {
9685 assert(CurTC == nullptr && "Expected one dependence!");
9686 CurTC = TC;
9687 });
9688 UB += C.addTempFile(
9689 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9690 } else {
9691 UB += CurTC->getInputFilename(Input: Inputs[I]);
9692 }
9693 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9694 }
9695 addOffloadCompressArgs(TCArgs, CmdArgs);
9696 // All the inputs are encoded as commands.
9697 C.addCommand(Cmd: std::make_unique<Command>(
9698 args: JA, args: *this, args: ResponseFileSupport::None(),
9699 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9700 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9701}
9702
9703void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9704 const InputInfo &Output,
9705 const InputInfoList &Inputs,
9706 const llvm::opt::ArgList &Args,
9707 const char *LinkingOutput) const {
9708 ArgStringList CmdArgs;
9709
9710 // Add the output file name.
9711 assert(Output.isFilename() && "Invalid output.");
9712 CmdArgs.push_back(Elt: "-o");
9713 CmdArgs.push_back(Elt: Output.getFilename());
9714
9715 // Create the inputs to bundle the needed metadata.
9716 for (const InputInfo &Input : Inputs) {
9717 const Action *OffloadAction = Input.getAction();
9718 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9719 const ArgList &TCArgs =
9720 C.getArgsForToolChain(TC, BA: OffloadAction->getOffloadingArch(),
9721 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9722 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9723 BoundArch Arch = OffloadAction->getOffloadingArch();
9724 if (Arch.empty())
9725 Arch = BoundArch(TCArgs.getLastArgValue(Id: options::OPT_march_EQ));
9726
9727 StringRef Kind =
9728 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9729
9730 ArgStringList Features;
9731 SmallVector<StringRef> FeatureArgs;
9732 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9733 ForAS: false);
9734 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9735 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9736
9737 // TODO: We need to pass in the full target-id and handle it properly in the
9738 // linker wrapper.
9739 SmallVector<std::string> Parts{
9740 "file=" + File.str(),
9741 "triple=" + TC->ComputeEffectiveClangTriple(Args: TCArgs, BA: Arch),
9742 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9743 "kind=" + Kind.str(),
9744 };
9745
9746 if (TC->isUsingLTO(Args: TCArgs, Kind: OffloadAction->getOffloadingDeviceKind()))
9747 for (StringRef Feature : FeatureArgs)
9748 Parts.emplace_back(Args: "feature=" + Feature.str());
9749
9750 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9751 }
9752
9753 C.addCommand(Cmd: std::make_unique<Command>(
9754 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9755 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9756 args&: CmdArgs, args: Inputs, args: Output));
9757}
9758
9759// Options that need the profile compiler-rt library on the target toolchain.
9760// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9761// too.
9762static bool requiresProfileRT(unsigned ID) {
9763 switch (ID) {
9764 case options::OPT_fprofile_generate:
9765 case options::OPT_fprofile_generate_EQ:
9766 case options::OPT_fprofile_instr_generate:
9767 case options::OPT_fprofile_instr_generate_EQ:
9768 case options::OPT_fcoverage_mapping:
9769 case options::OPT_fno_coverage_mapping:
9770 case options::OPT_fcoverage_compilation_dir_EQ:
9771 case options::OPT_ffile_compilation_dir_EQ:
9772 case options::OPT_fcoverage_prefix_map_EQ:
9773 return true;
9774 default:
9775 return false;
9776 }
9777}
9778
9779// Options that need the ubsan compiler-rt library on the target toolchain.
9780static bool requiresUBSanRT(unsigned ID) {
9781 switch (ID) {
9782 case options::OPT_fsanitize_EQ:
9783 case options::OPT_fno_sanitize_EQ:
9784 case options::OPT_fsanitize_minimal_runtime:
9785 case options::OPT_fno_sanitize_minimal_runtime:
9786 return true;
9787 default:
9788 return false;
9789 }
9790}
9791
9792void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9793 const InputInfo &Output,
9794 const InputInfoList &Inputs,
9795 const ArgList &Args,
9796 const char *LinkingOutput) const {
9797 using namespace options;
9798
9799 // A list of permitted options that will be forwarded to the embedded device
9800 // compilation job.
9801 const llvm::DenseSet<unsigned> CompilerOptions{
9802 OPT_v,
9803 OPT_hip_path_EQ,
9804 OPT_O_Group,
9805 OPT_g_Group,
9806 OPT_g_flags_Group,
9807 OPT_R_value_Group,
9808 OPT_R_Group,
9809 OPT_Xcuda_ptxas,
9810 OPT_ptxas_path_EQ,
9811 OPT_ftime_report,
9812 OPT_ftime_trace,
9813 OPT_ftime_trace_EQ,
9814 OPT_ftime_trace_granularity_EQ,
9815 OPT_ftime_trace_verbose,
9816 OPT_ftime_trace_compress_EQ,
9817 OPT_opt_record_file,
9818 OPT_opt_record_format,
9819 OPT_opt_record_passes,
9820 OPT_fsave_optimization_record,
9821 OPT_fsave_optimization_record_EQ,
9822 OPT_fno_save_optimization_record,
9823 OPT_foptimization_record_file_EQ,
9824 OPT_foptimization_record_passes_EQ,
9825 OPT_save_temps,
9826 OPT_save_temps_EQ,
9827 OPT_mcode_object_version_EQ,
9828 OPT_load,
9829 OPT_no_canonical_prefixes,
9830 OPT_fno_lto,
9831 OPT_flto,
9832 OPT_flto_partitions_EQ,
9833 OPT_flto_EQ,
9834 OPT_hipspv_pass_plugin_EQ,
9835 OPT_use_spirv_backend,
9836 OPT_no_use_spirv_backend,
9837 OPT_fmultilib_flag,
9838 OPT_fprofile_generate,
9839 OPT_fprofile_generate_EQ,
9840 OPT_fprofile_instr_generate,
9841 OPT_fprofile_instr_generate_EQ,
9842 OPT_fcoverage_mapping,
9843 OPT_fno_coverage_mapping,
9844 OPT_fcoverage_compilation_dir_EQ,
9845 OPT_ffile_compilation_dir_EQ,
9846 OPT_fcoverage_prefix_map_EQ,
9847 OPT_fsanitize_EQ,
9848 OPT_fno_sanitize_EQ,
9849 OPT_fsanitize_minimal_runtime,
9850 OPT_fno_sanitize_minimal_runtime,
9851 OPT_fsanitize_trap_EQ,
9852 OPT_fno_sanitize_trap_EQ,
9853 OPT_fslp_vectorize,
9854 OPT_fno_slp_vectorize,
9855 OPT_hipstdpar,
9856 OPT_fenable_spirv_size_optimization};
9857 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9858 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9859 // CMake implicit linker argument parsing.
9860 bool SuppressHIPNoRDCVerbose =
9861 JA.getType() == types::TY_HIP_FATBIN &&
9862 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
9863 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9864 return TC.getVFS().exists(
9865 Path: TC.getCompilerRT(Args, Component: Name, Type: ToolChain::FT_Static));
9866 };
9867 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9868 unsigned ID = A->getOption().getID();
9869 // Don't forward profiling arguments if the toolchain doesn't support it.
9870 // Without this check using it on the host would result in linker errors.
9871 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9872 // together to avoid a device cc1 diagnostic.
9873 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9874 return false;
9875 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9876 // Without this check using it on the host would result in linker errors.
9877 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal") &&
9878 !ToolChainHasRT(TC, "ubsan_standalone"))
9879 return false;
9880 // Don't forward -mllvm to toolchains that don't support LLVM.
9881 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9882 };
9883 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9884 const ToolChain &TC) {
9885 if (A->getOption().matches(ID: OPT_v) && SuppressHIPNoRDCVerbose)
9886 return false;
9887 return (Set.contains(V: A->getOption().getID()) ||
9888 (A->getOption().getGroup().isValid() &&
9889 Set.contains(V: A->getOption().getGroup().getID()))) &&
9890 ShouldForwardForToolChain(A, TC);
9891 };
9892
9893 ArgStringList CmdArgs;
9894 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9895 Action::OFK_HIP, Action::OFK_SYCL}) {
9896 auto TCRange = C.getOffloadToolChains(Kind);
9897 for (auto &I : llvm::make_range(p: TCRange)) {
9898 const ToolChain *TC = I.second;
9899
9900 // We do not use a bound architecture here so options passed only to a
9901 // specific architecture via -Xarch_<cpu> will not be forwarded.
9902 ArgStringList CompilerArgs;
9903 ArgStringList LinkerArgs;
9904 const DerivedArgList &ToolChainArgs =
9905 C.getArgsForToolChain(TC, /*BA=*/{}, DeviceOffloadKind: Kind);
9906 for (Arg *A : ToolChainArgs) {
9907 if (A->getOption().matches(ID: OPT_Zlinker_input))
9908 LinkerArgs.emplace_back(Args: A->getValue());
9909 else if (ShouldForward(CompilerOptions, A, *TC)) {
9910 A->claim();
9911 A->render(Args, Output&: CompilerArgs);
9912 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9913 A->claim();
9914 A->render(Args, Output&: LinkerArgs);
9915 }
9916 }
9917
9918 // If the user explicitly requested it via `--offload-arch` we should
9919 // extract it from any static libraries if present.
9920 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9921 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9922
9923 // If this is OpenMP the device linker will need `-lompdevice`.
9924 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9925 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9926 LinkerArgs.emplace_back(Args: "-lompdevice");
9927
9928 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9929 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9930 // flags to normal compilation.
9931 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9932 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9933 if (TC->getTriple().isSPIRV() &&
9934 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9935 Kind != Action::OFK_SYCL && !TC->isUsingLTO(Args: ToolChainArgs, Kind)) {
9936 // For SPIR-V some functions will be defined by the runtime so allow
9937 // unresolved symbols in `spirv-link`.
9938 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9939 // Don't optimize out exported symbols.
9940 LinkerArgs.emplace_back(Args: "--create-library");
9941 }
9942
9943 // Forward the SYCL device image split option to clang-sycl-linker.
9944 // The driver and clang-sycl-linker share the same value vocabulary, so
9945 // the value is passed through verbatim after validation.
9946 if (Kind == Action::OFK_SYCL) {
9947 if (Arg *A =
9948 ToolChainArgs.getLastArg(Ids: OPT_fsycl_device_image_split_EQ)) {
9949 StringRef Mode = A->getValue();
9950 if (Mode != "kernel" && Mode != "translation_unit" &&
9951 Mode != "link_unit")
9952 C.getDriver().Diag(DiagID: clang::diag::err_drv_invalid_value)
9953 << A->getSpelling() << Mode;
9954 else
9955 LinkerArgs.emplace_back(
9956 Args: Args.MakeArgString(Str: "--module-split-mode=" + Mode));
9957 }
9958 }
9959
9960 // Forward all of these to the appropriate toolchain.
9961 for (StringRef Arg : CompilerArgs)
9962 CmdArgs.push_back(Elt: Args.MakeArgString(
9963 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9964 for (StringRef Arg : LinkerArgs)
9965 CmdArgs.push_back(Elt: Args.MakeArgString(
9966 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9967
9968 // Forward the LTO mode for this toolchain.
9969 auto DeviceLTOMode = TC->getLTOMode(Args: ToolChainArgs, Kind);
9970 if (DeviceLTOMode == LTOK_Full)
9971 CmdArgs.push_back(Elt: Args.MakeArgString(
9972 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9973 else if (DeviceLTOMode == LTOK_Thin) {
9974 CmdArgs.push_back(Elt: Args.MakeArgString(
9975 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9976 if (TC->getTriple().isAMDGPU()) {
9977 CmdArgs.push_back(
9978 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9979 "=-plugin-opt=-force-import-all"));
9980 CmdArgs.push_back(
9981 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9982 "=-plugin-opt=-avail-extern-to-local"));
9983 CmdArgs.push_back(Elt: Args.MakeArgString(
9984 Str: "--device-linker=" + TC->getTripleString() +
9985 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9986 if (Kind == Action::OFK_OpenMP) {
9987 CmdArgs.push_back(
9988 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9989 "=-plugin-opt=-amdgpu-internalize-symbols"));
9990 }
9991 }
9992 }
9993 }
9994 }
9995
9996 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9997 CmdArgs.push_back(
9998 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
9999 else
10000 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
10001 getToolChain().getTripleString()));
10002
10003 if (Args.hasArg(Ids: options::OPT_v) && !SuppressHIPNoRDCVerbose)
10004 CmdArgs.push_back(Elt: "--wrapper-verbose");
10005 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ)) {
10006 CmdArgs.push_back(
10007 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
10008 CmdArgs.push_back(Elt: Args.MakeArgString(
10009 Str: Twine("--device-compiler=--cuda-path=") + A->getValue()));
10010 }
10011 if (Arg *A = Args.getLastArg(Ids: options::OPT_rocm_path_EQ)) {
10012 CmdArgs.push_back(Elt: Args.MakeArgString(
10013 Str: Twine("--device-compiler=--rocm-path=") + A->getValue()));
10014 }
10015
10016 // Construct the link job so we can wrap around it.
10017 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
10018 const auto &LinkCommand = C.getJobs().getJobs().back();
10019
10020 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10021 // wrapper.
10022 for (Arg *A :
10023 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
10024 StringRef Val = A->getValue(N: 0);
10025 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10026 auto WrapperOption =
10027 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10028 if (Val.empty())
10029 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
10030 else
10031 CmdArgs.push_back(Elt: Args.MakeArgString(
10032 Str: WrapperOption +
10033 ToolChain::normalizeOffloadTriple(OrigTT: Val.drop_front()).str() + "=" +
10034 A->getValue(N: 1)));
10035 }
10036 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
10037 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
10038
10039 // Embed bitcode instead of an object in JIT mode.
10040 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
10041 Neg: options::OPT_fno_openmp_target_jit, Default: false))
10042 CmdArgs.push_back(Elt: "--embed-bitcode");
10043
10044 // Save temporary files created by the linker wrapper.
10045 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
10046 Args.hasArg(Ids: options::OPT_save_temps))
10047 CmdArgs.push_back(Elt: "--save-temps");
10048
10049 // Pass in the C library for GPUs if present and not disabled.
10050 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
10051 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
10052 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
10053 Ids: options::OPT_nogpulibc)) {
10054 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
10055 // The device C library is only available for NVPTX and AMDGPU targets
10056 // and we only link it by default for OpenMP currently.
10057 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10058 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
10059 return;
10060 bool HasLibC = TC.getStdlibIncludePath().has_value();
10061 if (HasLibC) {
10062 CmdArgs.push_back(Elt: Args.MakeArgString(
10063 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10064 CmdArgs.push_back(Elt: Args.MakeArgString(
10065 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10066 }
10067 auto HasCompilerRT = getToolChain().getVFS().exists(
10068 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
10069 /*IsFortran=*/false));
10070 if (HasCompilerRT)
10071 CmdArgs.push_back(
10072 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10073 "-lclang_rt.builtins"));
10074
10075 bool HasFlangRT = getToolChain().getVFS().exists(
10076 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
10077 /*IsFortran=*/true));
10078 if (HasFlangRT && C.getDriver().IsFlangMode())
10079 CmdArgs.push_back(
10080 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10081 "-lflang_rt.runtime"));
10082 });
10083 }
10084
10085 // Add the linker arguments to be forwarded by the wrapper.
10086 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
10087 LinkCommand->getExecutable()));
10088
10089 // We use action type to differentiate two use cases of the linker wrapper.
10090 // TY_Image for normal linker wrapper work.
10091 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10092 // binary directly.
10093 assert(JA.getType() == types::TY_HIP_FATBIN ||
10094 JA.getType() == types::TY_SYCL_FATBIN ||
10095 JA.getType() == types::TY_Image);
10096 if (JA.getType() != types::TY_Image) {
10097 CmdArgs.push_back(Elt: "--emit-fatbin-only");
10098 CmdArgs.append(IL: {"-o", Output.getFilename()});
10099 for (auto Input : Inputs)
10100 CmdArgs.push_back(Elt: Input.getFilename());
10101 } else {
10102 for (const char *LinkArg : LinkCommand->getArguments())
10103 CmdArgs.push_back(Elt: LinkArg);
10104 }
10105
10106 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
10107
10108 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10109 if (OffloadJobs.A) {
10110 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10111 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
10112 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10113 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=" +
10114 Twine(OffloadJobs.NumThreads)));
10115 } else if (!OffloadJobs.A->isClaimed()) {
10116 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
10117 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10118 }
10119 }
10120
10121 // Propagate -no-canonical-prefixes.
10122 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
10123 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
10124
10125 const char *Exec =
10126 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
10127
10128 // Replace the executable and arguments of the link job with the
10129 // wrapper.
10130 LinkCommand->replaceExecutable(Exe: Exec);
10131 LinkCommand->replaceArguments(List: CmdArgs);
10132}
10133