1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
21#include "clang/Basic/CLWarnings.h"
22#include "clang/Basic/CodeGenOptions.h"
23#include "clang/Basic/HeaderInclude.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/MakeSupport.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
30#include "clang/Driver/CommonArgs.h"
31#include "clang/Driver/Distro.h"
32#include "clang/Driver/InputInfo.h"
33#include "clang/Driver/SanitizerArgs.h"
34#include "clang/Driver/Types.h"
35#include "clang/Driver/XRayArgs.h"
36#include "clang/Options/OptionUtils.h"
37#include "clang/Options/Options.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/BinaryFormat/Magic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Frontend/Debug/Options.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Option/ArgList.h"
46#include "llvm/ProfileData/InstrProfReader.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Compression.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64#include <iterator>
65
66using namespace clang::driver;
67using namespace clang::driver::tools;
68using namespace clang;
69using namespace llvm::opt;
70
71static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
73 Ids: options::OPT_fminimize_whitespace,
74 Ids: options::OPT_fno_minimize_whitespace,
75 Ids: options::OPT_fkeep_system_includes,
76 Ids: options::OPT_fno_keep_system_includes)) {
77 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
78 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
79 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
80 << A->getBaseArg().getAsString(Args)
81 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 }
83 }
84}
85
86static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
87 // In gcc, only ARM checks this, but it seems reasonable to check universally.
88 if (Args.hasArg(Ids: options::OPT_static))
89 if (const Arg *A =
90 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
91 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
92 << "-static";
93}
94
95/// Apply \a Work on the current tool chain \a RegularToolChain and any other
96/// offloading tool chain that is associated with the current action \a JA.
97static void
98forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
99 const ToolChain &RegularToolChain,
100 llvm::function_ref<void(const ToolChain &)> Work) {
101 // Apply Work on the current/regular tool chain.
102 Work(RegularToolChain);
103
104 // Apply Work on all the offloading tool chains associated with the current
105 // action.
106 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
107 Action::OFK_HIP, Action::OFK_SYCL}) {
108 if (JA.isHostOffloading(OKind: Kind)) {
109 auto TCs = C.getOffloadToolChains(Kind);
110 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
111 Work(*II->second);
112 } else if (JA.isDeviceOffloading(OKind: Kind))
113 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
114 }
115}
116
117static bool
118shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
119 const llvm::Triple &Triple) {
120 // We use the zero-cost exception tables for Objective-C if the non-fragile
121 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
122 // later.
123 if (runtime.isNonFragile())
124 return true;
125
126 if (!Triple.isMacOSX())
127 return false;
128
129 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
130 (Triple.getArch() == llvm::Triple::x86_64 ||
131 Triple.getArch() == llvm::Triple::arm));
132}
133
134/// Adds exception related arguments to the driver command arguments. There's a
135/// main flag, -fexceptions and also language specific flags to enable/disable
136/// C++ and Objective-C exceptions. This makes it possible to for example
137/// disable C++ exceptions but enable Objective-C exceptions.
138static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
139 const ToolChain &TC, bool KernelOrKext,
140 bool IsDeviceOffloadAction,
141 const ObjCRuntime &objcRuntime,
142 ArgStringList &CmdArgs) {
143 const llvm::Triple &Triple = TC.getTriple();
144
145 if (KernelOrKext) {
146 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
147 // arguments now to avoid warnings about unused arguments.
148 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
154 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
155 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
156 return false;
157 }
158
159 // See if the user explicitly enabled exceptions.
160 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
161 Default: false);
162
163 // Async exceptions are Windows MSVC only.
164 if (Triple.isWindowsMSVCEnvironment()) {
165 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
166 Neg: options::OPT_fno_async_exceptions, Default: false);
167 if (EHa) {
168 CmdArgs.push_back(Elt: "-fasync-exceptions");
169 EH = true;
170 }
171 }
172
173 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
174 // is not necessarily sensible, but follows GCC.
175 if (types::isObjC(Id: InputType) &&
176 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
177 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
178 CmdArgs.push_back(Elt: "-fobjc-exceptions");
179
180 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
181 }
182
183 if (types::isCXX(Id: InputType)) {
184 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
186 !Triple.isPS() && !Triple.isDriverKit() &&
187 !(Triple.isGPU() && !IsDeviceOffloadAction);
188 Arg *ExceptionArg = Args.getLastArg(
189 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
190 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
191 if (ExceptionArg)
192 CXXExceptionsEnabled =
193 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
194 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
195
196 if (CXXExceptionsEnabled) {
197 CmdArgs.push_back(Elt: "-fcxx-exceptions");
198
199 EH = true;
200 }
201 }
202
203 // OPT_fignore_exceptions means exception could still be thrown,
204 // but no clean up or catch would happen in current module.
205 // So we do not set EH to false.
206 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
207
208 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
209 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
210
211 if (EH)
212 CmdArgs.push_back(Elt: "-fexceptions");
213 return EH;
214}
215
216static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
217 const JobAction &JA) {
218 bool Default = true;
219 if (TC.getTriple().isOSDarwin()) {
220 // The native darwin assembler doesn't support the linker_option directives,
221 // so we disable them if we think the .s file will be passed to it.
222 Default = TC.useIntegratedAs();
223 }
224 // The linker_option directives are intended for host compilation.
225 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
226 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
227 Default = false;
228 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
229 Default);
230}
231
232/// Add a CC1 option to specify the debug compilation directory.
233static const char *addDebugCompDirArg(const ArgList &Args,
234 ArgStringList &CmdArgs,
235 const llvm::vfs::FileSystem &VFS) {
236 std::string DebugCompDir;
237 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
238 Ids: options::OPT_fdebug_compilation_dir_EQ))
239 DebugCompDir = A->getValue();
240
241 if (DebugCompDir.empty()) {
242 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
243 DebugCompDir = std::move(*CWD);
244 else
245 return nullptr;
246 }
247 CmdArgs.push_back(
248 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
249 StringRef Path(CmdArgs.back());
250 return Path.substr(Start: Path.find(C: '=') + 1).data();
251}
252
253static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
254 const char *DebugCompilationDir,
255 const char *OutputFileName) {
256 // No need to generate a value for -object-file-name if it was provided.
257 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
258 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
259 return;
260
261 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
262 return;
263
264 SmallString<128> ObjFileNameForDebug(OutputFileName);
265 if (ObjFileNameForDebug != "-" &&
266 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
267 (!DebugCompilationDir ||
268 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
269 // Make the path absolute in the debug infos like MSVC does.
270 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
271 }
272 // If the object file name is a relative path, then always use Windows
273 // backslash style as -object-file-name is used for embedding object file path
274 // in codeview and it can only be generated when targeting on Windows.
275 // Otherwise, just use native absolute path.
276 llvm::sys::path::Style Style =
277 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
278 ? llvm::sys::path::Style::native
279 : llvm::sys::path::Style::windows_backslash;
280 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
281 style: Style);
282 CmdArgs.push_back(
283 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
284}
285
286/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
287static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
288 const ArgList &Args, ArgStringList &CmdArgs) {
289 auto AddOneArg = [&](StringRef Map, StringRef Name) {
290 if (!Map.contains(C: '='))
291 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
292 else
293 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
294 };
295
296 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
297 Ids: options::OPT_fdebug_prefix_map_EQ)) {
298 AddOneArg(A->getValue(), A->getOption().getName());
299 A->claim();
300 }
301 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
302 if (GlobalRemapEntry.empty())
303 return;
304 AddOneArg(GlobalRemapEntry, "environment");
305}
306
307/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
308static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
309 ArgStringList &CmdArgs) {
310 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
311 Ids: options::OPT_fmacro_prefix_map_EQ)) {
312 StringRef Map = A->getValue();
313 if (!Map.contains(C: '='))
314 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
315 << Map << A->getOption().getName();
316 else
317 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
318 A->claim();
319 }
320}
321
322/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
323static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
324 ArgStringList &CmdArgs) {
325 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
326 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
327 StringRef Map = A->getValue();
328 if (!Map.contains(C: '='))
329 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
330 << Map << A->getOption().getName();
331 else
332 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
333 A->claim();
334 }
335}
336
337/// Add -x lang to \p CmdArgs for \p Input.
338static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
339 ArgStringList &CmdArgs) {
340 // When using -verify-pch, we don't want to provide the type
341 // 'precompiled-header' if it was inferred from the file extension
342 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
343 return;
344
345 CmdArgs.push_back(Elt: "-x");
346 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
347 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
348 else {
349 // Map the driver type to the frontend type. This is mostly an identity
350 // mapping, except that the distinction between module interface units
351 // and other source files does not exist at the frontend layer.
352 const char *ClangType;
353 switch (Input.getType()) {
354 case types::TY_CXXModule:
355 case types::TY_CXXStdModule:
356 ClangType = "c++";
357 break;
358 case types::TY_PP_CXXModule:
359 ClangType = "c++-cpp-output";
360 break;
361 default:
362 ClangType = types::getTypeName(Id: Input.getType());
363 break;
364 }
365 CmdArgs.push_back(Elt: ClangType);
366 }
367}
368
369static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
370 const JobAction &JA, const InputInfo &Output,
371 const ArgList &Args, SanitizerArgs &SanArgs,
372 ArgStringList &CmdArgs) {
373 const Driver &D = TC.getDriver();
374 const llvm::Triple &T = TC.getTriple();
375 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
376 Ids: options::OPT_fprofile_generate_EQ,
377 Ids: options::OPT_fno_profile_generate);
378 if (PGOGenerateArg &&
379 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
380 PGOGenerateArg = nullptr;
381
382 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
383
384 auto *ProfileGenerateArg = Args.getLastArg(
385 Ids: options::OPT_fprofile_instr_generate,
386 Ids: options::OPT_fprofile_instr_generate_EQ,
387 Ids: options::OPT_fno_profile_instr_generate);
388 if (ProfileGenerateArg &&
389 ProfileGenerateArg->getOption().matches(
390 ID: options::OPT_fno_profile_instr_generate))
391 ProfileGenerateArg = nullptr;
392
393 if (PGOGenerateArg && ProfileGenerateArg)
394 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
395 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
396
397 auto *ProfileUseArg = getLastProfileUseArg(Args);
398
399 if (PGOGenerateArg && ProfileUseArg)
400 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
401 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
402
403 if (ProfileGenerateArg && ProfileUseArg)
404 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
405 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
406
407 if (CSPGOGenerateArg && PGOGenerateArg) {
408 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
409 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
410 PGOGenerateArg = nullptr;
411 }
412
413 if (TC.getTriple().isOSAIX()) {
414 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
415 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
416 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
417 }
418
419 if (ProfileGenerateArg) {
420 if (ProfileGenerateArg->getOption().matches(
421 ID: options::OPT_fprofile_instr_generate_EQ))
422 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
423 ProfileGenerateArg->getValue()));
424 // The default is to use Clang Instrumentation.
425 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
426 if (TC.getTriple().isWindowsMSVCEnvironment() &&
427 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
428 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
429 // Add dependent lib for clang_rt.profile
430 CmdArgs.push_back(Elt: Args.MakeArgString(
431 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
432 }
433 }
434
435 if (auto *ColdFuncCoverageArg = Args.getLastArg(
436 Ids: options::OPT_fprofile_generate_cold_function_coverage,
437 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
438 SmallString<128> Path(
439 ColdFuncCoverageArg->getOption().matches(
440 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
441 ? ColdFuncCoverageArg->getValue()
442 : "");
443 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
444 // FIXME: Idealy the file path should be passed through
445 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
446 // shared with other profile use path(see PGOOptions), we need to refactor
447 // PGOOptions to make it work.
448 CmdArgs.push_back(Elt: "-mllvm");
449 CmdArgs.push_back(Elt: Args.MakeArgString(
450 Str: Twine("--instrument-cold-function-only-path=") + Path));
451 CmdArgs.push_back(Elt: "-mllvm");
452 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
453 CmdArgs.push_back(Elt: "-mllvm");
454 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
455 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
456 }
457
458 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
459 if (!PGOGenerateArg && !CSPGOGenerateArg)
460 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
461 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
462 CmdArgs.push_back(Elt: "-mllvm");
463 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
464 }
465
466 Arg *PGOGenArg = nullptr;
467 if (PGOGenerateArg) {
468 assert(!CSPGOGenerateArg);
469 PGOGenArg = PGOGenerateArg;
470 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
471 }
472 if (CSPGOGenerateArg) {
473 assert(!PGOGenerateArg);
474 PGOGenArg = CSPGOGenerateArg;
475 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
476 }
477 if (PGOGenArg) {
478 if (TC.getTriple().isWindowsMSVCEnvironment() &&
479 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
480 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
481 // Add dependent lib for clang_rt.profile
482 CmdArgs.push_back(Elt: Args.MakeArgString(
483 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
484 }
485 if (PGOGenArg->getOption().matches(
486 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
487 : options::OPT_fcs_profile_generate_EQ)) {
488 SmallString<128> Path(PGOGenArg->getValue());
489 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
490 CmdArgs.push_back(
491 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
492 }
493 }
494
495 if (ProfileUseArg) {
496 SmallString<128> UsePathBuf;
497 StringRef UsePath;
498 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
499 UsePath = ProfileUseArg->getValue();
500 else if ((ProfileUseArg->getOption().matches(
501 ID: options::OPT_fprofile_use_EQ) ||
502 ProfileUseArg->getOption().matches(
503 ID: options::OPT_fprofile_instr_use))) {
504 UsePathBuf =
505 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
506 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
507 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
508 UsePath = UsePathBuf;
509 }
510 auto ReaderOrErr =
511 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
512 if (auto E = ReaderOrErr.takeError()) {
513 auto DiagID = D.getDiags().getCustomDiagID(
514 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
515 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
516 D.Diag(DiagID) << UsePath.str() << EI.message();
517 });
518 } else {
519 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
520 std::move(ReaderOrErr.get());
521 StringRef UseKind;
522 // Currently memprof profiles are only added at the IR level. Mark the
523 // profile type as IR in that case as well and the subsequent matching
524 // needs to detect which is available (might be one or both).
525 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
526 if (PGOReader->hasCSIRLevelProfile())
527 UseKind = "csllvm";
528 else
529 UseKind = "llvm";
530 } else
531 UseKind = "clang";
532
533 CmdArgs.push_back(
534 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
535 CmdArgs.push_back(
536 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
537 }
538 }
539
540 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
541 Neg: options::OPT_fno_test_coverage, Default: false) ||
542 Args.hasArg(Ids: options::OPT_coverage);
543 bool EmitCovData = TC.needsGCovInstrumentation(Args);
544
545 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
546 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
547 if (!ProfileGenerateArg)
548 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
549 << "-fcoverage-mapping"
550 << "-fprofile-instr-generate";
551
552 CmdArgs.push_back(Elt: "-fcoverage-mapping");
553 }
554
555 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
556 Default: false)) {
557 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
558 Neg: options::OPT_fno_coverage_mapping, Default: false))
559 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
560 << "-fcoverage-mcdc"
561 << "-fcoverage-mapping";
562
563 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
564 }
565
566 StringRef CoverageCompDir;
567 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
568 Ids: options::OPT_fcoverage_compilation_dir_EQ))
569 CoverageCompDir = A->getValue();
570 if (CoverageCompDir.empty()) {
571 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
572 CmdArgs.push_back(
573 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
574 } else
575 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
576 CoverageCompDir));
577
578 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
579 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
580 if (!Args.hasArg(Ids: options::OPT_coverage))
581 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
582 << "-fprofile-exclude-files="
583 << "--coverage";
584
585 StringRef v = Arg->getValue();
586 CmdArgs.push_back(
587 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
588 }
589
590 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
591 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
592 if (!Args.hasArg(Ids: options::OPT_coverage))
593 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
594 << "-fprofile-filter-files="
595 << "--coverage";
596
597 StringRef v = Arg->getValue();
598 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
599 }
600
601 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
602 StringRef Val = A->getValue();
603 if (Val == "atomic" || Val == "prefer-atomic")
604 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
605 else if (Val != "single")
606 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
607 << A->getSpelling() << Val;
608 }
609 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
610 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
611 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
612 << A->getSpelling()
613 << "-fprofile-generate, -fprofile-instr-generate, or "
614 "-fcs-profile-generate";
615 else {
616 CmdArgs.push_back(Elt: "-fprofile-continuous");
617 // Platforms that require a bias variable:
618 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
619 CmdArgs.push_back(Elt: "-mllvm");
620 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
621 }
622 // -fprofile-instr-generate does not decide the profile file name in the
623 // FE, and so it does not define the filename symbol
624 // (__llvm_profile_filename). Instead, the runtime uses the name
625 // "default.profraw" for the profile file. When continuous mode is ON, we
626 // will create the filename symbol so that we can insert the "%c"
627 // modifier.
628 if (ProfileGenerateArg &&
629 (ProfileGenerateArg->getOption().matches(
630 ID: options::OPT_fprofile_instr_generate) ||
631 (ProfileGenerateArg->getOption().matches(
632 ID: options::OPT_fprofile_instr_generate_EQ) &&
633 strlen(s: ProfileGenerateArg->getValue()) == 0)))
634 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
635 }
636 }
637
638 int FunctionGroups = 1;
639 int SelectedFunctionGroup = 0;
640 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
641 StringRef Val = A->getValue();
642 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
643 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
644 }
645 if (const auto *A =
646 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
647 StringRef Val = A->getValue();
648 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
649 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
650 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
651 }
652 if (FunctionGroups != 1)
653 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
654 Twine(FunctionGroups)));
655 if (SelectedFunctionGroup != 0)
656 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
657 Twine(SelectedFunctionGroup)));
658
659 // Leave -fprofile-dir= an unused argument unless .gcda emission is
660 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
661 // the flag used. There is no -fno-profile-dir, so the user has no
662 // targeted way to suppress the warning.
663 Arg *FProfileDir = nullptr;
664 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
665 Args.hasArg(Ids: options::OPT_coverage))
666 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
667
668 // Put the .gcno and .gcda files (if needed) next to the primary output file,
669 // or fall back to a file in the current directory for `clang -c --coverage
670 // d/a.c` in the absence of -o.
671 if (EmitCovNotes || EmitCovData) {
672 SmallString<128> CoverageFilename;
673 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
674 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
675 // path separator.
676 CoverageFilename = DumpDir->getValue();
677 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
678 } else if (Arg *FinalOutput =
679 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
680 CoverageFilename = FinalOutput->getValue();
681 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
682 CoverageFilename = FinalOutput->getValue();
683 } else {
684 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
685 }
686 if (llvm::sys::path::is_relative(path: CoverageFilename))
687 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
688 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
689 if (EmitCovNotes) {
690 CmdArgs.push_back(
691 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
692 }
693
694 if (EmitCovData) {
695 if (FProfileDir) {
696 SmallString<128> Gcno = std::move(CoverageFilename);
697 CoverageFilename = FProfileDir->getValue();
698 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
699 }
700 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
701 CmdArgs.push_back(
702 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
703 }
704 }
705}
706
707static void
708RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
709 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
710 unsigned DwarfVersion,
711 llvm::DebuggerKind DebuggerTuning) {
712 addDebugInfoKind(CmdArgs, DebugInfoKind);
713 if (DwarfVersion > 0)
714 CmdArgs.push_back(
715 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
716 switch (DebuggerTuning) {
717 case llvm::DebuggerKind::GDB:
718 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
719 break;
720 case llvm::DebuggerKind::LLDB:
721 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
722 break;
723 case llvm::DebuggerKind::SCE:
724 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
725 break;
726 case llvm::DebuggerKind::DBX:
727 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
728 break;
729 default:
730 break;
731 }
732}
733
734static void RenderDebugInfoCompressionArgs(const ArgList &Args,
735 ArgStringList &CmdArgs,
736 const Driver &D,
737 const ToolChain &TC) {
738 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
739 if (!A)
740 return;
741 if (checkDebugInfoOption(A, Args, D, TC)) {
742 StringRef Value = A->getValue();
743 if (Value == "none") {
744 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
745 } else if (Value == "zlib") {
746 if (llvm::compression::zlib::isAvailable()) {
747 CmdArgs.push_back(
748 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
749 } else {
750 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
751 }
752 } else if (Value == "zstd") {
753 if (llvm::compression::zstd::isAvailable()) {
754 CmdArgs.push_back(
755 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
756 } else {
757 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
758 }
759 } else {
760 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
761 << A->getSpelling() << Value;
762 }
763 }
764}
765
766static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
767 const ArgList &Args,
768 ArgStringList &CmdArgs,
769 bool IsCC1As = false) {
770 // If no version was requested by the user, use the default value from the
771 // back end. This is consistent with the value returned from
772 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
773 // requiring the corresponding llvm to have the AMDGPU target enabled,
774 // provided the user (e.g. front end tests) can use the default.
775 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
776 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
777 CmdArgs.insert(I: CmdArgs.begin() + 1,
778 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
779 Twine(CodeObjVer)));
780 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
781 // -cc1as does not accept -mcode-object-version option.
782 if (!IsCC1As)
783 CmdArgs.insert(I: CmdArgs.begin() + 1,
784 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
785 Twine(CodeObjVer)));
786 }
787}
788
789static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
790 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
791 D.getVFS().getBufferForFile(Name: Path);
792 if (!MemBuf)
793 return false;
794 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
795 if (Magic == llvm::file_magic::unknown)
796 return false;
797 // Return true for both raw Clang AST files and object files which may
798 // contain a __clangast section.
799 if (Magic == llvm::file_magic::clang_ast)
800 return true;
801 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
802 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
803 return !Obj.takeError();
804}
805
806static bool gchProbe(const Driver &D, StringRef Path) {
807 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
808 if (!Status)
809 return false;
810
811 if (Status->isDirectory()) {
812 std::error_code EC;
813 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
814 !EC && DI != DE; DI = DI.increment(EC)) {
815 if (maybeHasClangPchSignature(D, Path: DI->path()))
816 return true;
817 }
818 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
819 return false;
820 }
821
822 if (maybeHasClangPchSignature(D, Path))
823 return true;
824 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
825 return false;
826}
827
828void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
829 const Driver &D, const ArgList &Args,
830 ArgStringList &CmdArgs,
831 const InputInfo &Output,
832 const InputInfoList &Inputs) const {
833 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
834
835 CheckPreprocessingOptions(D, Args);
836
837 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
838 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
839
840 // Handle dependency file generation.
841 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
842 if (!ArgM)
843 ArgM = Args.getLastArg(Ids: options::OPT_M);
844 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
845 if (!ArgMD)
846 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
847
848 // -M and -MM imply -w.
849 if (ArgM)
850 CmdArgs.push_back(Elt: "-w");
851 else
852 ArgM = ArgMD;
853
854 if (ArgM) {
855 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
856 // Determine the output location.
857 const char *DepFile;
858 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
859 DepFile = MF->getValue();
860 C.addFailureResultFile(Name: DepFile, JA: &JA);
861 } else if (Output.getType() == types::TY_Dependencies) {
862 DepFile = Output.getFilename();
863 } else if (!ArgMD) {
864 DepFile = "-";
865 } else {
866 DepFile = getDependencyFileName(Args, Inputs);
867 C.addFailureResultFile(Name: DepFile, JA: &JA);
868 }
869 CmdArgs.push_back(Elt: "-dependency-file");
870 CmdArgs.push_back(Elt: DepFile);
871 }
872 // Cmake generates dependency files using all compilation options specified
873 // by users. Claim those not used for dependency files.
874 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
875 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
876 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
877 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
878 }
879
880 bool HasTarget = false;
881 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
882 HasTarget = true;
883 A->claim();
884 if (A->getOption().matches(ID: options::OPT_MT)) {
885 A->render(Args, Output&: CmdArgs);
886 } else {
887 CmdArgs.push_back(Elt: "-MT");
888 SmallString<128> Quoted;
889 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
890 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
891 }
892 }
893
894 // Add a default target if one wasn't specified.
895 if (!HasTarget) {
896 const char *DepTarget;
897
898 // If user provided -o, that is the dependency target, except
899 // when we are only generating a dependency file.
900 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
901 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
902 DepTarget = OutputOpt->getValue();
903 } else {
904 // Otherwise derive from the base input.
905 //
906 // FIXME: This should use the computed output file location.
907 SmallString<128> P(Inputs[0].getBaseInput());
908 llvm::sys::path::replace_extension(path&: P, extension: "o");
909 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
910 }
911
912 CmdArgs.push_back(Elt: "-MT");
913 SmallString<128> Quoted;
914 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
915 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
916 }
917
918 if (ArgM->getOption().matches(ID: options::OPT_M) ||
919 ArgM->getOption().matches(ID: options::OPT_MD))
920 CmdArgs.push_back(Elt: "-sys-header-deps");
921
922 // Determine module file deps mode.
923 StringRef ModuleFileDepsVal;
924 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_file_deps_EQ,
925 Ids: options::OPT_fmodule_file_deps,
926 Ids: options::OPT_fno_module_file_deps)) {
927 if (A->getOption().matches(ID: options::OPT_fmodule_file_deps_EQ))
928 ModuleFileDepsVal = A->getValue();
929 else if (A->getOption().matches(ID: options::OPT_fmodule_file_deps))
930 ModuleFileDepsVal = "all";
931 else
932 ModuleFileDepsVal = "none";
933 } else if (isa<PrecompileJobAction>(Val: JA)) {
934 ModuleFileDepsVal = "all";
935 }
936 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
937 CmdArgs.push_back(
938 Elt: Args.MakeArgString(Str: "-module-file-deps=" + ModuleFileDepsVal));
939 }
940
941 if (Args.hasArg(Ids: options::OPT_MG)) {
942 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
943 ArgM->getOption().matches(ID: options::OPT_MMD))
944 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
945 CmdArgs.push_back(Elt: "-MG");
946 }
947
948 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
949 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
950
951 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
952 // before we -I or -include anything else, because we must pick up the
953 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
954 // rather than from e.g. /usr/local/include.
955 if (JA.isOffloading(OKind: Action::OFK_Cuda))
956 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
957 if (JA.isOffloading(OKind: Action::OFK_HIP))
958 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
959 if (JA.isOffloading(OKind: Action::OFK_SYCL))
960 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
961
962 // If we are offloading to a target via OpenMP we need to include the
963 // openmp_wrappers folder which contains alternative system headers.
964 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
965 !Args.hasArg(Ids: options::OPT_nostdinc) &&
966 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
967 Default: true) &&
968 getToolChain().getTriple().isGPU()) {
969 if (!Args.hasArg(Ids: options::OPT_nobuiltininc)) {
970 // Add openmp_wrappers/* to our system include path. This lets us wrap
971 // standard library headers.
972 SmallString<128> P(D.ResourceDir);
973 llvm::sys::path::append(path&: P, a: "include");
974 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
975 CmdArgs.push_back(Elt: "-internal-isystem");
976 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
977 }
978
979 CmdArgs.push_back(Elt: "-include");
980 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
981 }
982
983 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm)) {
984 // Add llvm_wrappers/* to our system include path. This lets us wrap
985 // standard library headers and other headers.
986 SmallString<128> P(D.ResourceDir);
987 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
988 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
989 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
990 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
991 else
992 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
993 }
994
995 // Add -i* options, and automatically translate to
996 // -include-pch/-include-pth for transparent PCH support. It's
997 // wonky, but we include looking for .gch so we can support seamless
998 // replacement into a build system already set up to be generating
999 // .gch files.
1000
1001 if (getToolChain().getDriver().IsCLMode()) {
1002 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
1003 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
1004 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1005 JA.getKind() <= Action::AssembleJobClass) {
1006 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
1007 // -fpch-instantiate-templates is the default when creating
1008 // precomp using /Yc
1009 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
1010 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
1011 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
1012 }
1013 if (YcArg || YuArg) {
1014 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1015 if (!isa<PrecompileJobAction>(Val: JA)) {
1016 CmdArgs.push_back(Elt: "-include-pch");
1017 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1018 C, BaseName: !ThroughHeader.empty()
1019 ? ThroughHeader
1020 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1021 }
1022
1023 if (ThroughHeader.empty()) {
1024 CmdArgs.push_back(Elt: Args.MakeArgString(
1025 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1026 } else {
1027 CmdArgs.push_back(
1028 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1029 }
1030 }
1031 }
1032
1033 bool RenderedImplicitInclude = false;
1034 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1035 if (A->getOption().matches(ID: options::OPT_include) &&
1036 D.getProbePrecompiled()) {
1037 // Handling of gcc-style gch precompiled headers.
1038 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1039 RenderedImplicitInclude = true;
1040
1041 bool FoundPCH = false;
1042 SmallString<128> P(A->getValue());
1043 // We want the files to have a name like foo.h.pch. Add a dummy extension
1044 // so that replace_extension does the right thing.
1045 P += ".dummy";
1046 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1047 if (D.getVFS().exists(Path: P))
1048 FoundPCH = true;
1049
1050 if (!FoundPCH) {
1051 // For GCC compat, probe for a file or directory ending in .gch instead.
1052 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1053 FoundPCH = gchProbe(D, Path: P.str());
1054 }
1055
1056 if (FoundPCH) {
1057 if (IsFirstImplicitInclude) {
1058 A->claim();
1059 CmdArgs.push_back(Elt: "-include-pch");
1060 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1061 continue;
1062 } else {
1063 // Ignore the PCH if not first on command line and emit warning.
1064 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1065 << A->getAsString(Args);
1066 }
1067 }
1068 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1069 // Handling of paths which must come late. These entries are handled by
1070 // the toolchain itself after the resource dir is inserted in the right
1071 // search order.
1072 // Do not claim the argument so that the use of the argument does not
1073 // silently go unnoticed on toolchains which do not honour the option.
1074 continue;
1075 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1076 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1077 continue;
1078 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1079 // This is used only by the driver. No need to pass to cc1.
1080 continue;
1081 }
1082
1083 // Not translated, render as usual.
1084 A->claim();
1085 A->render(Args, Output&: CmdArgs);
1086 }
1087
1088 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1089 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1090 // Collect all enabled NVPTX architectures.
1091 std::set<unsigned> ArchIDs;
1092 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1093 const ToolChain *TC = I.second;
1094 for (BoundArch Arch :
1095 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1096 if (IsNVIDIAOffloadArch(A: Arch.Arch))
1097 ArchIDs.insert(x: CudaArchToID(Arch: Arch.Arch));
1098 }
1099 }
1100
1101 if (!ArchIDs.empty()) {
1102 SmallString<128> List;
1103 llvm::raw_svector_ostream OS(List);
1104 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1105 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1106 }
1107 }
1108
1109 Args.addAllArgs(Output&: CmdArgs,
1110 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1111 options::OPT_F, options::OPT_embed_dir_EQ});
1112
1113 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1114
1115 // FIXME: There is a very unfortunate problem here, some troubled
1116 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1117 // really support that we would have to parse and then translate
1118 // those options. :(
1119 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1120 Id1: options::OPT_Xpreprocessor);
1121
1122 // -I- is a deprecated GCC feature, reject it.
1123 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1124 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1125
1126 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1127 // -isysroot to the CC1 invocation.
1128 StringRef sysroot = C.getSysRoot();
1129 if (sysroot != "") {
1130 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1131 CmdArgs.push_back(Elt: "-isysroot");
1132 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1133 }
1134 }
1135
1136 // Parse additional include paths from environment variables.
1137 // FIXME: We should probably sink the logic for handling these from the
1138 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1139 // CPATH - included following the user specified includes (but prior to
1140 // builtin and standard includes).
1141 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1142 // C_INCLUDE_PATH - system includes enabled when compiling C.
1143 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1144 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1145 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1146 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1147 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1148 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1149 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1150
1151 // While adding the include arguments, we also attempt to retrieve the
1152 // arguments of related offloading toolchains or arguments that are specific
1153 // of an offloading programming model.
1154
1155 // Add C++ include arguments, if needed.
1156 if (types::isCXX(Id: Inputs[0].getType())) {
1157 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1158 forAllAssociatedToolChains(
1159 C, JA, RegularToolChain: getToolChain(),
1160 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1161 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1162 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1163 });
1164 }
1165
1166 // If we are compiling for a GPU target we want to override the system headers
1167 // with ones created by the 'libc' project if present.
1168 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1169 // OffloadKind as an argument.
1170 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1171 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1172 Default: true) &&
1173 !Args.hasArg(Ids: options::OPT_nobuiltininc) &&
1174 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1175 // TODO: CUDA / HIP include their own headers for some common functions
1176 // implemented here. We'll need to clean those up so they do not conflict.
1177 SmallString<128> P(D.ResourceDir);
1178 llvm::sys::path::append(path&: P, a: "include");
1179 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1180 CmdArgs.push_back(Elt: "-internal-isystem");
1181 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1182 }
1183
1184 // Add system include arguments for all targets but IAMCU.
1185 if (!IsIAMCU)
1186 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1187 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1188 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1189 });
1190 else {
1191 // For IAMCU add special include arguments.
1192 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1193 }
1194
1195 addMacroPrefixMapArg(D, Args, CmdArgs);
1196 addCoveragePrefixMapArg(D, Args, CmdArgs);
1197
1198 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1199 Ids: options::OPT_fno_file_reproducible);
1200
1201 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1202 CmdArgs.push_back(Elt: "-source-date-epoch");
1203 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1204 }
1205
1206 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1207 Neg: options::OPT_fno_define_target_os_macros);
1208}
1209
1210// FIXME: Move to target hook.
1211static bool isSignedCharDefault(const llvm::Triple &Triple) {
1212 switch (Triple.getArch()) {
1213 default:
1214 return true;
1215
1216 case llvm::Triple::aarch64:
1217 case llvm::Triple::aarch64_32:
1218 case llvm::Triple::aarch64_be:
1219 case llvm::Triple::arm:
1220 case llvm::Triple::armeb:
1221 case llvm::Triple::thumb:
1222 case llvm::Triple::thumbeb:
1223 if (Triple.isOSDarwin() || Triple.isOSWindows())
1224 return true;
1225 return false;
1226
1227 case llvm::Triple::ppc:
1228 case llvm::Triple::ppc64:
1229 if (Triple.isOSDarwin())
1230 return true;
1231 return false;
1232
1233 case llvm::Triple::csky:
1234 case llvm::Triple::hexagon:
1235 case llvm::Triple::msp430:
1236 case llvm::Triple::ppcle:
1237 case llvm::Triple::ppc64le:
1238 case llvm::Triple::riscv32:
1239 case llvm::Triple::riscv64:
1240 case llvm::Triple::riscv32be:
1241 case llvm::Triple::riscv64be:
1242 case llvm::Triple::systemz:
1243 case llvm::Triple::xcore:
1244 case llvm::Triple::xtensa:
1245 return false;
1246 }
1247}
1248
1249static bool hasMultipleInvocations(const llvm::Triple &Triple,
1250 const ArgList &Args) {
1251 // Supported only on Darwin where we invoke the compiler multiple times
1252 // followed by an invocation to lipo.
1253 if (!Triple.isOSDarwin())
1254 return false;
1255 // If more than one "-arch <arch>" is specified, we're targeting multiple
1256 // architectures resulting in a fat binary.
1257 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1258}
1259
1260static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1261 const llvm::Triple &Triple) {
1262 // When enabling remarks, we need to error if:
1263 // * The remark file is specified but we're targeting multiple architectures,
1264 // which means more than one remark file is being generated.
1265 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1266 bool hasExplicitOutputFile =
1267 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1268 if (hasMultipleInvocations && hasExplicitOutputFile) {
1269 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1270 << "-foptimization-record-file";
1271 return false;
1272 }
1273 return true;
1274}
1275
1276static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1277 const llvm::Triple &Triple,
1278 const InputInfo &Input,
1279 const InputInfo &Output, const JobAction &JA) {
1280 StringRef Format = "yaml";
1281 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1282 Format = A->getValue();
1283
1284 CmdArgs.push_back(Elt: "-opt-record-file");
1285
1286 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1287 if (A) {
1288 CmdArgs.push_back(Elt: A->getValue());
1289 } else {
1290 bool hasMultipleArchs =
1291 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1292 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1293
1294 SmallString<128> F;
1295
1296 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1297 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1298 F = FinalOutput->getValue();
1299 } else {
1300 if (Format != "yaml" && // For YAML, keep the original behavior.
1301 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1302 Output.isFilename())
1303 F = Output.getFilename();
1304 }
1305
1306 if (F.empty()) {
1307 // Use the input filename.
1308 F = llvm::sys::path::stem(path: Input.getBaseInput());
1309
1310 // If we're compiling for an offload architecture (i.e. a CUDA device),
1311 // we need to make the file name for the device compilation different
1312 // from the host compilation.
1313 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1314 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1315 llvm::sys::path::replace_extension(path&: F, extension: "");
1316 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1317 NormalizedTriple: Triple.str());
1318 F += "-";
1319 F += JA.getOffloadingArch().ArchName;
1320 }
1321 }
1322
1323 // If we're having more than one "-arch", we should name the files
1324 // differently so that every cc1 invocation writes to a different file.
1325 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1326 // name from the triple.
1327 if (hasMultipleArchs) {
1328 // First, remember the extension.
1329 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1330 // then, remove it.
1331 llvm::sys::path::replace_extension(path&: F, extension: "");
1332 // attach -<arch> to it.
1333 F += "-";
1334 F += Triple.getArchName();
1335 // put back the extension.
1336 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1337 }
1338
1339 SmallString<32> Extension;
1340 Extension += "opt.";
1341 Extension += Format;
1342
1343 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1344 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1345 }
1346
1347 if (const Arg *A =
1348 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1349 CmdArgs.push_back(Elt: "-opt-record-passes");
1350 CmdArgs.push_back(Elt: A->getValue());
1351 }
1352
1353 if (!Format.empty()) {
1354 CmdArgs.push_back(Elt: "-opt-record-format");
1355 CmdArgs.push_back(Elt: Format.data());
1356 }
1357}
1358
1359void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1360 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1361 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1362 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1363
1364 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1365 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1366}
1367
1368namespace {
1369void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1370 const ArgList &Args, ArgStringList &CmdArgs) {
1371 // Select the ABI to use.
1372 // FIXME: Support -meabi.
1373 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1374 const char *ABIName = nullptr;
1375 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1376 ABIName = A->getValue();
1377 else
1378 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1379
1380 CmdArgs.push_back(Elt: "-target-abi");
1381 CmdArgs.push_back(Elt: ABIName);
1382}
1383
1384void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1385 auto StrictAlignIter =
1386 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1387 return Arg == "+strict-align" || Arg == "-strict-align";
1388 });
1389 if (StrictAlignIter != CmdArgs.rend() &&
1390 StringRef(*StrictAlignIter) == "+strict-align")
1391 CmdArgs.push_back(Elt: "-Wunaligned-access");
1392}
1393}
1394
1395static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1396 ArgStringList &CmdArgs, bool isAArch64) {
1397 const llvm::Triple &Triple = TC.getEffectiveTriple();
1398 const Arg *A = isAArch64
1399 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1400 Ids: options::OPT_mbranch_protection_EQ)
1401 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1402 if (!A) {
1403 if (Triple.isOSOpenBSD() && isAArch64) {
1404 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1405 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1406 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1407 }
1408 return;
1409 }
1410
1411 const Driver &D = TC.getDriver();
1412 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1413 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1414 << Triple.getArchName();
1415
1416 StringRef Scope, Key;
1417 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1418
1419 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1420 Scope = A->getValue();
1421 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1422 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1423 << A->getSpelling() << Scope;
1424 Key = "a_key";
1425 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1426 BranchProtectionPAuthLR = false;
1427 GuardedControlStack = false;
1428 } else {
1429 StringRef DiagMsg;
1430 llvm::ARM::ParsedBranchProtection PBP;
1431 bool EnablePAuthLR = false;
1432
1433 // To know if we need to enable PAuth-LR As part of the standard branch
1434 // protection option, it needs to be determined if the feature has been
1435 // activated in the `march` argument. This information is stored within the
1436 // CmdArgs variable and can be found using a search.
1437 if (isAArch64) {
1438 auto isPAuthLR = [](const char *member) {
1439 llvm::AArch64::ExtensionInfo pauthlr_extension =
1440 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1441 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1442 member;
1443 };
1444
1445 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1446 EnablePAuthLR = true;
1447 }
1448 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg, Triple,
1449 EnablePAuthLR))
1450 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1451 << A->getSpelling() << DiagMsg;
1452 if (!isAArch64 && PBP.Key == "b_key")
1453 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1454 << "b-key" << A->getAsString(Args);
1455 Scope = PBP.Scope;
1456 Key = PBP.Key;
1457 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1458 IndirectBranches = PBP.BranchTargetEnforcement;
1459 GuardedControlStack = PBP.GuardedControlStack;
1460 }
1461
1462 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1463 Ids: options::OPT_fno_ptrauth_returns);
1464 bool HasPtrauthReturns =
1465 PtrauthReturnsArg &&
1466 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1467 // GCS is currently untested with ptrauth-returns, but enabling this could be
1468 // allowed in future after testing with a suitable system.
1469 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1470 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1471 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1472 << A->getAsString(Args) << Triple.getTriple();
1473 else if (HasPtrauthReturns)
1474 D.Diag(DiagID: diag::err_drv_incompatible_options)
1475 << A->getAsString(Args) << "-fptrauth-returns";
1476 }
1477
1478 CmdArgs.push_back(
1479 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1480 if (Scope != "none")
1481 CmdArgs.push_back(
1482 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1483 if (BranchProtectionPAuthLR)
1484 CmdArgs.push_back(
1485 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1486 if (IndirectBranches)
1487 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1488
1489 if (GuardedControlStack)
1490 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1491}
1492
1493void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1494 ArgStringList &CmdArgs, bool KernelOrKext) const {
1495 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1496
1497 // Determine floating point ABI from the options & target defaults.
1498 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1499 if (ABI == arm::FloatABI::Soft) {
1500 // Floating point operations and argument passing are soft.
1501 // FIXME: This changes CPP defines, we need -target-soft-float.
1502 CmdArgs.push_back(Elt: "-msoft-float");
1503 CmdArgs.push_back(Elt: "-mfloat-abi");
1504 CmdArgs.push_back(Elt: "soft");
1505 } else if (ABI == arm::FloatABI::SoftFP) {
1506 // Floating point operations are hard, but argument passing is soft.
1507 CmdArgs.push_back(Elt: "-mfloat-abi");
1508 CmdArgs.push_back(Elt: "soft");
1509 } else {
1510 // Floating point operations and argument passing are hard.
1511 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1512 CmdArgs.push_back(Elt: "-mfloat-abi");
1513 CmdArgs.push_back(Elt: "hard");
1514 }
1515
1516 // Forward the -mglobal-merge option for explicit control over the pass.
1517 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1518 Ids: options::OPT_mno_global_merge)) {
1519 CmdArgs.push_back(Elt: "-mllvm");
1520 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1521 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1522 else
1523 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1524 }
1525
1526 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1527 Neg: options::OPT_mno_implicit_float, Default: true))
1528 CmdArgs.push_back(Elt: "-no-implicit-float");
1529
1530 if (Args.getLastArg(Ids: options::OPT_mcmse))
1531 CmdArgs.push_back(Elt: "-mcmse");
1532
1533 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1534
1535 // Enable/disable return address signing and indirect branch targets.
1536 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1537
1538 AddUnalignedAccessWarning(CmdArgs);
1539}
1540
1541void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1542 ArgStringList &CmdArgs) const {
1543 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1544 if (Arg *A = Args.getLastArg(Ids: options::OPT_mxnack, Ids: options::OPT_mno_xnack))
1545 A->render(Args, Output&: CmdArgs);
1546 if (Arg *A = Args.getLastArg(Ids: options::OPT_msramecc, Ids: options::OPT_mno_sramecc))
1547 A->render(Args, Output&: CmdArgs);
1548}
1549
1550void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1551 const ArgList &Args, bool KernelOrKext,
1552 ArgStringList &CmdArgs) const {
1553 const ToolChain &TC = getToolChain();
1554
1555 // Add the target features
1556 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1557
1558 // Add target specific flags.
1559 switch (TC.getArch()) {
1560 default:
1561 break;
1562
1563 case llvm::Triple::arm:
1564 case llvm::Triple::armeb:
1565 case llvm::Triple::thumb:
1566 case llvm::Triple::thumbeb:
1567 // Use the effective triple, which takes into account the deployment target.
1568 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1569 break;
1570
1571 case llvm::Triple::aarch64:
1572 case llvm::Triple::aarch64_32:
1573 case llvm::Triple::aarch64_be:
1574 AddAArch64TargetArgs(Args, CmdArgs);
1575 break;
1576
1577 case llvm::Triple::amdgpu:
1578 AddAMDGPUTargetArgs(Args, CmdArgs);
1579 break;
1580
1581 case llvm::Triple::loongarch32:
1582 case llvm::Triple::loongarch64:
1583 AddLoongArchTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::mips:
1587 case llvm::Triple::mipsel:
1588 case llvm::Triple::mips64:
1589 case llvm::Triple::mips64el:
1590 AddMIPSTargetArgs(Args, CmdArgs);
1591 break;
1592
1593 case llvm::Triple::ppc:
1594 case llvm::Triple::ppcle:
1595 case llvm::Triple::ppc64:
1596 case llvm::Triple::ppc64le:
1597 AddPPCTargetArgs(Args, CmdArgs);
1598 break;
1599
1600 case llvm::Triple::riscv32:
1601 case llvm::Triple::riscv64:
1602 case llvm::Triple::riscv32be:
1603 case llvm::Triple::riscv64be:
1604 AddRISCVTargetArgs(Args, CmdArgs);
1605 break;
1606
1607 case llvm::Triple::sparc:
1608 case llvm::Triple::sparcel:
1609 case llvm::Triple::sparcv9:
1610 AddSparcTargetArgs(Args, CmdArgs);
1611 break;
1612
1613 case llvm::Triple::systemz:
1614 AddSystemZTargetArgs(Args, CmdArgs);
1615 break;
1616
1617 case llvm::Triple::x86:
1618 case llvm::Triple::x86_64:
1619 AddX86TargetArgs(Args, CmdArgs);
1620 break;
1621
1622 case llvm::Triple::lanai:
1623 AddLanaiTargetArgs(Args, CmdArgs);
1624 break;
1625
1626 case llvm::Triple::hexagon:
1627 AddHexagonTargetArgs(Args, CmdArgs);
1628 break;
1629
1630 case llvm::Triple::wasm32:
1631 case llvm::Triple::wasm64:
1632 AddWebAssemblyTargetArgs(Args, CmdArgs);
1633 break;
1634
1635 case llvm::Triple::ve:
1636 AddVETargetArgs(Args, CmdArgs);
1637 break;
1638 }
1639}
1640
1641namespace {
1642void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1643 ArgStringList &CmdArgs) {
1644 const char *ABIName = nullptr;
1645 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1646 ABIName = A->getValue();
1647 else if (Triple.isOSDarwin())
1648 ABIName = "darwinpcs";
1649 // TODO: we probably want to have some target hook here.
1650 else if (Triple.isOSLinux() &&
1651 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1652 ABIName = "pauthtest";
1653 else
1654 ABIName = "aapcs";
1655
1656 CmdArgs.push_back(Elt: "-target-abi");
1657 CmdArgs.push_back(Elt: ABIName);
1658}
1659}
1660
1661void Clang::AddAArch64TargetArgs(const ArgList &Args,
1662 ArgStringList &CmdArgs) const {
1663 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1664
1665 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1666 Args.hasArg(Ids: options::OPT_mkernel) ||
1667 Args.hasArg(Ids: options::OPT_fapple_kext))
1668 CmdArgs.push_back(Elt: "-disable-red-zone");
1669
1670 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1671 Neg: options::OPT_mno_implicit_float, Default: true))
1672 CmdArgs.push_back(Elt: "-no-implicit-float");
1673
1674 RenderAArch64ABI(Triple, Args, CmdArgs);
1675
1676 // Forward the -mglobal-merge option for explicit control over the pass.
1677 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1678 Ids: options::OPT_mno_global_merge)) {
1679 CmdArgs.push_back(Elt: "-mllvm");
1680 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1681 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1682 else
1683 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1684 }
1685
1686 // Handle -msve_vector_bits=<bits>
1687 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1688 StringRef VScaleMax) {
1689 StringRef Val = A->getValue();
1690 const Driver &D = getToolChain().getDriver();
1691 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1692 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1693 Val == "1024+" || Val == "2048+") {
1694 unsigned Bits = 0;
1695 if (!Val.consume_back(Suffix: "+")) {
1696 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1697 (void)Invalid;
1698 assert(!Invalid && "Failed to parse value");
1699 CmdArgs.push_back(
1700 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1701 }
1702
1703 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1704 (void)Invalid;
1705 assert(!Invalid && "Failed to parse value");
1706
1707 CmdArgs.push_back(
1708 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1709 } else if (Val == "scalable") {
1710 // Silently drop requests for vector-length agnostic code as it's implied.
1711 } else {
1712 // Handle the unsupported values passed to msve-vector-bits.
1713 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1714 << A->getSpelling() << Val;
1715 }
1716 };
1717 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1718 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1719 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1720 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1721
1722 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1723
1724 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1725 CmdArgs.push_back(Elt: "-tune-cpu");
1726 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1727 }
1728
1729 AddUnalignedAccessWarning(CmdArgs);
1730
1731 if (Triple.isOSDarwin() ||
1732 (Triple.isOSLinux() &&
1733 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1734 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1735 Neg: options::OPT_fno_ptrauth_intrinsics);
1736 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1737 Neg: options::OPT_fno_ptrauth_calls);
1738 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1739 Neg: options::OPT_fno_ptrauth_returns);
1740 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1741 Neg: options::OPT_fno_ptrauth_auth_traps);
1742 Args.addOptInFlag(
1743 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1744 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1745 Args.addOptInFlag(
1746 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1747 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1748 Args.addOptInFlag(
1749 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1750 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1751 Args.addOptInFlag(
1752 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1753 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1754 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1755 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1756 }
1757 if (Triple.isOSLinux() &&
1758 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1759 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1760 Neg: options::OPT_fno_ptrauth_init_fini);
1761 Args.addOptInFlag(
1762 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1763 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1764 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1765 Neg: options::OPT_fno_ptrauth_elf_got);
1766 }
1767 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1768 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1769
1770 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1771 Neg: options::OPT_fno_ptrauth_objc_isa);
1772 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1773 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1774 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1775 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1776
1777 // Enable/disable return address signing and indirect branch targets.
1778 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1779}
1780
1781void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1782 ArgStringList &CmdArgs) const {
1783 const llvm::Triple &Triple = getToolChain().getTriple();
1784
1785 CmdArgs.push_back(Elt: "-target-abi");
1786 CmdArgs.push_back(
1787 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1788 .data());
1789
1790 // Handle -mtune.
1791 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1792 std::string TuneCPU = A->getValue();
1793 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1794 CmdArgs.push_back(Elt: "-tune-cpu");
1795 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1796 }
1797
1798 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1799 Ids: options::OPT_mno_annotate_tablejump)) {
1800 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1801 CmdArgs.push_back(Elt: "-mllvm");
1802 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1803 }
1804 }
1805}
1806
1807void Clang::AddMIPSTargetArgs(const ArgList &Args,
1808 ArgStringList &CmdArgs) const {
1809 const Driver &D = getToolChain().getDriver();
1810 StringRef CPUName;
1811 StringRef ABIName;
1812 const llvm::Triple &Triple = getToolChain().getTriple();
1813 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1814
1815 CmdArgs.push_back(Elt: "-target-abi");
1816 CmdArgs.push_back(Elt: ABIName.data());
1817
1818 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1819 if (ABI == mips::FloatABI::Soft) {
1820 // Floating point operations and argument passing are soft.
1821 CmdArgs.push_back(Elt: "-msoft-float");
1822 CmdArgs.push_back(Elt: "-mfloat-abi");
1823 CmdArgs.push_back(Elt: "soft");
1824 } else {
1825 // Floating point operations and argument passing are hard.
1826 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1827 CmdArgs.push_back(Elt: "-mfloat-abi");
1828 CmdArgs.push_back(Elt: "hard");
1829 }
1830
1831 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1832 Ids: options::OPT_mno_ldc1_sdc1)) {
1833 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1834 CmdArgs.push_back(Elt: "-mllvm");
1835 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1836 }
1837 }
1838
1839 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1840 Ids: options::OPT_mno_check_zero_division)) {
1841 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1842 CmdArgs.push_back(Elt: "-mllvm");
1843 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1844 }
1845 }
1846
1847 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1848 CmdArgs.push_back(Elt: "-mllvm");
1849 CmdArgs.push_back(Elt: "-mfix4300");
1850 }
1851
1852 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1853 StringRef v = A->getValue();
1854 CmdArgs.push_back(Elt: "-mllvm");
1855 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1856 A->claim();
1857 }
1858
1859 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1860 Arg *ABICalls =
1861 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1862
1863 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1864 // -mgpopt is the default for static, -fno-pic environments but these two
1865 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1866 // the only case where -mllvm -mgpopt is passed.
1867 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1868 // passed explicitly when compiling something with -mabicalls
1869 // (implictly) in affect. Currently the warning is in the backend.
1870 //
1871 // When the ABI in use is N64, we also need to determine the PIC mode that
1872 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1873 bool NoABICalls =
1874 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1875
1876 llvm::Reloc::Model RelocationModel;
1877 unsigned PICLevel;
1878 bool IsPIE;
1879 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1880 ParsePICArgs(ToolChain: getToolChain(), Args);
1881
1882 NoABICalls = NoABICalls ||
1883 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1884
1885 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1886 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1887 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1888 CmdArgs.push_back(Elt: "-mllvm");
1889 CmdArgs.push_back(Elt: "-mgpopt");
1890
1891 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1892 Ids: options::OPT_mno_local_sdata);
1893 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1894 Ids: options::OPT_mno_extern_sdata);
1895 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1896 Ids: options::OPT_mno_embedded_data);
1897 if (LocalSData) {
1898 CmdArgs.push_back(Elt: "-mllvm");
1899 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1900 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1901 } else {
1902 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1903 }
1904 LocalSData->claim();
1905 }
1906
1907 if (ExternSData) {
1908 CmdArgs.push_back(Elt: "-mllvm");
1909 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1910 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1911 } else {
1912 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1913 }
1914 ExternSData->claim();
1915 }
1916
1917 if (EmbeddedData) {
1918 CmdArgs.push_back(Elt: "-mllvm");
1919 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1920 CmdArgs.push_back(Elt: "-membedded-data=1");
1921 } else {
1922 CmdArgs.push_back(Elt: "-membedded-data=0");
1923 }
1924 EmbeddedData->claim();
1925 }
1926
1927 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1928 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1929
1930 if (GPOpt)
1931 GPOpt->claim();
1932
1933 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1934 StringRef Val = StringRef(A->getValue());
1935 if (mips::hasCompactBranches(CPU&: CPUName)) {
1936 if (Val == "never" || Val == "always" || Val == "optimal") {
1937 CmdArgs.push_back(Elt: "-mllvm");
1938 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1939 } else
1940 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1941 << A->getSpelling() << Val;
1942 } else
1943 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1944 }
1945
1946 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1947 Ids: options::OPT_mno_relax_pic_calls)) {
1948 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1949 CmdArgs.push_back(Elt: "-mllvm");
1950 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1951 }
1952 }
1953}
1954
1955void Clang::AddPPCTargetArgs(const ArgList &Args,
1956 ArgStringList &CmdArgs) const {
1957 const Driver &D = getToolChain().getDriver();
1958 const llvm::Triple &T = getToolChain().getTriple();
1959 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1960 CmdArgs.push_back(Elt: "-tune-cpu");
1961 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1962 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
1963 }
1964
1965 // Select the ABI to use.
1966 const char *ABIName = nullptr;
1967 if (T.isOSBinFormatELF()) {
1968 switch (getToolChain().getArch()) {
1969 case llvm::Triple::ppc64: {
1970 if (T.isPPC64ELFv2ABI())
1971 ABIName = "elfv2";
1972 else
1973 ABIName = "elfv1";
1974 break;
1975 }
1976 case llvm::Triple::ppc64le:
1977 ABIName = "elfv2";
1978 break;
1979 default:
1980 break;
1981 }
1982 }
1983
1984 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1985 bool VecExtabi = false;
1986 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1987 StringRef V = A->getValue();
1988 if (V == "ieeelongdouble") {
1989 IEEELongDouble = true;
1990 A->claim();
1991 } else if (V == "ibmlongdouble") {
1992 IEEELongDouble = false;
1993 A->claim();
1994 } else if (V == "vec-default") {
1995 VecExtabi = false;
1996 A->claim();
1997 } else if (V == "vec-extabi") {
1998 VecExtabi = true;
1999 A->claim();
2000 } else if (V == "elfv1") {
2001 ABIName = "elfv1";
2002 A->claim();
2003 } else if (V == "elfv2") {
2004 ABIName = "elfv2";
2005 A->claim();
2006 } else if (V != "altivec")
2007 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2008 // the option if given as we don't have backend support for any targets
2009 // that don't use the altivec abi.
2010 ABIName = A->getValue();
2011 }
2012 if (IEEELongDouble)
2013 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
2014 if (VecExtabi) {
2015 if (!T.isOSAIX())
2016 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2017 << "-mabi=vec-extabi" << T.str();
2018 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
2019 }
2020
2021 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
2022 CmdArgs.push_back(Elt: "-disable-red-zone");
2023
2024 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2025 if (FloatABI == ppc::FloatABI::Soft) {
2026 // Floating point operations and argument passing are soft.
2027 CmdArgs.push_back(Elt: "-msoft-float");
2028 CmdArgs.push_back(Elt: "-mfloat-abi");
2029 CmdArgs.push_back(Elt: "soft");
2030 } else {
2031 // Floating point operations and argument passing are hard.
2032 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2033 CmdArgs.push_back(Elt: "-mfloat-abi");
2034 CmdArgs.push_back(Elt: "hard");
2035 }
2036
2037 if (ABIName) {
2038 CmdArgs.push_back(Elt: "-target-abi");
2039 CmdArgs.push_back(Elt: ABIName);
2040 }
2041}
2042
2043void Clang::AddRISCVTargetArgs(const ArgList &Args,
2044 ArgStringList &CmdArgs) const {
2045 const llvm::Triple &Triple = getToolChain().getTriple();
2046 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2047
2048 CmdArgs.push_back(Elt: "-target-abi");
2049 CmdArgs.push_back(Elt: ABIName.data());
2050
2051 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2052 CmdArgs.push_back(Elt: "-msmall-data-limit");
2053 CmdArgs.push_back(Elt: A->getValue());
2054 }
2055
2056 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2057 Neg: options::OPT_mno_implicit_float, Default: true))
2058 CmdArgs.push_back(Elt: "-no-implicit-float");
2059
2060 auto TuneCPU = riscv::getRISCVTuneCPU(D: getToolChain().getDriver(), Args);
2061 if (!TuneCPU)
2062 return;
2063 if (!TuneCPU->empty()) {
2064 CmdArgs.push_back(Elt: "-tune-cpu");
2065 if (*TuneCPU == "native")
2066 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2067 else
2068 // TuneCPU might or might not be the original -mtune string, so we
2069 // have to create a new copy here.
2070 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
2071 }
2072
2073 // Handle -mrvv-vector-bits=<bits>
2074 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2075 StringRef Val = A->getValue();
2076 const Driver &D = getToolChain().getDriver();
2077
2078 // Get minimum VLen from march.
2079 unsigned MinVLen = 0;
2080 std::string Arch = riscv::getRISCVArch(Args, Triple);
2081 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2082 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2083 // Ignore parsing error.
2084 if (!errorToBool(Err: ISAInfo.takeError()))
2085 MinVLen = (*ISAInfo)->getMinVLen();
2086
2087 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2088 // as integer as long as we have a MinVLen.
2089 unsigned Bits = 0;
2090 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2091 Bits = MinVLen;
2092 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2093 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2094 // at least MinVLen.
2095 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2096 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2097 Bits = 0;
2098 }
2099
2100 // If we got a valid value try to use it.
2101 if (Bits != 0) {
2102 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2103 CmdArgs.push_back(
2104 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2105 CmdArgs.push_back(
2106 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2107 } else if (Val != "scalable") {
2108 // Handle the unsupported values passed to mrvv-vector-bits.
2109 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2110 << A->getSpelling() << Val;
2111 }
2112 }
2113}
2114
2115void Clang::AddSparcTargetArgs(const ArgList &Args,
2116 ArgStringList &CmdArgs) const {
2117 sparc::FloatABI FloatABI =
2118 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2119
2120 if (FloatABI == sparc::FloatABI::Soft) {
2121 // Floating point operations and argument passing are soft.
2122 CmdArgs.push_back(Elt: "-msoft-float");
2123 CmdArgs.push_back(Elt: "-mfloat-abi");
2124 CmdArgs.push_back(Elt: "soft");
2125 } else {
2126 // Floating point operations and argument passing are hard.
2127 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2128 CmdArgs.push_back(Elt: "-mfloat-abi");
2129 CmdArgs.push_back(Elt: "hard");
2130 }
2131
2132 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2133 StringRef Name = A->getValue();
2134 std::string TuneCPU;
2135 if (Name == "native")
2136 TuneCPU = std::string(llvm::sys::getHostCPUName());
2137 else
2138 TuneCPU = std::string(Name);
2139
2140 CmdArgs.push_back(Elt: "-tune-cpu");
2141 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2142 }
2143}
2144
2145void Clang::AddSystemZTargetArgs(const ArgList &Args,
2146 ArgStringList &CmdArgs) const {
2147 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2148 CmdArgs.push_back(Elt: "-tune-cpu");
2149 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2150 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2151 else
2152 CmdArgs.push_back(Elt: A->getValue());
2153 }
2154
2155 bool HasBackchain =
2156 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2157 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2158 Neg: options::OPT_mno_packed_stack, Default: false);
2159 systemz::FloatABI FloatABI =
2160 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2161 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2162
2163 // Only hard float ABI (-mhard-float) is supported on z/OS.
2164 const Driver &D = getToolChain().getDriver();
2165 const llvm::Triple &Triple = getToolChain().getTriple();
2166 if (HasSoftFloat && Triple.isOSzOS()) {
2167 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2168 << "-msoft-float" << Triple.str();
2169 }
2170 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2171 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2172 << "-mpacked-stack -mbackchain -mhard-float";
2173 }
2174 if (HasBackchain)
2175 CmdArgs.push_back(Elt: "-mbackchain");
2176 if (HasPackedStack)
2177 CmdArgs.push_back(Elt: "-mpacked-stack");
2178 if (HasSoftFloat) {
2179 // Floating point operations and argument passing are soft.
2180 CmdArgs.push_back(Elt: "-msoft-float");
2181 CmdArgs.push_back(Elt: "-mfloat-abi");
2182 CmdArgs.push_back(Elt: "soft");
2183 }
2184
2185 if (Triple.isOSzOS())
2186 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mzos_ppa1_name,
2187 Ids: options::OPT_mno_zos_ppa1_name);
2188}
2189
2190void Clang::AddX86TargetArgs(const ArgList &Args,
2191 ArgStringList &CmdArgs) const {
2192 const Driver &D = getToolChain().getDriver();
2193 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2194
2195 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2196 Args.hasArg(Ids: options::OPT_mkernel) ||
2197 Args.hasArg(Ids: options::OPT_fapple_kext))
2198 CmdArgs.push_back(Elt: "-disable-red-zone");
2199
2200 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2201 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2202 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2203
2204 // Default to avoid implicit floating-point for kernel/kext code, but allow
2205 // that to be overridden with -mno-soft-float.
2206 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2207 Args.hasArg(Ids: options::OPT_fapple_kext));
2208 if (Arg *A = Args.getLastArg(
2209 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2210 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2211 const Option &O = A->getOption();
2212 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2213 O.matches(ID: options::OPT_msoft_float));
2214 }
2215 if (NoImplicitFloat)
2216 CmdArgs.push_back(Elt: "-no-implicit-float");
2217
2218 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2219 StringRef Value = A->getValue();
2220 if (Value == "intel" || Value == "att") {
2221 CmdArgs.push_back(Elt: "-mllvm");
2222 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2223 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2224 } else {
2225 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2226 << A->getSpelling() << Value;
2227 }
2228 } else if (D.IsCLMode()) {
2229 CmdArgs.push_back(Elt: "-mllvm");
2230 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2231 }
2232
2233 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2234 Ids: options::OPT_mno_skip_rax_setup))
2235 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2236 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2237
2238 // Set flags to support MCU ABI.
2239 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2240 CmdArgs.push_back(Elt: "-mfloat-abi");
2241 CmdArgs.push_back(Elt: "soft");
2242 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2243 }
2244
2245 // Handle -mtune.
2246
2247 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2248 std::string TuneCPU;
2249 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2250 TuneCPU = "generic";
2251
2252 // Override based on -mtune.
2253 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2254 StringRef Name = A->getValue();
2255
2256 if (Name == "native") {
2257 Name = llvm::sys::getHostCPUName();
2258 if (!Name.empty())
2259 TuneCPU = std::string(Name);
2260 } else
2261 TuneCPU = std::string(Name);
2262 }
2263
2264 if (!TuneCPU.empty()) {
2265 CmdArgs.push_back(Elt: "-tune-cpu");
2266 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2267 }
2268}
2269
2270static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2271 size_t Index = Option.find(C: Delimiter);
2272 if (Index != StringRef::npos)
2273 Option = Option.substr(Start: 0, N: Index);
2274 return Option;
2275}
2276
2277static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2278 Opt = getOptionName(Option: Opt);
2279 if (CmdArgs.size() < 2)
2280 return;
2281
2282 for (auto It = std::next(x: CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2283 StringRef Option = *It;
2284 if (!Option.starts_with(Prefix: Opt))
2285 continue;
2286 Option = getOptionName(Option);
2287 if (Option != Opt)
2288 continue;
2289 if (StringRef(*(It - 1)) != "-mllvm")
2290 continue;
2291
2292 It = CmdArgs.erase(CI: It);
2293 CmdArgs.erase(CI: It - 1);
2294 return;
2295 }
2296}
2297
2298static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2299 checkAndRemoveLLVMArg(CmdArgs, Opt: A);
2300 CmdArgs.push_back(Elt: "-mllvm");
2301 CmdArgs.push_back(Elt: A);
2302}
2303
2304static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2305 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2306 StringRef Option = *It;
2307 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2308 It = CmdArgs.erase(CI: It);
2309 Ie = CmdArgs.end();
2310 } else {
2311 ++It;
2312 }
2313 }
2314
2315 CmdArgs.push_back(Elt: "-menable-no-infs");
2316 CmdArgs.push_back(Elt: "-menable-no-nans");
2317 CmdArgs.push_back(Elt: "-fapprox-func");
2318 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
2319 CmdArgs.push_back(Elt: "-fno-signed-zeros");
2320 CmdArgs.push_back(Elt: "-mreassociate");
2321 CmdArgs.push_back(Elt: "-freciprocal-math");
2322 CmdArgs.push_back(Elt: "-ffp-contract=fast");
2323 CmdArgs.push_back(Elt: "-ffast-math");
2324 CmdArgs.push_back(Elt: "-ffinite-math-only");
2325 CmdArgs.push_back(Elt: "-D__FAST_MATH__");
2326 pushBackLLVMArg(CmdArgs, A: "-fast-math=true");
2327}
2328
2329static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2330 ArgStringList &CmdArgs) {
2331 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2332 bool HasHVX = HvxVerOpt.has_value();
2333 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2334 if (!Args.hasArg(Ids: options::OPT_mhexagon_hvx, Ids: options::OPT_mhexagon_hvx_EQ,
2335 Ids: options::OPT_mhexagon_hvx_ieee_fp) ||
2336 !HasHVX)
2337 return;
2338 unsigned HvxVerNum = 0;
2339 if (StringRef(HvxVer).drop_front(N: 1).getAsInteger(Radix: 10, Result&: HvxVerNum))
2340 HvxVerNum = 0;
2341
2342 if (Arg *A = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2343 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2344 Ids: options::OPT_mhexagon_hvx_ieee_fp)) {
2345 if (HvxVerNum >= 79) {
2346 if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2347 const char *Mode =
2348 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2349 .Case(S: "strict-ieee", Value: "-hexagon-qfloat-mode=strict-ieee")
2350 .Case(S: "ieee", Value: "-hexagon-qfloat-mode=ieee")
2351 .Case(S: "lossy", Value: "-hexagon-qfloat-mode=lossy")
2352 .Case(S: "legacy", Value: "-hexagon-qfloat-mode=legacy")
2353 .Default(Value: nullptr);
2354 if (!Mode) {
2355 D.Diag(DiagID: diag::err_drv_invalid_value)
2356 << A->getAsString(Args) << A->getValue();
2357 return;
2358 }
2359 pushBackLLVMArg(CmdArgs, A: Mode);
2360 if (strcmp(s1: Mode, s2: "-hexagon-qfloat-mode=lossy") == 0)
2361 addQFloatLossyFastMathArgs(CmdArgs);
2362 } else if (A->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat)) {
2363 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=lossy");
2364 addQFloatLossyFastMathArgs(CmdArgs);
2365 } else {
2366 pushBackLLVMArg(CmdArgs, A: "-hexagon-qfloat-mode=ieee");
2367 }
2368 } else {
2369 if (Arg *QFloatArg = Args.getLastArg(Ids: options::OPT_mhexagon_hvx_qfloat,
2370 Ids: options::OPT_mhexagon_hvx_qfloat_EQ,
2371 Ids: options::OPT_mno_hexagon_hvx_qfloat);
2372 QFloatArg &&
2373 QFloatArg->getOption().matches(ID: options::OPT_mhexagon_hvx_qfloat_EQ)) {
2374 D.Diag(DiagID: diag::warn_drv_unsupported_option_part_for_target)
2375 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2376 << (std::string("HVX ") + HvxVer +
2377 "; falling back to legacy qfloat mode");
2378 }
2379 }
2380 }
2381}
2382
2383void Clang::AddHexagonTargetArgs(const ArgList &Args,
2384 ArgStringList &CmdArgs) const {
2385 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2386 CmdArgs.push_back(Elt: "-Wreturn-type");
2387
2388 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2389 CmdArgs.push_back(Elt: "-mllvm");
2390 CmdArgs.push_back(
2391 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2392 }
2393
2394 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2395 CmdArgs.push_back(Elt: "-fshort-enums");
2396 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2397 CmdArgs.push_back(Elt: "-mllvm");
2398 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2399 }
2400 CmdArgs.push_back(Elt: "-mllvm");
2401 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2402
2403 addQFloatBackendArg(D: getToolChain().getDriver(), Args, CmdArgs);
2404}
2405
2406void Clang::AddLanaiTargetArgs(const ArgList &Args,
2407 ArgStringList &CmdArgs) const {
2408 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2409 StringRef CPUName = A->getValue();
2410
2411 CmdArgs.push_back(Elt: "-target-cpu");
2412 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2413 }
2414 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2415 StringRef Value = A->getValue();
2416 // Only support mregparm=4 to support old usage. Report error for all other
2417 // cases.
2418 int Mregparm;
2419 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2420 if (Mregparm != 4) {
2421 getToolChain().getDriver().Diag(
2422 DiagID: diag::err_drv_unsupported_option_argument)
2423 << A->getSpelling() << Value;
2424 }
2425 }
2426 }
2427}
2428
2429void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2430 ArgStringList &CmdArgs) const {
2431 // Default to "hidden" visibility.
2432 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2433 Ids: options::OPT_fvisibility_ms_compat))
2434 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2435}
2436
2437void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2438 // Floating point operations and argument passing are hard.
2439 CmdArgs.push_back(Elt: "-mfloat-abi");
2440 CmdArgs.push_back(Elt: "hard");
2441}
2442
2443void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2444 StringRef Target, const InputInfo &Output,
2445 const InputInfo &Input, const ArgList &Args) const {
2446 // If this is a dry run, do not create the compilation database file.
2447 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2448 return;
2449
2450 using llvm::yaml::escape;
2451 const Driver &D = getToolChain().getDriver();
2452
2453 if (!CompilationDatabase) {
2454 std::error_code EC;
2455 auto File = std::make_unique<llvm::raw_fd_ostream>(
2456 args&: Filename, args&: EC,
2457 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2458 if (EC) {
2459 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2460 << EC.message();
2461 return;
2462 }
2463 CompilationDatabase = std::move(File);
2464 }
2465 auto &CDB = *CompilationDatabase;
2466 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2467 if (!CWD)
2468 CWD = ".";
2469 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2470 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2471 if (Output.isFilename())
2472 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2473 CDB << ", \"arguments\": [\"" << escape(Input: D.DriverExecutable) << "\"";
2474 SmallString<128> Buf;
2475 Buf = "-x";
2476 Buf += types::getTypeName(Id: Input.getType());
2477 CDB << ", \"" << escape(Input: Buf) << "\"";
2478 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2479 Buf = "--sysroot=";
2480 Buf += D.SysRoot;
2481 CDB << ", \"" << escape(Input: Buf) << "\"";
2482 }
2483 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2484 if (Output.isFilename())
2485 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2486 for (auto &A: Args) {
2487 auto &O = A->getOption();
2488 // Skip language selection, which is positional.
2489 if (O.getID() == options::OPT_x)
2490 continue;
2491 // Skip writing dependency output and the compilation database itself.
2492 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2493 continue;
2494 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2495 continue;
2496 // Skip inputs.
2497 if (O.getKind() == Option::InputClass)
2498 continue;
2499 // Skip output.
2500 if (O.getID() == options::OPT_o)
2501 continue;
2502 // All other arguments are quoted and appended.
2503 ArgStringList ASL;
2504 A->render(Args, Output&: ASL);
2505 for (auto &it: ASL)
2506 CDB << ", \"" << escape(Input: it) << "\"";
2507 }
2508 Buf = "--target=";
2509 Buf += Target;
2510 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2511}
2512
2513void Clang::DumpCompilationDatabaseFragmentToDir(
2514 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2515 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2516 // If this is a dry run, do not create the compilation database file.
2517 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2518 return;
2519
2520 if (CompilationDatabase)
2521 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2522
2523 SmallString<256> Path = Dir;
2524 const auto &Driver = C.getDriver();
2525 Driver.getVFS().makeAbsolute(Path);
2526 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2527 if (Err) {
2528 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2529 return;
2530 }
2531
2532 llvm::sys::path::append(
2533 path&: Path,
2534 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2535 int FD;
2536 SmallString<256> TempPath;
2537 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2538 Flags: llvm::sys::fs::OF_Text);
2539 if (Err) {
2540 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2541 return;
2542 }
2543 CompilationDatabase =
2544 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2545 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2546}
2547
2548static bool CheckARMImplicitITArg(StringRef Value) {
2549 return Value == "always" || Value == "never" || Value == "arm" ||
2550 Value == "thumb";
2551}
2552
2553static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2554 StringRef Value) {
2555 CmdArgs.push_back(Elt: "-mllvm");
2556 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2557}
2558
2559static void CollectArgsForIntegratedAssembler(Compilation &C,
2560 const ArgList &Args,
2561 ArgStringList &CmdArgs,
2562 const Driver &D) {
2563 // Default to -mno-relax-all.
2564 //
2565 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2566 // cannot be done by assembler branch relaxation as it needs a free temporary
2567 // register. Because of this, branch relaxation is handled by a MachineIR pass
2568 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2569 // MachineIR branch relaxation inaccurate and it will miss cases where an
2570 // indirect branch is necessary.
2571 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2572 Neg: options::OPT_mno_relax_all);
2573
2574 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mincremental_linker_compatible,
2575 Ids: options::OPT_mno_incremental_linker_compatible);
2576
2577 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2578
2579 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2580 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2581
2582 // If you add more args here, also add them to the block below that
2583 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2584
2585 // When passing -I arguments to the assembler we sometimes need to
2586 // unconditionally take the next argument. For example, when parsing
2587 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2588 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2589 // arg after parsing the '-I' arg.
2590 bool TakeNextArg = false;
2591
2592 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2593 bool IsELF = Triple.isOSBinFormatELF();
2594 bool Crel = false, ExperimentalCrel = false;
2595 StringRef RelocSectionSym;
2596 bool SFrame = false, ExperimentalSFrame = false;
2597 bool ImplicitMapSyms = false;
2598 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2599 bool UseNoExecStack = false;
2600 bool Msa = false;
2601 const char *MipsTargetFeature = nullptr;
2602 llvm::SmallVector<const char *> SparcTargetFeatures;
2603 StringRef ImplicitIt;
2604 for (const Arg *A :
2605 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2606 Ids: options::OPT_mimplicit_it_EQ)) {
2607 A->claim();
2608
2609 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2610 switch (C.getDefaultToolChain().getArch()) {
2611 case llvm::Triple::arm:
2612 case llvm::Triple::armeb:
2613 case llvm::Triple::thumb:
2614 case llvm::Triple::thumbeb:
2615 // Only store the value; the last value set takes effect.
2616 ImplicitIt = A->getValue();
2617 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2618 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2619 << A->getSpelling() << ImplicitIt;
2620 continue;
2621 default:
2622 break;
2623 }
2624 }
2625
2626 for (StringRef Value : A->getValues()) {
2627 if (TakeNextArg) {
2628 CmdArgs.push_back(Elt: Value.data());
2629 TakeNextArg = false;
2630 continue;
2631 }
2632
2633 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2634 Value == "-mbig-obj")
2635 continue; // LLVM handles bigobj automatically
2636
2637 auto Equal = Value.split(Separator: '=');
2638 auto checkArg = [&](bool ValidTarget,
2639 std::initializer_list<const char *> Set) {
2640 if (!ValidTarget) {
2641 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2642 << (Twine("-Wa,") + Equal.first + "=").str()
2643 << Triple.getTriple();
2644 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2645 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2646 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2647 }
2648 };
2649 switch (C.getDefaultToolChain().getArch()) {
2650 default:
2651 break;
2652 case llvm::Triple::x86:
2653 case llvm::Triple::x86_64:
2654 if (Equal.first == "-mrelax-relocations" ||
2655 Equal.first == "--mrelax-relocations") {
2656 UseRelaxRelocations = Equal.second == "yes";
2657 checkArg(IsELF, {"yes", "no"});
2658 continue;
2659 }
2660 if (Value == "-msse2avx") {
2661 CmdArgs.push_back(Elt: "-msse2avx");
2662 continue;
2663 }
2664 break;
2665 case llvm::Triple::wasm32:
2666 case llvm::Triple::wasm64:
2667 if (Value == "--no-type-check") {
2668 CmdArgs.push_back(Elt: "-mno-type-check");
2669 continue;
2670 }
2671 break;
2672 case llvm::Triple::thumb:
2673 case llvm::Triple::thumbeb:
2674 case llvm::Triple::arm:
2675 case llvm::Triple::armeb:
2676 if (Equal.first == "-mimplicit-it") {
2677 // Only store the value; the last value set takes effect.
2678 ImplicitIt = Equal.second;
2679 checkArg(true, {"always", "never", "arm", "thumb"});
2680 continue;
2681 }
2682 if (Value == "-mthumb")
2683 // -mthumb has already been processed in ComputeLLVMTriple()
2684 // recognize but skip over here.
2685 continue;
2686 break;
2687 case llvm::Triple::aarch64:
2688 case llvm::Triple::aarch64_be:
2689 case llvm::Triple::aarch64_32:
2690 if (Equal.first == "-mmapsyms") {
2691 ImplicitMapSyms = Equal.second == "implicit";
2692 checkArg(IsELF, {"default", "implicit"});
2693 continue;
2694 }
2695 break;
2696 case llvm::Triple::mips:
2697 case llvm::Triple::mipsel:
2698 case llvm::Triple::mips64:
2699 case llvm::Triple::mips64el:
2700 if (Value == "--trap") {
2701 CmdArgs.push_back(Elt: "-target-feature");
2702 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2703 continue;
2704 }
2705 if (Value == "--break") {
2706 CmdArgs.push_back(Elt: "-target-feature");
2707 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2708 continue;
2709 }
2710 if (Value.starts_with(Prefix: "-msoft-float")) {
2711 CmdArgs.push_back(Elt: "-target-feature");
2712 CmdArgs.push_back(Elt: "+soft-float");
2713 continue;
2714 }
2715 if (Value.starts_with(Prefix: "-mhard-float")) {
2716 CmdArgs.push_back(Elt: "-target-feature");
2717 CmdArgs.push_back(Elt: "-soft-float");
2718 continue;
2719 }
2720 if (Value == "-mmsa") {
2721 Msa = true;
2722 continue;
2723 }
2724 if (Value == "-mno-msa") {
2725 Msa = false;
2726 continue;
2727 }
2728 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2729 .Case(S: "-mips1", Value: "+mips1")
2730 .Case(S: "-mips2", Value: "+mips2")
2731 .Case(S: "-mips3", Value: "+mips3")
2732 .Case(S: "-mips4", Value: "+mips4")
2733 .Case(S: "-mips5", Value: "+mips5")
2734 .Case(S: "-mips32", Value: "+mips32")
2735 .Case(S: "-mips32r2", Value: "+mips32r2")
2736 .Case(S: "-mips32r3", Value: "+mips32r3")
2737 .Case(S: "-mips32r5", Value: "+mips32r5")
2738 .Case(S: "-mips32r6", Value: "+mips32r6")
2739 .Case(S: "-mips64", Value: "+mips64")
2740 .Case(S: "-mips64r2", Value: "+mips64r2")
2741 .Case(S: "-mips64r3", Value: "+mips64r3")
2742 .Case(S: "-mips64r5", Value: "+mips64r5")
2743 .Case(S: "-mips64r6", Value: "+mips64r6")
2744 .Default(Value: nullptr);
2745 if (MipsTargetFeature)
2746 continue;
2747 break;
2748
2749 case llvm::Triple::sparc:
2750 case llvm::Triple::sparcel:
2751 case llvm::Triple::sparcv9:
2752 if (Value == "--undeclared-regs") {
2753 // LLVM already allows undeclared use of G registers, so this option
2754 // becomes a no-op. This solely exists for GNU compatibility.
2755 // TODO implement --no-undeclared-regs
2756 continue;
2757 }
2758 SparcTargetFeatures =
2759 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2760 .Case(S: "-Av8", Value: {"-v8plus"})
2761 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2762 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2763 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2764 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2765 .Case(S: "-Av9", Value: {"+v9"})
2766 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2767 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2768 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2769 .Default(Value: {});
2770 if (!SparcTargetFeatures.empty())
2771 continue;
2772 break;
2773 }
2774
2775 if (Value == "-force_cpusubtype_ALL") {
2776 // Do nothing, this is the default and we don't support anything else.
2777 } else if (Value == "-L") {
2778 CmdArgs.push_back(Elt: "-msave-temp-labels");
2779 } else if (Value == "--fatal-warnings") {
2780 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2781 } else if (Value == "--no-warn" || Value == "-W") {
2782 CmdArgs.push_back(Elt: "-massembler-no-warn");
2783 } else if (Value == "--noexecstack") {
2784 UseNoExecStack = true;
2785 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2786 Value.starts_with(Prefix: "--compress-debug-sections") ||
2787 Value == "-nocompress-debug-sections" ||
2788 Value == "--nocompress-debug-sections") {
2789 CmdArgs.push_back(Elt: Value.data());
2790 } else if (Value == "--crel") {
2791 Crel = true;
2792 } else if (Value == "--no-crel") {
2793 Crel = false;
2794 } else if (Value == "--allow-experimental-crel") {
2795 ExperimentalCrel = true;
2796 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2797 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2798 } else if (Value.starts_with(Prefix: "-I")) {
2799 CmdArgs.push_back(Elt: Value.data());
2800 // We need to consume the next argument if the current arg is a plain
2801 // -I. The next arg will be the include directory.
2802 if (Value == "-I")
2803 TakeNextArg = true;
2804 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2805 // "-gdwarf-N" options are not cc1as options.
2806 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2807 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2808 CmdArgs.push_back(Elt: Value.data());
2809 } else {
2810 RenderDebugEnablingArgs(Args, CmdArgs,
2811 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2812 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2813 }
2814 } else if (Value == "--gsframe") {
2815 SFrame = true;
2816 } else if (Value == "--allow-experimental-sframe") {
2817 ExperimentalSFrame = true;
2818 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2819 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2820 // Do nothing, we'll validate it later.
2821 } else if (Value == "-defsym" || Value == "--defsym") {
2822 if (A->getNumValues() != 2) {
2823 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2824 break;
2825 }
2826 const char *S = A->getValue(N: 1);
2827 auto Pair = StringRef(S).split(Separator: '=');
2828 auto Sym = Pair.first;
2829 auto SVal = Pair.second;
2830
2831 if (Sym.empty() || SVal.empty()) {
2832 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2833 break;
2834 }
2835 int64_t IVal;
2836 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2837 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2838 break;
2839 }
2840 CmdArgs.push_back(Elt: "--defsym");
2841 TakeNextArg = true;
2842 } else if (Value == "-fdebug-compilation-dir") {
2843 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2844 TakeNextArg = true;
2845 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2846 // The flag is a -Wa / -Xassembler argument and Options doesn't
2847 // parse the argument, so this isn't automatically aliased to
2848 // -fdebug-compilation-dir (without '=') here.
2849 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2850 CmdArgs.push_back(Elt: Value.data());
2851 } else if (Value == "--version") {
2852 D.PrintVersion(C, OS&: llvm::outs());
2853 } else {
2854 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2855 << A->getSpelling() << Value;
2856 }
2857 }
2858 }
2859 if (ImplicitIt.size())
2860 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2861 if (Crel) {
2862 if (!ExperimentalCrel)
2863 D.Diag(DiagID: diag::err_drv_experimental_crel);
2864 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2865 CmdArgs.push_back(Elt: "--crel");
2866 } else {
2867 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2868 << "-Wa,--crel" << D.getTargetTriple();
2869 }
2870 }
2871 if (!RelocSectionSym.empty()) {
2872 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2873 RelocSectionSym != "none")
2874 D.Diag(DiagID: diag::err_drv_invalid_value)
2875 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2876 << RelocSectionSym;
2877 else if (Triple.isOSBinFormatELF())
2878 CmdArgs.push_back(
2879 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2880 else
2881 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2882 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2883 }
2884 if (SFrame) {
2885 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2886 if (!ExperimentalSFrame)
2887 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2888 else
2889 CmdArgs.push_back(Elt: "--gsframe");
2890 } else {
2891 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2892 << "-Wa,--gsframe" << D.getTargetTriple();
2893 }
2894 }
2895 if (ImplicitMapSyms)
2896 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2897 if (Msa)
2898 CmdArgs.push_back(Elt: "-mmsa");
2899 if (!UseRelaxRelocations)
2900 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2901 if (UseNoExecStack)
2902 CmdArgs.push_back(Elt: "-mnoexecstack");
2903 if (MipsTargetFeature != nullptr) {
2904 CmdArgs.push_back(Elt: "-target-feature");
2905 CmdArgs.push_back(Elt: MipsTargetFeature);
2906 }
2907
2908 for (const char *Feature : SparcTargetFeatures) {
2909 CmdArgs.push_back(Elt: "-target-feature");
2910 CmdArgs.push_back(Elt: Feature);
2911 }
2912
2913 // forward -fembed-bitcode to assmebler
2914 if (C.getDriver().embedBitcodeEnabled() ||
2915 C.getDriver().embedBitcodeMarkerOnly())
2916 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2917
2918 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2919 CmdArgs.push_back(Elt: "-as-secure-log-file");
2920 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2921 }
2922}
2923
2924static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2925 bool OFastEnabled, const ArgList &Args,
2926 ArgStringList &CmdArgs,
2927 const JobAction &JA) {
2928 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2929 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2930 llvm::StringLiteral("SLEEF")};
2931 bool NoMathErrnoWasImpliedByVecLib = false;
2932 const Arg *VecLibArg = nullptr;
2933 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2934 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2935
2936 // Handle various floating point optimization flags, mapping them to the
2937 // appropriate LLVM code generation flags. This is complicated by several
2938 // "umbrella" flags, so we do this by stepping through the flags incrementally
2939 // adjusting what we think is enabled/disabled, then at the end setting the
2940 // LLVM flags based on the final state.
2941 bool HonorINFs = true;
2942 bool HonorNaNs = true;
2943 bool ApproxFunc = false;
2944 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2945 bool MathErrno = TC.IsMathErrnoDefault();
2946 bool AssociativeMath = false;
2947 bool ReciprocalMath = false;
2948 bool SignedZeros = true;
2949 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2950 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2951 // overriden by ffp-exception-behavior?
2952 bool RoundingFPMath = false;
2953 // -ffp-model values: strict, fast, precise
2954 StringRef FPModel = "";
2955 // -ffp-exception-behavior options: strict, maytrap, ignore
2956 StringRef FPExceptionBehavior = "";
2957 // -ffp-eval-method options: double, extended, source
2958 StringRef FPEvalMethod = "";
2959 llvm::DenormalMode DenormalFPMath =
2960 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2961 llvm::DenormalMode DenormalFP32Math =
2962 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2963
2964 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2965 // If one wasn't given by the user, don't pass it here.
2966 StringRef FPContract;
2967 StringRef LastSeenFfpContractOption;
2968 StringRef LastFpContractOverrideOption;
2969 bool SeenUnsafeMathModeOption = false;
2970 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2971 !JA.isOffloading(OKind: Action::OFK_HIP))
2972 FPContract = "on";
2973 bool StrictFPModel = false;
2974 StringRef Float16ExcessPrecision = "";
2975 StringRef BFloat16ExcessPrecision = "";
2976 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2977 std::string ComplexRangeStr;
2978 StringRef LastComplexRangeOption;
2979
2980 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2981 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2982 if (Aggressive) {
2983 HonorINFs = false;
2984 HonorNaNs = false;
2985 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2986 LastOpt&: LastComplexRangeOption, Range);
2987 } else {
2988 HonorINFs = true;
2989 HonorNaNs = true;
2990 setComplexRange(D, NewOpt: CallerOption,
2991 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2992 LastOpt&: LastComplexRangeOption, Range);
2993 }
2994 MathErrno = false;
2995 AssociativeMath = true;
2996 ReciprocalMath = true;
2997 ApproxFunc = true;
2998 SignedZeros = false;
2999 TrappingMath = false;
3000 RoundingFPMath = false;
3001 FPExceptionBehavior = "";
3002 FPContract = "fast";
3003 SeenUnsafeMathModeOption = true;
3004 };
3005
3006 // Lambda to consolidate common handling for fp-contract
3007 auto restoreFPContractState = [&]() {
3008 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3009 // For other targets, if the state has been changed by one of the
3010 // unsafe-math umbrella options a subsequent -fno-fast-math or
3011 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3012 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3013 // option. If we have not seen an unsafe-math option or -ffp-contract,
3014 // we leave the FPContract state unchanged.
3015 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
3016 !JA.isOffloading(OKind: Action::OFK_HIP)) {
3017 if (LastSeenFfpContractOption != "")
3018 FPContract = LastSeenFfpContractOption;
3019 else if (SeenUnsafeMathModeOption)
3020 FPContract = "on";
3021 }
3022 // In this case, we're reverting to the last explicit fp-contract option
3023 // or the platform default
3024 LastFpContractOverrideOption = "";
3025 };
3026
3027 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
3028 CmdArgs.push_back(Elt: "-mlimit-float-precision");
3029 CmdArgs.push_back(Elt: A->getValue());
3030 }
3031
3032 for (const Arg *A : Args) {
3033 llvm::scope_exit CheckMathErrnoForVecLib(
3034 [&, MathErrnoBeforeArg = MathErrno] {
3035 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3036 ArgThatEnabledMathErrnoAfterVecLib = A;
3037 });
3038
3039 switch (A->getOption().getID()) {
3040 // If this isn't an FP option skip the claim below
3041 default: continue;
3042
3043 case options::OPT_fcx_limited_range:
3044 setComplexRange(D, NewOpt: A->getSpelling(),
3045 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
3046 LastOpt&: LastComplexRangeOption, Range);
3047 break;
3048 case options::OPT_fno_cx_limited_range:
3049 setComplexRange(D, NewOpt: A->getSpelling(),
3050 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3051 LastOpt&: LastComplexRangeOption, Range);
3052 break;
3053 case options::OPT_fcx_fortran_rules:
3054 setComplexRange(D, NewOpt: A->getSpelling(),
3055 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
3056 LastOpt&: LastComplexRangeOption, Range);
3057 break;
3058 case options::OPT_fno_cx_fortran_rules:
3059 setComplexRange(D, NewOpt: A->getSpelling(),
3060 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3061 LastOpt&: LastComplexRangeOption, Range);
3062 break;
3063 case options::OPT_fcomplex_arithmetic_EQ: {
3064 LangOptions::ComplexRangeKind RangeVal;
3065 StringRef Val = A->getValue();
3066 if (Val == "full")
3067 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
3068 else if (Val == "improved")
3069 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
3070 else if (Val == "promoted")
3071 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
3072 else if (Val == "basic")
3073 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
3074 else {
3075 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3076 << A->getSpelling() << Val;
3077 break;
3078 }
3079 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
3080 LastOpt&: LastComplexRangeOption, Range);
3081 break;
3082 }
3083 case options::OPT_ffp_model_EQ: {
3084 // If -ffp-model= is seen, reset to fno-fast-math
3085 HonorINFs = true;
3086 HonorNaNs = true;
3087 ApproxFunc = false;
3088 // Turning *off* -ffast-math restores the toolchain default.
3089 MathErrno = TC.IsMathErrnoDefault();
3090 AssociativeMath = false;
3091 ReciprocalMath = false;
3092 SignedZeros = true;
3093
3094 StringRef Val = A->getValue();
3095 if (OFastEnabled && Val != "aggressive") {
3096 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3097 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3098 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
3099 break;
3100 }
3101 StrictFPModel = false;
3102 if (!FPModel.empty() && FPModel != Val)
3103 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3104 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
3105 << Args.MakeArgString(Str: "-ffp-model=" + Val);
3106 if (Val == "fast") {
3107 FPModel = Val;
3108 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
3109 // applyFastMath sets fp-contract="fast"
3110 LastFpContractOverrideOption = "-ffp-model=fast";
3111 } else if (Val == "aggressive") {
3112 FPModel = Val;
3113 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
3114 // applyFastMath sets fp-contract="fast"
3115 LastFpContractOverrideOption = "-ffp-model=aggressive";
3116 } else if (Val == "precise") {
3117 FPModel = Val;
3118 FPContract = "on";
3119 LastFpContractOverrideOption = "-ffp-model=precise";
3120 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3121 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3122 LastOpt&: LastComplexRangeOption, Range);
3123 } else if (Val == "strict") {
3124 StrictFPModel = true;
3125 FPExceptionBehavior = "strict";
3126 FPModel = Val;
3127 FPContract = "off";
3128 LastFpContractOverrideOption = "-ffp-model=strict";
3129 TrappingMath = true;
3130 RoundingFPMath = true;
3131 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
3132 NewRange: LangOptions::ComplexRangeKind::CX_Full,
3133 LastOpt&: LastComplexRangeOption, Range);
3134 } else
3135 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3136 << A->getSpelling() << Val;
3137 break;
3138 }
3139
3140 // Options controlling individual features
3141 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3142 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3143 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3144 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3145 case options::OPT_fapprox_func: ApproxFunc = true; break;
3146 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3147 case options::OPT_fmath_errno: MathErrno = true; break;
3148 case options::OPT_fno_math_errno: MathErrno = false; break;
3149 case options::OPT_fassociative_math: AssociativeMath = true; break;
3150 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3151 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3152 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3153 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3154 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3155 case options::OPT_ftrapping_math:
3156 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3157 FPExceptionBehavior != "strict")
3158 // Warn that previous value of option is overridden.
3159 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3160 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3161 FPExceptionBehavior)
3162 << "-ftrapping-math";
3163 TrappingMath = true;
3164 TrappingMathPresent = true;
3165 FPExceptionBehavior = "strict";
3166 break;
3167 case options::OPT_fveclib:
3168 VecLibArg = A;
3169 NoMathErrnoWasImpliedByVecLib =
3170 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3171 if (NoMathErrnoWasImpliedByVecLib)
3172 MathErrno = false;
3173 break;
3174 case options::OPT_fno_trapping_math:
3175 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3176 FPExceptionBehavior != "ignore")
3177 // Warn that previous value of option is overridden.
3178 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3179 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3180 FPExceptionBehavior)
3181 << "-fno-trapping-math";
3182 TrappingMath = false;
3183 TrappingMathPresent = true;
3184 FPExceptionBehavior = "ignore";
3185 break;
3186
3187 case options::OPT_frounding_math:
3188 RoundingFPMath = true;
3189 break;
3190
3191 case options::OPT_fno_rounding_math:
3192 RoundingFPMath = false;
3193 break;
3194
3195 case options::OPT_fdenormal_fp_math_EQ:
3196 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3197 DenormalFP32Math = DenormalFPMath;
3198 if (!DenormalFPMath.isValid()) {
3199 D.Diag(DiagID: diag::err_drv_invalid_value)
3200 << A->getAsString(Args) << A->getValue();
3201 }
3202 break;
3203
3204 case options::OPT_fdenormal_fp_math_f32_EQ:
3205 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3206 if (!DenormalFP32Math.isValid()) {
3207 D.Diag(DiagID: diag::err_drv_invalid_value)
3208 << A->getAsString(Args) << A->getValue();
3209 }
3210 break;
3211
3212 // Validate and pass through -ffp-contract option.
3213 case options::OPT_ffp_contract: {
3214 StringRef Val = A->getValue();
3215 if (Val == "fast" || Val == "on" || Val == "off" ||
3216 Val == "fast-honor-pragmas") {
3217 if (Val != FPContract && LastFpContractOverrideOption != "") {
3218 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3219 << LastFpContractOverrideOption
3220 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3221 }
3222
3223 FPContract = Val;
3224 LastSeenFfpContractOption = Val;
3225 LastFpContractOverrideOption = "";
3226 } else
3227 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3228 << A->getSpelling() << Val;
3229 break;
3230 }
3231
3232 // Validate and pass through -ffp-exception-behavior option.
3233 case options::OPT_ffp_exception_behavior_EQ: {
3234 StringRef Val = A->getValue();
3235 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3236 FPExceptionBehavior != Val)
3237 // Warn that previous value of option is overridden.
3238 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3239 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3240 FPExceptionBehavior)
3241 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3242 TrappingMath = TrappingMathPresent = false;
3243 if (Val == "ignore" || Val == "maytrap")
3244 FPExceptionBehavior = Val;
3245 else if (Val == "strict") {
3246 FPExceptionBehavior = Val;
3247 TrappingMath = TrappingMathPresent = true;
3248 } else
3249 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3250 << A->getSpelling() << Val;
3251 break;
3252 }
3253
3254 // Validate and pass through -ffp-eval-method option.
3255 case options::OPT_ffp_eval_method_EQ: {
3256 StringRef Val = A->getValue();
3257 if (Val == "double" || Val == "extended" || Val == "source")
3258 FPEvalMethod = Val;
3259 else
3260 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3261 << A->getSpelling() << Val;
3262 break;
3263 }
3264
3265 case options::OPT_fexcess_precision_EQ: {
3266 StringRef Val = A->getValue();
3267 const llvm::Triple::ArchType Arch = TC.getArch();
3268 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3269 if (Val == "standard" || Val == "fast")
3270 Float16ExcessPrecision = Val;
3271 // To make it GCC compatible, allow the value of "16" which
3272 // means disable excess precision, the same meaning than clang's
3273 // equivalent value "none".
3274 else if (Val == "16")
3275 Float16ExcessPrecision = "none";
3276 else
3277 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3278 << A->getSpelling() << Val;
3279 } else {
3280 if (!(Val == "standard" || Val == "fast"))
3281 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3282 << A->getSpelling() << Val;
3283 }
3284 BFloat16ExcessPrecision = Float16ExcessPrecision;
3285 break;
3286 }
3287 case options::OPT_ffinite_math_only:
3288 HonorINFs = false;
3289 HonorNaNs = false;
3290 break;
3291 case options::OPT_fno_finite_math_only:
3292 HonorINFs = true;
3293 HonorNaNs = true;
3294 break;
3295
3296 case options::OPT_funsafe_math_optimizations:
3297 AssociativeMath = true;
3298 ReciprocalMath = true;
3299 SignedZeros = false;
3300 ApproxFunc = true;
3301 TrappingMath = false;
3302 FPExceptionBehavior = "";
3303 FPContract = "fast";
3304 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3305 SeenUnsafeMathModeOption = true;
3306 break;
3307 case options::OPT_fno_unsafe_math_optimizations:
3308 AssociativeMath = false;
3309 ReciprocalMath = false;
3310 SignedZeros = true;
3311 ApproxFunc = false;
3312 restoreFPContractState();
3313 break;
3314
3315 case options::OPT_Ofast:
3316 // If -Ofast is the optimization level, then -ffast-math should be enabled
3317 if (!OFastEnabled)
3318 continue;
3319 [[fallthrough]];
3320 case options::OPT_ffast_math:
3321 applyFastMath(true, A->getSpelling());
3322 if (A->getOption().getID() == options::OPT_Ofast)
3323 LastFpContractOverrideOption = "-Ofast";
3324 else
3325 LastFpContractOverrideOption = "-ffast-math";
3326 break;
3327 case options::OPT_fno_fast_math:
3328 HonorINFs = true;
3329 HonorNaNs = true;
3330 // Turning on -ffast-math (with either flag) removes the need for
3331 // MathErrno. However, turning *off* -ffast-math merely restores the
3332 // toolchain default (which may be false).
3333 MathErrno = TC.IsMathErrnoDefault();
3334 AssociativeMath = false;
3335 ReciprocalMath = false;
3336 ApproxFunc = false;
3337 SignedZeros = true;
3338 restoreFPContractState();
3339 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3340 setComplexRange(D, NewOpt: A->getSpelling(),
3341 NewRange: LangOptions::ComplexRangeKind::CX_None,
3342 LastOpt&: LastComplexRangeOption, Range);
3343 else
3344 Range = LangOptions::ComplexRangeKind::CX_None;
3345 LastComplexRangeOption = "";
3346 LastFpContractOverrideOption = "";
3347 break;
3348 } // End switch (A->getOption().getID())
3349
3350 // The StrictFPModel local variable is needed to report warnings
3351 // in the way we intend. If -ffp-model=strict has been used, we
3352 // want to report a warning for the next option encountered that
3353 // takes us out of the settings described by fp-model=strict, but
3354 // we don't want to continue issuing warnings for other conflicting
3355 // options after that.
3356 if (StrictFPModel) {
3357 // If -ffp-model=strict has been specified on command line but
3358 // subsequent options conflict then emit warning diagnostic.
3359 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3360 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3361 FPContract == "off")
3362 // OK: Current Arg doesn't conflict with -ffp-model=strict
3363 ;
3364 else {
3365 StrictFPModel = false;
3366 FPModel = "";
3367 // The warning for -ffp-contract would have been reported by the
3368 // OPT_ffp_contract_EQ handler above. A special check here is needed
3369 // to avoid duplicating the warning.
3370 auto RHS = (A->getNumValues() == 0)
3371 ? A->getSpelling()
3372 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3373 if (A->getSpelling() != "-ffp-contract=") {
3374 if (RHS != "-ffp-model=strict")
3375 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3376 << "-ffp-model=strict" << RHS;
3377 }
3378 }
3379 }
3380
3381 // If we handled this option claim it
3382 A->claim();
3383 }
3384
3385 if (!HonorINFs)
3386 CmdArgs.push_back(Elt: "-menable-no-infs");
3387
3388 if (!HonorNaNs)
3389 CmdArgs.push_back(Elt: "-menable-no-nans");
3390
3391 if (ApproxFunc)
3392 CmdArgs.push_back(Elt: "-fapprox-func");
3393
3394 if (MathErrno) {
3395 CmdArgs.push_back(Elt: "-fmath-errno");
3396 if (NoMathErrnoWasImpliedByVecLib)
3397 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3398 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3399 << VecLibArg->getAsString(Args);
3400 }
3401
3402 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3403 !TrappingMath)
3404 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3405
3406 if (!SignedZeros)
3407 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3408
3409 if (AssociativeMath && !SignedZeros && !TrappingMath)
3410 CmdArgs.push_back(Elt: "-mreassociate");
3411
3412 if (ReciprocalMath)
3413 CmdArgs.push_back(Elt: "-freciprocal-math");
3414
3415 if (TrappingMath) {
3416 // FP Exception Behavior is also set to strict
3417 assert(FPExceptionBehavior == "strict");
3418 }
3419
3420 // The default is IEEE.
3421 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3422 llvm::SmallString<64> DenormFlag;
3423 llvm::raw_svector_ostream ArgStr(DenormFlag);
3424 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3425 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3426 }
3427
3428 // Add f32 specific denormal mode flag if it's different.
3429 if (DenormalFP32Math != DenormalFPMath) {
3430 llvm::SmallString<64> DenormFlag;
3431 llvm::raw_svector_ostream ArgStr(DenormFlag);
3432 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3433 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3434 }
3435
3436 if (!FPContract.empty())
3437 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3438
3439 if (RoundingFPMath)
3440 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3441 else
3442 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3443
3444 if (!FPExceptionBehavior.empty())
3445 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3446 FPExceptionBehavior));
3447
3448 if (!FPEvalMethod.empty())
3449 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3450
3451 if (!Float16ExcessPrecision.empty())
3452 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3453 Float16ExcessPrecision));
3454 if (!BFloat16ExcessPrecision.empty())
3455 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3456 BFloat16ExcessPrecision));
3457
3458 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3459 if (!Recip.empty())
3460 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3461
3462 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3463 // individual features enabled by -ffast-math instead of the option itself as
3464 // that's consistent with gcc's behaviour.
3465 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3466 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3467 CmdArgs.push_back(Elt: "-ffast-math");
3468
3469 // Handle __FINITE_MATH_ONLY__ similarly.
3470 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3471 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3472 // -menable-no-nans are set by the user.
3473 bool shouldAddFiniteMathOnly = false;
3474 if (!HonorINFs && !HonorNaNs) {
3475 shouldAddFiniteMathOnly = true;
3476 } else {
3477 bool InfValues = true;
3478 bool NanValues = true;
3479 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3480 StringRef ArgValue = Arg->getValue();
3481 if (ArgValue == "-menable-no-nans")
3482 NanValues = false;
3483 else if (ArgValue == "-menable-no-infs")
3484 InfValues = false;
3485 }
3486 if (!NanValues && !InfValues)
3487 shouldAddFiniteMathOnly = true;
3488 }
3489 if (shouldAddFiniteMathOnly) {
3490 CmdArgs.push_back(Elt: "-ffinite-math-only");
3491 }
3492 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3493 CmdArgs.push_back(Elt: "-mfpmath");
3494 CmdArgs.push_back(Elt: A->getValue());
3495 }
3496
3497 // Disable a codegen optimization for floating-point casts.
3498 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3499 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3500 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3501
3502 if (Range != LangOptions::ComplexRangeKind::CX_None)
3503 ComplexRangeStr = renderComplexRangeOption(Range);
3504 if (!ComplexRangeStr.empty()) {
3505 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3506 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3507 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3508 complexRangeKindToStr(Range)));
3509 }
3510 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3511 CmdArgs.push_back(Elt: "-fcx-limited-range");
3512 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3513 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3514 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3515 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3516 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3517 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3518}
3519
3520static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3521 const llvm::Triple &Triple,
3522 const InputInfo &Input) {
3523 // Add default argument set.
3524 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3525 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3526 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3527
3528 if (!Triple.isWindowsMSVCEnvironment()) {
3529 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3530 } else {
3531 // Enable "unix" checkers that also work on Windows.
3532 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3533 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3534 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3535 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3536 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3537 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3538 }
3539
3540 // Disable some unix checkers for PS4/PS5.
3541 if (Triple.isPS()) {
3542 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3543 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3544 }
3545
3546 if (Triple.isOSDarwin()) {
3547 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3548 CmdArgs.push_back(
3549 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3550 }
3551 else if (Triple.isOSFuchsia())
3552 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3553
3554 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3555
3556 if (types::isCXX(Id: Input.getType()))
3557 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3558
3559 if (!Triple.isPS()) {
3560 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3561 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3562 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3563 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3564 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3565 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3566 }
3567
3568 // Default nullability checks.
3569 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3570 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3571 }
3572
3573 // Set the output format. The default is plist, for (lame) historical reasons.
3574 CmdArgs.push_back(Elt: "-analyzer-output");
3575 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3576 CmdArgs.push_back(Elt: A->getValue());
3577 else
3578 CmdArgs.push_back(Elt: "plist");
3579
3580 // Disable the presentation of standard compiler warnings when using
3581 // --analyze. We only want to show static analyzer diagnostics or frontend
3582 // errors.
3583 CmdArgs.push_back(Elt: "-w");
3584
3585 // Add -Xanalyzer arguments when running as analyzer.
3586 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3587}
3588
3589static bool isValidSymbolName(StringRef S) {
3590 if (S.empty())
3591 return false;
3592
3593 if (std::isdigit(S[0]))
3594 return false;
3595
3596 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3597}
3598
3599static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3600 const ArgList &Args, ArgStringList &CmdArgs,
3601 bool KernelOrKext) {
3602 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3603
3604 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3605 // doesn't even have a stack!
3606 if (EffectiveTriple.isNVPTX())
3607 return;
3608
3609 // -stack-protector=0 is default.
3610 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3611 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3612 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3613
3614 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3615 Ids: options::OPT_fstack_protector_all,
3616 Ids: options::OPT_fstack_protector_strong,
3617 Ids: options::OPT_fstack_protector)) {
3618 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3619 StackProtectorLevel =
3620 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3621 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3622 StackProtectorLevel = LangOptions::SSPStrong;
3623 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3624 StackProtectorLevel = LangOptions::SSPReq;
3625
3626 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3627 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3628 << A->getSpelling() << EffectiveTriple.getTriple();
3629 StackProtectorLevel = DefaultStackProtectorLevel;
3630 }
3631 } else {
3632 StackProtectorLevel = DefaultStackProtectorLevel;
3633 }
3634
3635 if (StackProtectorLevel) {
3636 CmdArgs.push_back(Elt: "-stack-protector");
3637 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3638 }
3639
3640 // --param ssp-buffer-size=
3641 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3642 StringRef Str(A->getValue());
3643 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3644 if (StackProtectorLevel) {
3645 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3646 // FIXME: Verify the argument is a valid integer.
3647 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3648 }
3649 A->claim();
3650 }
3651 }
3652
3653 const std::string &TripleStr = EffectiveTriple.getTriple();
3654 StringRef GuardValue;
3655 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3656 GuardValue = A->getValue();
3657 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3658 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3659 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3660 !EffectiveTriple.isSystemZ())
3661 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3662 << A->getAsString(Args) << TripleStr;
3663 // z/OS only supports the tls mode.
3664 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3665 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3666 << A->getOption().getName() << GuardValue << "tls";
3667 return;
3668 }
3669 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3670 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3671 GuardValue != "tls" && GuardValue != "global") {
3672 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3673 << A->getOption().getName() << GuardValue << "tls global";
3674 return;
3675 }
3676 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3677 GuardValue == "tls") {
3678 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3679 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3680 << A->getAsString(Args);
3681 return;
3682 }
3683 // Check whether the target subarch supports the hardware TLS register
3684 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3685 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3686 << EffectiveTriple.getArchName();
3687 return;
3688 }
3689 // Check whether the user asked for something other than -mtp=cp15
3690 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3691 StringRef Value = A->getValue();
3692 if (Value != "cp15") {
3693 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3694 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3695 return;
3696 }
3697 }
3698 CmdArgs.push_back(Elt: "-target-feature");
3699 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3700 }
3701 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3702 GuardValue != "global") {
3703 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3704 << A->getOption().getName() << GuardValue << "sysreg global";
3705 return;
3706 }
3707 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3708 if (GuardValue != "tls" && GuardValue != "global") {
3709 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3710 << A->getOption().getName() << GuardValue << "tls global";
3711 return;
3712 }
3713 if (GuardValue == "tls") {
3714 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3715 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3716 << A->getAsString(Args);
3717 return;
3718 }
3719 }
3720 }
3721 A->render(Args, Output&: CmdArgs);
3722 }
3723
3724 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3725 StringRef Value = A->getValue();
3726 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3727 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3728 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3729 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3730 << A->getAsString(Args) << TripleStr;
3731 int Offset;
3732 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3733 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3734 return;
3735 }
3736 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3737 (Offset < 0 || Offset > 0xfffff)) {
3738 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3739 << A->getOption().getName() << Value;
3740 return;
3741 }
3742 A->render(Args, Output&: CmdArgs);
3743 }
3744
3745 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3746 StringRef Value = A->getValue();
3747 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3748 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3749 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3750 << A->getAsString(Args) << TripleStr;
3751 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3752 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3753 << A->getOption().getName() << Value << "fs gs";
3754 return;
3755 }
3756 if (EffectiveTriple.isAArch64() &&
3757 llvm::StringSwitch<bool>(Value)
3758 .Cases(CaseStrings: {"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3759 "tpidr_el2", "far_el1", "far_el2"},
3760 Value: false)
3761 .Default(Value: true)) {
3762 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3763 << A->getOption().getName() << Value
3764 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3765 return;
3766 }
3767 if (EffectiveTriple.isRISCV() && Value != "tp") {
3768 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3769 << A->getOption().getName() << Value << "tp";
3770 return;
3771 }
3772 if (EffectiveTriple.isPPC64() && Value != "r13") {
3773 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3774 << A->getOption().getName() << Value << "r13";
3775 return;
3776 }
3777 if (EffectiveTriple.isPPC32() && Value != "r2") {
3778 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3779 << A->getOption().getName() << Value << "r2";
3780 return;
3781 }
3782 A->render(Args, Output&: CmdArgs);
3783 }
3784
3785 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3786 StringRef Value = A->getValue();
3787 if (!isValidSymbolName(S: Value)) {
3788 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3789 << A->getOption().getName() << "legal symbol name";
3790 return;
3791 }
3792 A->render(Args, Output&: CmdArgs);
3793 }
3794
3795 if (Arg *A =
3796 Args.getLastArg(Ids: options::OPT_mstack_protector_guard_value_width_EQ)) {
3797 if (!EffectiveTriple.isAArch64())
3798 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3799 << A->getAsString(Args) << TripleStr;
3800 StringRef Value = A->getValue();
3801 unsigned Width;
3802 if (Value.getAsInteger(Radix: 10, Result&: Width)) {
3803 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3804 return;
3805 }
3806 if (Width != 4 && Width != 8) {
3807 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3808 << A->getOption().getName() << Value;
3809 }
3810 }
3811 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstackprotector_guard_record)) {
3812 if (!EffectiveTriple.isSystemZ()) {
3813 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3814 << A->getAsString(Args) << TripleStr;
3815 return;
3816 }
3817 if (GuardValue != "global") {
3818 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3819 << "-mstack-protector-guard-record"
3820 << "-mstack-protector-guard=global";
3821 return;
3822 }
3823 A->render(Args, Output&: CmdArgs);
3824 }
3825}
3826
3827static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3828 ArgStringList &CmdArgs) {
3829 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3830
3831 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3832 !EffectiveTriple.isOSFuchsia())
3833 return;
3834
3835 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3836 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3837 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3838 return;
3839
3840 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_clash_protection,
3841 Neg: options::OPT_fno_stack_clash_protection);
3842}
3843
3844static void RenderTrivialAutoVarInitOptions(const Driver &D,
3845 const ToolChain &TC,
3846 const ArgList &Args,
3847 ArgStringList &CmdArgs) {
3848 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3849 StringRef TrivialAutoVarInit = "";
3850
3851 for (const Arg *A : Args) {
3852 switch (A->getOption().getID()) {
3853 default:
3854 continue;
3855 case options::OPT_ftrivial_auto_var_init: {
3856 A->claim();
3857 StringRef Val = A->getValue();
3858 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3859 TrivialAutoVarInit = Val;
3860 else
3861 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3862 << A->getSpelling() << Val;
3863 break;
3864 }
3865 }
3866 }
3867
3868 if (TrivialAutoVarInit.empty())
3869 switch (DefaultTrivialAutoVarInit) {
3870 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3871 break;
3872 case LangOptions::TrivialAutoVarInitKind::Pattern:
3873 TrivialAutoVarInit = "pattern";
3874 break;
3875 case LangOptions::TrivialAutoVarInitKind::Zero:
3876 TrivialAutoVarInit = "zero";
3877 break;
3878 }
3879
3880 if (!TrivialAutoVarInit.empty()) {
3881 CmdArgs.push_back(
3882 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3883 }
3884
3885 if (Arg *A =
3886 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3887 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3888 StringRef(
3889 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3890 "uninitialized")
3891 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3892 A->claim();
3893 StringRef Val = A->getValue();
3894 if (std::stoi(str: Val.str()) <= 0)
3895 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3896 CmdArgs.push_back(
3897 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3898 }
3899
3900 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3901 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3902 StringRef(
3903 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3904 "uninitialized")
3905 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3906 A->claim();
3907 StringRef Val = A->getValue();
3908 if (std::stoi(str: Val.str()) <= 0)
3909 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3910 CmdArgs.push_back(
3911 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3912 }
3913}
3914
3915static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3916 types::ID InputType) {
3917 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3918 // for denormal flushing handling based on the target.
3919 const unsigned ForwardedArguments[] = {
3920 options::OPT_cl_opt_disable,
3921 options::OPT_cl_strict_aliasing,
3922 options::OPT_cl_single_precision_constant,
3923 options::OPT_cl_finite_math_only,
3924 options::OPT_cl_kernel_arg_info,
3925 options::OPT_cl_unsafe_math_optimizations,
3926 options::OPT_cl_fast_relaxed_math,
3927 options::OPT_cl_mad_enable,
3928 options::OPT_cl_no_signed_zeros,
3929 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3930 options::OPT_cl_uniform_work_group_size
3931 };
3932
3933 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3934 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3935 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3936 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3937 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3938 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3939 }
3940
3941 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3942 CmdArgs.push_back(Elt: "-menable-no-infs");
3943 CmdArgs.push_back(Elt: "-menable-no-nans");
3944 }
3945
3946 for (const auto &Arg : ForwardedArguments)
3947 if (const auto *A = Args.getLastArg(Ids: Arg))
3948 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3949
3950 // Only add the default headers if we are compiling OpenCL sources.
3951 if ((types::isOpenCL(Id: InputType) ||
3952 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3953 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3954 CmdArgs.push_back(Elt: "-finclude-default-header");
3955 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3956 }
3957}
3958
3959static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3960 ArgStringList &CmdArgs, types::ID InputType) {
3961 const unsigned ForwardedArguments[] = {
3962 options::OPT_hlsl_all_resources_bound,
3963 options::OPT_dxil_validator_version,
3964 options::OPT_res_may_alias,
3965 options::OPT_D,
3966 options::OPT_I,
3967 options::OPT_O,
3968 options::OPT_emit_llvm,
3969 options::OPT_emit_obj,
3970 options::OPT_disable_llvm_passes,
3971 options::OPT_fnative_half_type,
3972 options::OPT_fnative_int16_type,
3973 options::OPT_fmatrix_memory_layout_EQ,
3974 options::OPT_hlsl_entrypoint,
3975 options::OPT_fdx_rootsignature_define,
3976 options::OPT_fdx_rootsignature_version,
3977 options::OPT_fhlsl_spv_use_unknown_image_format,
3978 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3979 options::OPT_fhlsl_spv_preserve_interface};
3980 if (!types::isHLSL(Id: InputType))
3981 return;
3982 for (const auto &Arg : ForwardedArguments)
3983 if (const auto *A = Args.getLastArg(Ids: Arg))
3984 A->renderAsInput(Args, Output&: CmdArgs);
3985 // Add the default headers if dxc_no_stdinc is not set.
3986 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3987 !Args.hasArg(Ids: options::OPT_nostdinc))
3988 CmdArgs.push_back(Elt: "-finclude-default-header");
3989
3990 if (Args.hasArg(Ids: options::OPT_dxc_Zss)) {
3991 if (Args.hasArg(Ids: options::OPT_dxc_Zsb))
3992 D.Diag(DiagID: diag::err_drv_dxc_invalid_shader_hash);
3993 CmdArgs.push_back(Elt: "-mllvm");
3994 CmdArgs.push_back(Elt: "-dx-Zss");
3995 }
3996 if (Arg *A = Args.getLastArg(Ids: options::OPT_dxc_Zsb))
3997 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3998 if (Args.hasArg(Ids: options::OPT_dxc_source_in_debug_module)) {
3999 CmdArgs.push_back(Elt: "-mllvm");
4000 CmdArgs.push_back(Elt: "--dx-source-in-debug-module");
4001 }
4002 if (Args.hasArg(Ids: options::OPT_dxc_Qstrip_debug)) {
4003 CmdArgs.push_back(Elt: "-mllvm");
4004 CmdArgs.push_back(Elt: "--dx-strip-debug");
4005 }
4006 if (Args.hasArg(Ids: options::OPT_dxc_Qpdb_in_private)) {
4007 CmdArgs.push_back(Elt: "-mllvm");
4008 CmdArgs.push_back(Elt: "--dx-pdb-in-private");
4009 }
4010}
4011
4012static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4013 ArgStringList &CmdArgs, types::ID InputType) {
4014 if (!Args.hasArg(Ids: options::OPT_fopenacc))
4015 return;
4016
4017 CmdArgs.push_back(Elt: "-fopenacc");
4018}
4019
4020static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4021 const ArgList &Args, ArgStringList &CmdArgs) {
4022 // -fbuiltin is default unless -mkernel is used.
4023 bool UseBuiltins =
4024 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
4025 Default: !Args.hasArg(Ids: options::OPT_mkernel));
4026 if (!UseBuiltins)
4027 CmdArgs.push_back(Elt: "-fno-builtin");
4028
4029 // -ffreestanding implies -fno-builtin.
4030 if (Args.hasArg(Ids: options::OPT_ffreestanding))
4031 UseBuiltins = false;
4032
4033 // Process the -fno-builtin-* options.
4034 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
4035 A->claim();
4036
4037 // If -fno-builtin is specified, then there's no need to pass the option to
4038 // the frontend.
4039 if (UseBuiltins)
4040 A->render(Args, Output&: CmdArgs);
4041 }
4042}
4043
4044bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
4045 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
4046 Twine Path{Str};
4047 Path.toVector(Out&: Result);
4048 return Path.getSingleStringRef() != "";
4049 }
4050 if (llvm::sys::path::cache_directory(result&: Result)) {
4051 llvm::sys::path::append(path&: Result, a: "clang");
4052 llvm::sys::path::append(path&: Result, a: "ModuleCache");
4053 return true;
4054 }
4055 return false;
4056}
4057
4058llvm::SmallString<256>
4059clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
4060 const char *BaseInput) {
4061 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
4062 return StringRef(ModuleOutputEQ->getValue());
4063
4064 SmallString<256> OutputPath;
4065 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
4066 FinalOutput && Args.hasArg(Ids: options::OPT_c))
4067 OutputPath = FinalOutput->getValue();
4068 else {
4069 llvm::sys::fs::current_path(result&: OutputPath);
4070 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
4071 }
4072
4073 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
4074 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
4075 return OutputPath;
4076}
4077
4078static bool RenderModulesOptions(Compilation &C, const Driver &D,
4079 const ArgList &Args, const InputInfo &Input,
4080 const InputInfo &Output, bool HaveStd20,
4081 ArgStringList &CmdArgs) {
4082 const bool IsCXX = types::isCXX(Id: Input.getType());
4083 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4084 bool HaveModules = HaveStdCXXModules;
4085
4086 // -fmodules enables the use of precompiled modules (off by default).
4087 // Users can pass -fno-cxx-modules to turn off modules support for
4088 // C++/Objective-C++ programs.
4089 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
4090 Neg: options::OPT_fno_cxx_modules, Default: true);
4091 bool HaveClangModules = false;
4092 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
4093 if (AllowedInCXX || !IsCXX) {
4094 CmdArgs.push_back(Elt: "-fmodules");
4095 HaveClangModules = true;
4096 }
4097 }
4098
4099 HaveModules |= HaveClangModules;
4100
4101 if (HaveModules && !AllowedInCXX)
4102 CmdArgs.push_back(Elt: "-fno-cxx-modules");
4103
4104 // -fmodule-maps enables implicit reading of module map files. By default,
4105 // this is enabled if we are using Clang's flavor of precompiled modules.
4106 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
4107 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
4108 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
4109
4110 // -fmodules-decluse checks that modules used are declared so (off by default)
4111 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
4112 Neg: options::OPT_fno_modules_decluse);
4113
4114 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4115 // all #included headers are part of modules.
4116 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
4117 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
4118 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
4119
4120 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
4121 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
4122
4123 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4124 bool ImplicitModules = false;
4125 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
4126 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
4127 if (HaveModules)
4128 CmdArgs.push_back(Elt: "-fno-implicit-modules");
4129 } else if (HaveModules) {
4130 ImplicitModules = true;
4131 // -fmodule-cache-path specifies where our implicitly-built module files
4132 // should be written.
4133 SmallString<128> Path;
4134 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
4135 Path = A->getValue();
4136
4137 bool HasPath = true;
4138 if (C.isForDiagnostics()) {
4139 // When generating crash reports, we want to emit the modules along with
4140 // the reproduction sources, so we ignore any provided module path.
4141 Path = Output.getFilename();
4142 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
4143 llvm::sys::path::append(path&: Path, a: "modules");
4144 } else if (Path.empty()) {
4145 // No module path was provided: use the default.
4146 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
4147 }
4148
4149 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4150 // That being said, that failure is unlikely and not caching is harmless.
4151 if (HasPath) {
4152 const char Arg[] = "-fmodules-cache-path=";
4153 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
4154 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
4155 }
4156
4157 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
4158 }
4159
4160 if (HaveModules) {
4161 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
4162 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
4163 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
4164 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
4165 Neg: options::OPT_fno_modules_validate_input_files_content,
4166 Default: false))
4167 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
4168 }
4169
4170 // -fmodule-name specifies the module that is currently being built (or
4171 // used for header checking by -fmodule-maps).
4172 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
4173
4174 // -fmodule-map-file can be used to specify files containing module
4175 // definitions.
4176 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
4177
4178 // -fbuiltin-module-map can be used to load the clang
4179 // builtin headers modulemap file.
4180 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
4181 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4182 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
4183 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
4184 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
4185 CmdArgs.push_back(
4186 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
4187 }
4188
4189 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4190 // names to precompiled module files (the module is loaded only if used).
4191 // The -fmodule-file=<file> form can be used to unconditionally load
4192 // precompiled module files (whether used or not).
4193 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4194 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
4195
4196 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4197 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
4198 CmdArgs.push_back(Elt: Args.MakeArgString(
4199 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
4200 A->claim();
4201 }
4202 } else
4203 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
4204
4205 // When building modules and generating crashdumps, we need to dump a module
4206 // dependency VFS alongside the output.
4207 if (HaveClangModules && C.isForDiagnostics()) {
4208 SmallString<128> VFSDir(Output.getFilename());
4209 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
4210 // Add the cache directory as a temp so the crash diagnostics pick it up.
4211 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
4212
4213 llvm::sys::path::append(path&: VFSDir, a: "vfs");
4214 CmdArgs.push_back(Elt: "-module-dependency-dir");
4215 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
4216 }
4217
4218 if (HaveClangModules)
4219 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
4220
4221 // Pass through all -fmodules-ignore-macro arguments.
4222 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
4223 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
4224 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4225
4226 if (HaveClangModules) {
4227 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4228
4229 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4230 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4231 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4232 << A->getAsString(Args) << "-fbuild-session-timestamp";
4233
4234 llvm::sys::fs::file_status Status;
4235 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4236 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4237 CmdArgs.push_back(Elt: Args.MakeArgString(
4238 Str: "-fbuild-session-timestamp=" +
4239 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4240 d: Status.getLastModificationTime().time_since_epoch())
4241 .count())));
4242 }
4243
4244 if (Args.getLastArg(
4245 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4246 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4247 Ids: options::OPT_fbuild_session_file))
4248 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4249
4250 Args.AddLastArg(Output&: CmdArgs,
4251 Ids: options::OPT_fmodules_validate_once_per_build_session);
4252 }
4253
4254 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4255 Neg: options::OPT_fno_modules_validate_system_headers,
4256 Default: ImplicitModules))
4257 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4258
4259 Args.AddLastArg(Output&: CmdArgs,
4260 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4261 } else {
4262 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4263 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4264 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4265 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4266 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4267 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4268 }
4269
4270 // FIXME: We provisionally don't check ODR violations for decls in the global
4271 // module fragment.
4272 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4273
4274 if (Input.getType() == driver::types::TY_CXXModule ||
4275 Input.getType() == driver::types::TY_PP_CXXModule) {
4276 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4277 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4278
4279 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4280 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4281 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4282 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4283 Args.hasArg(Ids: options::OPT_fmodule_output))
4284 // If --precompile is specified, we will always generate a module file if
4285 // we're compiling an importable module unit. This is fine even if the
4286 // compilation process won't reach the point of generating the module file
4287 // (e.g., in the preprocessing mode), since the attached flag
4288 // '-fmodule-output' is useless.
4289 //
4290 // But if '--precompile' is specified, it might be annoying to always
4291 // generate the module file as '--precompile' will generate the module
4292 // file anyway.
4293 CmdArgs.push_back(Elt: Args.MakeArgString(
4294 Str: "-fmodule-output=" +
4295 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4296 }
4297
4298 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4299 Args.hasArg(Ids: options::OPT__precompile) &&
4300 (!Args.hasArg(Ids: options::OPT_o) ||
4301 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4302 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4303 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4304 }
4305
4306 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4307 // other translation units than module units. This is more user friendly to
4308 // allow end uers to enable this feature without asking for help from build
4309 // systems.
4310 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4311 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4312
4313 // We need to include the case the input file is a module file here.
4314 // Since the default compilation model for C++ module interface unit will
4315 // create temporary module file and compile the temporary module file
4316 // to get the object file. Then the `-fmodule-output` flag will be
4317 // brought to the second compilation process. So we have to claim it for
4318 // the case too.
4319 if (Input.getType() == driver::types::TY_CXXModule ||
4320 Input.getType() == driver::types::TY_PP_CXXModule ||
4321 Input.getType() == driver::types::TY_ModuleFile) {
4322 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4323 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4324 }
4325
4326 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4327 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4328
4329 return HaveModules;
4330}
4331
4332static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4333 ArgStringList &CmdArgs) {
4334 // -fsigned-char is default.
4335 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4336 Ids: options::OPT_fno_signed_char,
4337 Ids: options::OPT_funsigned_char,
4338 Ids: options::OPT_fno_unsigned_char)) {
4339 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4340 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4341 CmdArgs.push_back(Elt: "-fno-signed-char");
4342 }
4343 } else if (!isSignedCharDefault(Triple: T)) {
4344 CmdArgs.push_back(Elt: "-fno-signed-char");
4345 }
4346
4347 // The default depends on the language standard.
4348 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4349
4350 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4351 Ids: options::OPT_fno_short_wchar)) {
4352 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4353 CmdArgs.push_back(Elt: "-fwchar-type=short");
4354 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4355 } else {
4356 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4357 CmdArgs.push_back(Elt: "-fwchar-type=int");
4358 if (T.isOSzOS() ||
4359 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4360 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4361 else
4362 CmdArgs.push_back(Elt: "-fsigned-wchar");
4363 }
4364 } else if (T.isOSzOS())
4365 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4366}
4367
4368static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4369 const llvm::Triple &T, const ArgList &Args,
4370 ObjCRuntime &Runtime, bool InferCovariantReturns,
4371 const InputInfo &Input, ArgStringList &CmdArgs) {
4372 const llvm::Triple::ArchType Arch = TC.getArch();
4373
4374 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4375 // is the default. Except for deployment target of 10.5, next runtime is
4376 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4377 if (Runtime.isNonFragile()) {
4378 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4379 Neg: options::OPT_fno_objc_legacy_dispatch,
4380 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4381 if (TC.UseObjCMixedDispatch())
4382 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4383 else
4384 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4385 }
4386 }
4387
4388 // Forward -fobjc-direct-precondition-thunk to cc1
4389 // Defaults to false and needs explict turn on for now
4390 // TODO: switch to default true and needs explict turn off in the future.
4391 // TODO: add support for other runtimes
4392 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4393 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4394 if (Runtime.isNeXTFamily()) {
4395 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4396 } else {
4397 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4398 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4399 }
4400 }
4401
4402 if (types::isObjC(Id: Input.getType())) {
4403 // Pass down -fobjc-msgsend-selector-stubs if present.
4404 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4405 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4406 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4407
4408 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4409 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4410 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4411 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4412 }
4413
4414 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4415 // to do Array/Dictionary subscripting by default.
4416 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4417 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4418 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4419
4420 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4421 // NOTE: This logic is duplicated in ToolChains.cpp.
4422 if (isObjCAutoRefCount(Args)) {
4423 TC.CheckObjCARC();
4424
4425 CmdArgs.push_back(Elt: "-fobjc-arc");
4426
4427 // FIXME: It seems like this entire block, and several around it should be
4428 // wrapped in isObjC, but for now we just use it here as this is where it
4429 // was being used previously.
4430 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4431 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4432 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4433 else
4434 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4435 }
4436
4437 // Allow the user to enable full exceptions code emission.
4438 // We default off for Objective-C, on for Objective-C++.
4439 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4440 Neg: options::OPT_fno_objc_arc_exceptions,
4441 /*Default=*/types::isCXX(Id: Input.getType())))
4442 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4443 }
4444
4445 // Silence warning for full exception code emission options when explicitly
4446 // set to use no ARC.
4447 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4448 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4449 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4450 }
4451
4452 // Allow the user to control whether messages can be converted to runtime
4453 // functions.
4454 if (types::isObjC(Id: Input.getType())) {
4455 auto *Arg = Args.getLastArg(
4456 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4457 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4458 if (Arg &&
4459 Arg->getOption().matches(
4460 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4461 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4462 }
4463
4464 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4465 // rewriter.
4466 if (InferCovariantReturns)
4467 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4468
4469 // Pass down -fobjc-weak or -fno-objc-weak if present.
4470 if (types::isObjC(Id: Input.getType())) {
4471 auto WeakArg =
4472 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4473 if (!WeakArg) {
4474 // nothing to do
4475 } else if (!Runtime.allowsWeak()) {
4476 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4477 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4478 } else {
4479 WeakArg->render(Args, Output&: CmdArgs);
4480 }
4481 }
4482
4483 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4484 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4485
4486 // Forward constant literal flags to cc1.
4487 if (types::isObjC(Id: Input.getType())) {
4488 bool EnableConstantLiterals =
4489 Args.hasFlag(Pos: options::OPT_fobjc_constant_literals,
4490 Neg: options::OPT_fno_objc_constant_literals,
4491 /*default=*/Default: true) &&
4492 Runtime.hasConstantLiteralClasses();
4493 if (EnableConstantLiterals)
4494 CmdArgs.push_back(Elt: "-fobjc-constant-literals");
4495 if (Args.hasFlag(Pos: options::OPT_fconstant_nsnumber_literals,
4496 Neg: options::OPT_fno_constant_nsnumber_literals,
4497 /*default=*/Default: true) &&
4498 EnableConstantLiterals)
4499 CmdArgs.push_back(Elt: "-fconstant-nsnumber-literals");
4500 if (Args.hasFlag(Pos: options::OPT_fconstant_nsarray_literals,
4501 Neg: options::OPT_fno_constant_nsarray_literals,
4502 /*default=*/Default: true) &&
4503 EnableConstantLiterals)
4504 CmdArgs.push_back(Elt: "-fconstant-nsarray-literals");
4505 if (Args.hasFlag(Pos: options::OPT_fconstant_nsdictionary_literals,
4506 Neg: options::OPT_fno_constant_nsdictionary_literals,
4507 /*default=*/Default: true) &&
4508 EnableConstantLiterals)
4509 CmdArgs.push_back(Elt: "-fconstant-nsdictionary-literals");
4510 }
4511}
4512
4513static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4514 ArgStringList &CmdArgs) {
4515 bool CaretDefault = true;
4516 bool ColumnDefault = true;
4517
4518 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4519 Ids: options::OPT__SLASH_diagnostics_column,
4520 Ids: options::OPT__SLASH_diagnostics_caret)) {
4521 switch (A->getOption().getID()) {
4522 case options::OPT__SLASH_diagnostics_caret:
4523 CaretDefault = true;
4524 ColumnDefault = true;
4525 break;
4526 case options::OPT__SLASH_diagnostics_column:
4527 CaretDefault = false;
4528 ColumnDefault = true;
4529 break;
4530 case options::OPT__SLASH_diagnostics_classic:
4531 CaretDefault = false;
4532 ColumnDefault = false;
4533 break;
4534 }
4535 }
4536
4537 // -fcaret-diagnostics is default.
4538 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4539 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4540 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4541
4542 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4543 Neg: options::OPT_fno_diagnostics_fixit_info);
4544 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4545 Neg: options::OPT_fno_diagnostics_show_option);
4546
4547 if (const Arg *A =
4548 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4549 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4550 CmdArgs.push_back(Elt: A->getValue());
4551 }
4552
4553 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4554 Neg: options::OPT_fno_diagnostics_show_hotness);
4555
4556 if (const Arg *A =
4557 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4558 std::string Opt =
4559 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4560 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4561 }
4562
4563 if (const Arg *A =
4564 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4565 std::string Opt =
4566 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4567 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4568 }
4569
4570 if (const Arg *A =
4571 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_inlining_chain,
4572 Ids: options::OPT_fno_diagnostics_show_inlining_chain)) {
4573 if (A->getOption().matches(ID: options::OPT_fdiagnostics_show_inlining_chain))
4574 CmdArgs.push_back(Elt: "-fdiagnostics-show-inlining-chain");
4575 else
4576 CmdArgs.push_back(Elt: "-fno-diagnostics-show-inlining-chain");
4577 }
4578
4579 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4580 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4581 CmdArgs.push_back(Elt: A->getValue());
4582 if (StringRef(A->getValue()) == "sarif" ||
4583 StringRef(A->getValue()) == "SARIF")
4584 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4585 }
4586
4587 if (const Arg *A = Args.getLastArg(
4588 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4589 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4590 const Option &O = A->getOption();
4591 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4592 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4593 else
4594 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4595 }
4596
4597 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4598
4599 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4600 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4601
4602 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4603 Neg: options::OPT_fno_show_source_location);
4604
4605 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4606 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4607
4608 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4609 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4610
4611 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4612 Default: ColumnDefault))
4613 CmdArgs.push_back(Elt: "-fno-show-column");
4614
4615 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4616 Neg: options::OPT_fno_spell_checking);
4617
4618 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4619}
4620
4621static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4622 const ArgList &Args, ArgStringList &CmdArgs,
4623 unsigned DwarfVersion) {
4624 auto *DwarfFormatArg =
4625 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4626 if (!DwarfFormatArg)
4627 return;
4628
4629 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4630 if (DwarfVersion < 3)
4631 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4632 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4633 else if (!T.isArch64Bit())
4634 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4635 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4636 else if (!T.isOSBinFormatELF())
4637 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4638 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4639 }
4640
4641 DwarfFormatArg->render(Args, Output&: CmdArgs);
4642}
4643
4644static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4645 const ArgList &Args) {
4646 bool NeedsSimpleTemplateNames =
4647 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4648 Neg: options::OPT_gno_simple_template_names,
4649 Default: TC.getDefaultDebugSimpleTemplateNames());
4650 if (!NeedsSimpleTemplateNames)
4651 return false;
4652
4653 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4654 if (!checkDebugInfoOption(A, Args, D, TC))
4655 return false;
4656
4657 return true;
4658}
4659
4660static void
4661renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4662 const ArgList &Args, types::ID InputType,
4663 ArgStringList &CmdArgs, const InputInfo &Output,
4664 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4665 DwarfFissionKind &DwarfFission) {
4666 bool IRInput = isLLVMIR(Id: InputType);
4667 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4668 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4669 !isOpenCL(Id: InputType);
4670
4671 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4672
4673 if (!Args.hasFlag(Pos: options::OPT_fdebug_record_sysroot,
4674 Neg: options::OPT_fno_debug_record_sysroot, Default: true))
4675 CmdArgs.push_back(Elt: "-fno-debug-record-sysroot");
4676
4677 // The 'g' groups options involve a somewhat intricate sequence of decisions
4678 // about what to pass from the driver to the frontend, but by the time they
4679 // reach cc1 they've been factored into three well-defined orthogonal choices:
4680 // * what level of debug info to generate
4681 // * what dwarf version to write
4682 // * what debugger tuning to use
4683 // This avoids having to monkey around further in cc1 other than to disable
4684 // codeview if not running in a Windows environment. Perhaps even that
4685 // decision should be made in the driver as well though.
4686 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4687
4688 bool SplitDWARFInlining =
4689 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4690 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4691
4692 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4693 // object file generation and no IR generation, -gN should not be needed. So
4694 // allow -gsplit-dwarf with either -gN or IR input.
4695 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4696 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4697 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4698 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4699 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4700 << TC.getTripleString();
4701 return;
4702 }
4703 Arg *SplitDWARFArg;
4704 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4705 if (DwarfFission != DwarfFissionKind::None &&
4706 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4707 DwarfFission = DwarfFissionKind::None;
4708 SplitDWARFInlining = false;
4709 }
4710 }
4711 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4712 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4713
4714 // If the last option explicitly specified a debug-info level, use it.
4715 if (checkDebugInfoOption(A, Args, D, TC) &&
4716 A->getOption().matches(ID: options::OPT_gN_Group)) {
4717 DebugInfoKind = debugLevelToInfoKind(A: *A);
4718 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4719 // complicated if you've disabled inline info in the skeleton CUs
4720 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4721 // line-tables-only, so let those compose naturally in that case.
4722 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4723 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4724 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4725 SplitDWARFInlining))
4726 DwarfFission = DwarfFissionKind::None;
4727 }
4728 }
4729
4730 // If a debugger tuning argument appeared, remember it.
4731 bool HasDebuggerTuning = false;
4732 if (const Arg *A =
4733 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4734 HasDebuggerTuning = true;
4735 if (checkDebugInfoOption(A, Args, D, TC)) {
4736 if (A->getOption().matches(ID: options::OPT_glldb))
4737 DebuggerTuning = llvm::DebuggerKind::LLDB;
4738 else if (A->getOption().matches(ID: options::OPT_gsce))
4739 DebuggerTuning = llvm::DebuggerKind::SCE;
4740 else if (A->getOption().matches(ID: options::OPT_gdbx))
4741 DebuggerTuning = llvm::DebuggerKind::DBX;
4742 else
4743 DebuggerTuning = llvm::DebuggerKind::GDB;
4744 }
4745 }
4746
4747 // If a -gdwarf argument appeared, remember it.
4748 bool EmitDwarf = false;
4749 if (const Arg *A = getDwarfNArg(Args))
4750 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4751
4752 bool EmitCodeView = false;
4753 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4754 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4755
4756 // If the user asked for debug info but did not explicitly specify -gcodeview
4757 // or -gdwarf, ask the toolchain for the default format.
4758 if (!EmitCodeView && !EmitDwarf &&
4759 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4760 switch (TC.getDefaultDebugFormat()) {
4761 case llvm::codegenoptions::DIF_CodeView:
4762 EmitCodeView = true;
4763 break;
4764 case llvm::codegenoptions::DIF_DWARF:
4765 EmitDwarf = true;
4766 break;
4767 }
4768 }
4769
4770 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4771 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4772 // be lower than what the user wanted.
4773 if (EmitDwarf) {
4774 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4775 // Clamp effective DWARF version to the max supported by the toolchain.
4776 EffectiveDWARFVersion =
4777 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4778 } else {
4779 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4780 }
4781
4782 // -gline-directives-only supported only for the DWARF debug info.
4783 if (RequestedDWARFVersion == 0 &&
4784 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4785 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4786
4787 // strict DWARF is set to false by default. But for DBX, we need it to be set
4788 // as true by default.
4789 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4790 (void)checkDebugInfoOption(A, Args, D, TC);
4791 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4792 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4793 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4794
4795 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4796 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4797
4798 // Column info is included by default for everything except SCE and
4799 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4800 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4801 // practice, however, the Microsoft debuggers don't handle missing end columns
4802 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4803 // it's better not to include any column info.
4804 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4805 (void)checkDebugInfoOption(A, Args, D, TC);
4806 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4807 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4808 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4809 DebuggerTuning != llvm::DebuggerKind::DBX)))
4810 CmdArgs.push_back(Elt: "-gno-column-info");
4811
4812 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4813 Neg: options::OPT_gno_call_site_info, Default: true))
4814 CmdArgs.push_back(Elt: "-gno-call-site-info");
4815
4816 // FIXME: Move backend command line options to the module.
4817 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4818 // If -gline-tables-only or -gline-directives-only is the last option it
4819 // wins.
4820 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4821 TC)) {
4822 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4823 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4824 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4825 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4826 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4827 }
4828 }
4829 }
4830
4831 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4832 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4833
4834 // After we've dealt with all combinations of things that could
4835 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4836 // figure out if we need to "upgrade" it to standalone debug info.
4837 // We parse these two '-f' options whether or not they will be used,
4838 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4839 bool NeedFullDebug = Args.hasFlag(
4840 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4841 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4842 TC.GetDefaultStandaloneDebug());
4843 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4844 (void)checkDebugInfoOption(A, Args, D, TC);
4845
4846 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4847 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4848 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4849 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4850 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4851 else if (NeedFullDebug)
4852 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4853 }
4854
4855 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4856 Default: false)) {
4857 // Source embedding is a vendor extension to DWARF v5. By now we have
4858 // checked if a DWARF version was stated explicitly, and have otherwise
4859 // fallen back to the target default, so if this is still not at least 5
4860 // we emit an error.
4861 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4862 if (RequestedDWARFVersion < 5)
4863 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4864 << A->getAsString(Args) << "-gdwarf-5";
4865 else if (EffectiveDWARFVersion < 5)
4866 // The toolchain has reduced allowed dwarf version, so we can't enable
4867 // -gembed-source.
4868 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4869 << A->getAsString(Args) << TC.getTripleString() << 5
4870 << EffectiveDWARFVersion;
4871 else if (checkDebugInfoOption(A, Args, D, TC))
4872 CmdArgs.push_back(Elt: "-gembed-source");
4873 }
4874
4875 // Enable Key Instructions by default if we're emitting DWARF, the language is
4876 // plain C or C++, and optimisations are enabled.
4877 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4878 bool KeyInstructionsOnByDefault =
4879 EmitDwarf && PlainCOrCXX && OptLevel &&
4880 !OptLevel->getOption().matches(ID: options::OPT_O0);
4881 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4882 Neg: options::OPT_gno_key_instructions,
4883 Default: KeyInstructionsOnByDefault))
4884 CmdArgs.push_back(Elt: "-gkey-instructions");
4885
4886 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4887 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4888 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4889
4890 if (EmitCodeView) {
4891 CmdArgs.push_back(Elt: "-gcodeview");
4892
4893 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4894 Neg: options::OPT_gno_codeview_ghash);
4895
4896 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4897 Neg: options::OPT_gno_codeview_command_line);
4898 }
4899
4900 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4901 Neg: options::OPT_gno_inline_line_tables);
4902
4903 // When emitting remarks, we need at least debug lines in the output.
4904 if (willEmitRemarks(Args) &&
4905 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4906 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4907
4908 // Adjust the debug info kind for the given toolchain.
4909 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4910
4911 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4912 // set.
4913 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4914 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4915 ? llvm::DebuggerKind::Default
4916 : DebuggerTuning);
4917
4918 // -fdebug-macro turns on macro debug info generation.
4919 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4920 Default: false))
4921 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4922 D, TC))
4923 CmdArgs.push_back(Elt: "-debug-info-macro");
4924
4925 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4926 const auto *PubnamesArg =
4927 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4928 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4929 if (DwarfFission != DwarfFissionKind::None ||
4930 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4931 const bool OptionSet =
4932 (PubnamesArg &&
4933 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4934 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4935 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4936 (!PubnamesArg ||
4937 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4938 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4939 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4940 ID: options::OPT_gpubnames)
4941 ? "-gpubnames"
4942 : "-ggnu-pubnames");
4943 }
4944
4945 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4946 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4947 ForwardTemplateParams = true;
4948 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4949 }
4950
4951 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4952 bool UseDebugTemplateAlias =
4953 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4954 if (const auto *DebugTemplateAlias = Args.getLastArg(
4955 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4956 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4957 // asks for it we should let them have it (if the target supports it).
4958 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4959 const auto &Opt = DebugTemplateAlias->getOption();
4960 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4961 }
4962 }
4963 if (UseDebugTemplateAlias)
4964 CmdArgs.push_back(Elt: "-gtemplate-alias");
4965
4966 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4967 StringRef v = A->getValue();
4968 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4969 }
4970
4971 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
4972 Neg: options::OPT_fno_debug_ranges_base_address);
4973
4974 // -gdwarf-aranges turns on the emission of the aranges section in the
4975 // backend.
4976 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
4977 A && checkDebugInfoOption(A, Args, D, TC)) {
4978 CmdArgs.push_back(Elt: "-mllvm");
4979 CmdArgs.push_back(Elt: "-generate-arange-section");
4980 }
4981
4982 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
4983 Neg: options::OPT_fno_force_dwarf_frame);
4984
4985 bool EnableTypeUnits = false;
4986 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
4987 Neg: options::OPT_fno_debug_types_section, Default: false)) {
4988 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4989 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4990 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
4991 ->getAsString(Args)
4992 << T.getTriple();
4993 } else if (checkDebugInfoOption(
4994 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
4995 TC)) {
4996 EnableTypeUnits = true;
4997 CmdArgs.push_back(Elt: "-mllvm");
4998 CmdArgs.push_back(Elt: "-generate-type-units");
4999 }
5000 }
5001
5002 if (const Arg *A =
5003 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
5004 Ids: options::OPT_gno_omit_unreferenced_methods))
5005 (void)checkDebugInfoOption(A, Args, D, TC);
5006 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
5007 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
5008 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5009 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5010 !EnableTypeUnits) {
5011 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
5012 }
5013
5014 // To avoid join/split of directory+filename, the integrated assembler prefers
5015 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5016 // form before DWARF v5.
5017 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
5018 Neg: options::OPT_fno_dwarf_directory_asm,
5019 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5020 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
5021
5022 // Decide how to render forward declarations of template instantiations.
5023 // SCE wants full descriptions, others just get them in the name.
5024 if (ForwardTemplateParams)
5025 CmdArgs.push_back(Elt: "-debug-forward-template-params");
5026
5027 // Do we need to explicitly import anonymous namespaces into the parent
5028 // scope?
5029 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5030 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
5031
5032 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
5033 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5034
5035 // This controls whether or not we perform JustMyCode instrumentation.
5036 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
5037 if (TC.getTriple().isOSBinFormatELF() ||
5038 TC.getTriple().isWindowsMSVCEnvironment()) {
5039 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5040 CmdArgs.push_back(Elt: "-fjmc");
5041 else if (D.IsCLMode())
5042 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5043 << "'/Zi', '/Z7'";
5044 else
5045 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5046 << "-g";
5047 } else {
5048 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
5049 }
5050 }
5051
5052 // Add in -fdebug-compilation-dir if necessary.
5053 const char *DebugCompilationDir =
5054 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
5055
5056 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5057
5058 // Add the output path to the object file for CodeView debug infos.
5059 if (EmitCodeView && Output.isFilename())
5060 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5061 OutputFileName: Output.getFilename());
5062}
5063
5064static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5065 ArgStringList &CmdArgs) {
5066 unsigned RTOptionID = options::OPT__SLASH_MT;
5067
5068 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5069 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5070 // but defining _DEBUG is sticky.
5071 RTOptionID = options::OPT__SLASH_MTd;
5072
5073 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
5074 RTOptionID = A->getOption().getID();
5075
5076 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5077 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5078 .Case(S: "static", Value: options::OPT__SLASH_MT)
5079 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
5080 .Case(S: "dll", Value: options::OPT__SLASH_MD)
5081 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
5082 .Default(Value: options::OPT__SLASH_MT);
5083 }
5084
5085 StringRef FlagForCRT;
5086 switch (RTOptionID) {
5087 case options::OPT__SLASH_MD:
5088 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5089 CmdArgs.push_back(Elt: "-D_DEBUG");
5090 CmdArgs.push_back(Elt: "-D_MT");
5091 CmdArgs.push_back(Elt: "-D_DLL");
5092 FlagForCRT = "--dependent-lib=msvcrt";
5093 break;
5094 case options::OPT__SLASH_MDd:
5095 CmdArgs.push_back(Elt: "-D_DEBUG");
5096 CmdArgs.push_back(Elt: "-D_MT");
5097 CmdArgs.push_back(Elt: "-D_DLL");
5098 FlagForCRT = "--dependent-lib=msvcrtd";
5099 break;
5100 case options::OPT__SLASH_MT:
5101 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
5102 CmdArgs.push_back(Elt: "-D_DEBUG");
5103 CmdArgs.push_back(Elt: "-D_MT");
5104 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5105 FlagForCRT = "--dependent-lib=libcmt";
5106 break;
5107 case options::OPT__SLASH_MTd:
5108 CmdArgs.push_back(Elt: "-D_DEBUG");
5109 CmdArgs.push_back(Elt: "-D_MT");
5110 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
5111 FlagForCRT = "--dependent-lib=libcmtd";
5112 break;
5113 default:
5114 llvm_unreachable("Unexpected option ID.");
5115 }
5116
5117 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5118 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
5119 } else {
5120 CmdArgs.push_back(Elt: FlagForCRT.data());
5121
5122 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5123 // users want. The /Za flag to cl.exe turns this off, but it's not
5124 // implemented in clang.
5125 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
5126 }
5127
5128 // SYCL: Add SYCL runtime library dependency
5129 // SYCL runtime is a required dependency similar to CRT, so we use
5130 // --dependent-lib to embed it in the object file metadata
5131 if (Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) &&
5132 !Args.hasArg(Ids: options::OPT_nolibsycl) &&
5133 !Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
5134
5135 // Determine debug vs release based on CRT flags
5136 bool IsDebugBuild = false;
5137
5138 // Check -fms-runtime-lib=dll_dbg
5139 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
5140 StringRef RuntimeVal = A->getValue();
5141 if (RuntimeVal == "dll_dbg")
5142 IsDebugBuild = true;
5143 }
5144
5145 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5146 // overriding options (e.g., /MDd /MD -> /MD wins)
5147 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group)) {
5148 if (A->getOption().matches(ID: options::OPT__SLASH_MDd))
5149 IsDebugBuild = true;
5150 }
5151
5152 // Add appropriate SYCL runtime library dependency
5153 CmdArgs.push_back(Elt: IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5154 : "--dependent-lib=LLVMSYCL");
5155 }
5156
5157 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5158 // even if the file doesn't actually refer to any of the routines because
5159 // the CRT itself has incomplete dependency markings.
5160 if (TC.getTriple().isWindowsArm64EC())
5161 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
5162}
5163
5164void Clang::ConstructJob(Compilation &C, const JobAction &JA,
5165 const InputInfo &Output, const InputInfoList &Inputs,
5166 const ArgList &Args, const char *LinkingOutput) const {
5167 const auto &TC = getToolChain();
5168 const llvm::Triple &RawTriple = TC.getTriple();
5169 const llvm::Triple &Triple = TC.getEffectiveTriple();
5170 const std::string &TripleStr = Triple.getTriple();
5171
5172 bool KernelOrKext =
5173 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
5174 const Driver &D = TC.getDriver();
5175 ArgStringList CmdArgs;
5176
5177 assert(Inputs.size() >= 1 && "Must have at least one input.");
5178 // CUDA/HIP compilation may have multiple inputs (source file + results of
5179 // device-side compilations). OpenMP device jobs also take the host IR as a
5180 // second input. Module precompilation accepts a list of header files to
5181 // include as part of the module. API extraction accepts a list of header
5182 // files whose API information is emitted in the output. All other jobs are
5183 // expected to have exactly one input. SYCL compilation only expects a
5184 // single input.
5185 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
5186 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
5187 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
5188 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
5189 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
5190 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
5191 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
5192 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
5193 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
5194 JA.isDeviceOffloading(OKind: Action::OFK_Host));
5195 bool IsHostOffloadingAction =
5196 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
5197 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
5198 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()) &&
5199 Args.hasFlag(Pos: options::OPT_offload_new_driver,
5200 Neg: options::OPT_no_offload_new_driver,
5201 Default: C.getActiveOffloadKinds() != Action::OFK_None));
5202
5203 bool IsRDCMode =
5204 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
5205
5206 auto LTOMode = TC.getLTOMode(Args, Kind: JA.getOffloadingDeviceKind());
5207 bool IsUsingLTO = LTOMode != LTOK_None;
5208
5209 // Extract API doesn't have a main input file, so invent a fake one as a
5210 // placeholder.
5211 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5212 "extract-api");
5213
5214 const InputInfo &Input =
5215 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5216
5217 InputInfoList ExtractAPIInputs;
5218 InputInfoList HostOffloadingInputs;
5219 const InputInfo *CudaDeviceInput = nullptr;
5220 const InputInfo *OpenMPDeviceInput = nullptr;
5221 for (const InputInfo &I : Inputs) {
5222 if (&I == &Input || I.getType() == types::TY_Nothing) {
5223 // This is the primary input or contains nothing.
5224 } else if (IsExtractAPI) {
5225 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5226 if (I.getType() != ExpectedInputType) {
5227 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
5228 << I.getFilename() << types::getTypeName(Id: I.getType())
5229 << types::getTypeName(Id: ExpectedInputType);
5230 }
5231 ExtractAPIInputs.push_back(Elt: I);
5232 } else if (IsHostOffloadingAction) {
5233 HostOffloadingInputs.push_back(Elt: I);
5234 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5235 CudaDeviceInput = &I;
5236 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5237 OpenMPDeviceInput = &I;
5238 } else {
5239 llvm_unreachable("unexpectedly given multiple inputs");
5240 }
5241 }
5242
5243 bool IsUEFI = RawTriple.isUEFI();
5244 bool IsIAMCU = RawTriple.isOSIAMCU();
5245
5246 // C++ is not supported for IAMCU.
5247 if (IsIAMCU && types::isCXX(Id: Input.getType()))
5248 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5249
5250 // Invoke ourselves in -cc1 mode.
5251 //
5252 // FIXME: Implement custom jobs for internal actions.
5253 CmdArgs.push_back(Elt: "-cc1");
5254
5255 // Add the "effective" target triple.
5256 CmdArgs.push_back(Elt: "-triple");
5257 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: TripleStr));
5258
5259 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5260
5261 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5262 if (AuxTriple) {
5263 CmdArgs.push_back(Elt: "-aux-triple");
5264 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: AuxTriple->str()));
5265
5266 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5267 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5268 // Windows), we need to pass Windows-specific flags to cc1.
5269 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5270 } else if (JA.getOffloadingHostActiveKinds() != Action::OFK_None) {
5271 // Figure out the device side triple for the host-side compilation.
5272 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5273 ++I) {
5274 Compilation::const_offload_toolchains_range OffloadToolChains =
5275 C.getOffloadToolChains(Kind: static_cast<Action::OffloadKind>(I));
5276 if (OffloadToolChains.first == OffloadToolChains.second)
5277 continue;
5278
5279 const llvm::Triple &DeviceAuxTriple =
5280 OffloadToolChains.first->second->getTriple();
5281 CmdArgs.push_back(Elt: "-aux-triple");
5282 CmdArgs.push_back(Elt: Args.MakeArgStringRef(Str: DeviceAuxTriple.str()));
5283 break;
5284 }
5285 }
5286
5287 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
5288 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
5289 Args.ClaimAllArgs(Id0: options::OPT_MJ);
5290 } else if (const Arg *GenCDBFragment =
5291 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
5292 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
5293 Target: TripleStr, Output, Input, Args);
5294 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
5295 }
5296
5297 if ((getToolChain().getTriple().isAMDGPU() ||
5298 (getToolChain().getTriple().isSPIRV() &&
5299 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5300 // Device side compilation printf
5301 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5302 CmdArgs.push_back(Elt: Args.MakeArgString(
5303 Str: "-mprintf-kind=" +
5304 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5305 // Force compiler error on invalid conversion specifiers
5306 CmdArgs.push_back(
5307 Elt: Args.MakeArgStringRef(Str: "-Werror=format-invalid-specifier"));
5308 }
5309 }
5310
5311 if (IsCuda && !IsCudaDevice) {
5312 // We need to figure out which CUDA version we're compiling for, as that
5313 // determines how we load and launch GPU kernels.
5314 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5315 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5316 assert(CTC && "Expected valid CUDA Toolchain.");
5317 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5318 CmdArgs.push_back(Elt: Args.MakeArgString(
5319 Str: Twine("-target-sdk-version=") +
5320 CudaVersionToString(V: CTC->CudaInstallation.version())));
5321 }
5322
5323 // Optimization level for CodeGen.
5324 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5325 if (A->getOption().matches(ID: options::OPT_O4)) {
5326 CmdArgs.push_back(Elt: "-O3");
5327 D.Diag(DiagID: diag::warn_O4_is_O3);
5328 } else {
5329 A->render(Args, Output&: CmdArgs);
5330 }
5331 }
5332
5333 // Unconditionally claim the printf option now to avoid unused diagnostic.
5334 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5335 PF->claim();
5336
5337 if (IsSYCL) {
5338 if (IsSYCLDevice) {
5339 // We want to compile sycl kernels.
5340 CmdArgs.push_back(Elt: "-fsycl-is-device");
5341
5342 // Set O2 optimization level by default
5343 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5344 CmdArgs.push_back(Elt: "-O2");
5345 } else {
5346 // Add any options that are needed specific to SYCL offload while
5347 // performing the host side compilation.
5348
5349 // Let the front-end host compilation flow know about SYCL offload
5350 // compilation.
5351 CmdArgs.push_back(Elt: "-fsycl-is-host");
5352 }
5353
5354 // Set options for both host and device.
5355 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5356 if (SYCLStdArg) {
5357 SYCLStdArg->render(Args, Output&: CmdArgs);
5358 } else {
5359 // Ensure the default version in SYCL mode is 2020.
5360 CmdArgs.push_back(Elt: "-sycl-std=2020");
5361 }
5362 }
5363
5364 if (Args.hasArg(Ids: options::OPT_fclangir))
5365 CmdArgs.push_back(Elt: "-fclangir");
5366
5367 if (IsOpenMPDevice) {
5368 // We have to pass the triple of the host if compiling for an OpenMP device.
5369 const llvm::Triple &HostTriple =
5370 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5371 CmdArgs.push_back(Elt: "-aux-triple");
5372 CmdArgs.push_back(Elt: HostTriple.str().c_str());
5373 }
5374
5375 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5376 Triple.getArch() == llvm::Triple::thumb)) {
5377 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5378 unsigned Version = 0;
5379 bool Failure =
5380 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5381 if (Failure || Version < 7)
5382 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5383 << TripleStr;
5384 }
5385
5386 // Push all default warning arguments that are specific to
5387 // the given target. These come before user provided warning options
5388 // are provided.
5389 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5390
5391 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5392 if (Triple.isSPIR() || Triple.isSPIRV())
5393 CmdArgs.push_back(Elt: "-Wspir-compat");
5394
5395 // Select the appropriate action.
5396 RewriteKind rewriteKind = RK_None;
5397
5398 bool UnifiedLTO = false;
5399 if (IsUsingLTO) {
5400 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5401 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5402 if (UnifiedLTO)
5403 CmdArgs.push_back(Elt: "-funified-lto");
5404 }
5405
5406 if (Args.hasArg(Ids: options::OPT_fdefined_pointer_subtraction))
5407 CmdArgs.push_back(Elt: "-fdefined-pointer-subtraction");
5408
5409 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5410 // it claims when not running an assembler. Otherwise, clang would emit
5411 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5412 // flags while debugging something. That'd be somewhat inconvenient, and it's
5413 // also inconsistent with most other flags -- we don't warn on
5414 // -ffunction-sections not being used in -E mode either for example, even
5415 // though it's not really used either.
5416 if (!isa<AssembleJobAction>(Val: JA)) {
5417 // The args claimed here should match the args used in
5418 // CollectArgsForIntegratedAssembler().
5419 if (TC.useIntegratedAs()) {
5420 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5421 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5422 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5423 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5424 switch (C.getDefaultToolChain().getArch()) {
5425 case llvm::Triple::arm:
5426 case llvm::Triple::armeb:
5427 case llvm::Triple::thumb:
5428 case llvm::Triple::thumbeb:
5429 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5430 break;
5431 default:
5432 break;
5433 }
5434 }
5435 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5436 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5437 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5438 }
5439
5440 bool IsAMDSPIRVForHIPDevice =
5441 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5442 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5443
5444 if (isa<AnalyzeJobAction>(Val: JA)) {
5445 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5446 CmdArgs.push_back(Elt: "-analyze");
5447 } else if (isa<PreprocessJobAction>(Val: JA)) {
5448 if (Output.getType() == types::TY_Dependencies)
5449 CmdArgs.push_back(Elt: "-Eonly");
5450 else {
5451 CmdArgs.push_back(Elt: "-E");
5452 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5453 !Args.hasArg(Ids: options::OPT_g_Group))
5454 CmdArgs.push_back(Elt: "-P");
5455 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5456 CmdArgs.push_back(Elt: "-fdirectives-only");
5457 }
5458 } else if (isa<AssembleJobAction>(Val: JA)) {
5459 CmdArgs.push_back(Elt: "-emit-obj");
5460
5461 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5462
5463 // Also ignore explicit -force_cpusubtype_ALL option.
5464 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5465 } else if (isa<PrecompileJobAction>(Val: JA)) {
5466 if (JA.getType() == types::TY_Nothing)
5467 CmdArgs.push_back(Elt: "-fsyntax-only");
5468 else if (JA.getType() == types::TY_ModuleFile) {
5469 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi) ||
5470 ((Input.getType() == types::TY_CXXStdModule ||
5471 Input.getType() == types::TY_PP_CXXStdModule) &&
5472 !Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi)))
5473 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5474 else
5475 CmdArgs.push_back(Elt: "-emit-module-interface");
5476 } else if (JA.getType() == types::TY_HeaderUnit)
5477 CmdArgs.push_back(Elt: "-emit-header-unit");
5478 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5479 CmdArgs.push_back(Elt: "-emit-pch");
5480 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5481 CmdArgs.push_back(Elt: "-verify-pch");
5482 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5483 assert(JA.getType() == types::TY_API_INFO &&
5484 "Extract API actions must generate a API information.");
5485 CmdArgs.push_back(Elt: "-extract-api");
5486
5487 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5488 PrettySGFArg->render(Args, Output&: CmdArgs);
5489
5490 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5491
5492 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5493 ProductNameArg->render(Args, Output&: CmdArgs);
5494 if (Arg *ExtractAPIIgnoresFileArg =
5495 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5496 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5497 if (Arg *EmitExtensionSymbolGraphs =
5498 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5499 if (!SymbolGraphDirArg)
5500 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5501
5502 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5503 }
5504 if (SymbolGraphDirArg)
5505 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5506 } else {
5507 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5508 "Invalid action for clang tool.");
5509 if (JA.getType() == types::TY_Nothing) {
5510 CmdArgs.push_back(Elt: "-fsyntax-only");
5511 } else if (JA.getType() == types::TY_LLVM_IR ||
5512 JA.getType() == types::TY_LTO_IR) {
5513 CmdArgs.push_back(Elt: "-emit-llvm");
5514 } else if (JA.getType() == types::TY_LLVM_BC ||
5515 JA.getType() == types::TY_LTO_BC) {
5516 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5517 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5518 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5519 CmdArgs.push_back(Elt: "-emit-llvm");
5520 } else {
5521 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5522 }
5523 } else if (JA.getType() == types::TY_IFS ||
5524 JA.getType() == types::TY_IFS_CPP) {
5525 StringRef ArgStr =
5526 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5527 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5528 : "ifs-v1";
5529 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5530 CmdArgs.push_back(
5531 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr));
5532 } else if (JA.getType() == types::TY_PP_Asm) {
5533 CmdArgs.push_back(Elt: "-S");
5534 } else if (JA.getType() == types::TY_AST) {
5535 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5536 CmdArgs.push_back(Elt: "-emit-pch");
5537 } else if (JA.getType() == types::TY_ModuleFile) {
5538 CmdArgs.push_back(Elt: "-module-file-info");
5539 } else if (JA.getType() == types::TY_RewrittenObjC) {
5540 CmdArgs.push_back(Elt: "-rewrite-objc");
5541 rewriteKind = RK_NonFragile;
5542 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5543 CmdArgs.push_back(Elt: "-rewrite-objc");
5544 rewriteKind = RK_Fragile;
5545 } else if (JA.getType() == types::TY_CIR) {
5546 CmdArgs.push_back(Elt: "-emit-cir");
5547 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5548 CmdArgs.push_back(Elt: "-emit-obj");
5549 } else {
5550 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5551 }
5552
5553 // Preserve use-list order by default when emitting bitcode, so that
5554 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5555 // same result as running passes here. For LTO, we don't need to preserve
5556 // the use-list order, since serialization to bitcode is part of the flow.
5557 if (JA.getType() == types::TY_LLVM_BC)
5558 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5559
5560 if (IsUsingLTO) {
5561 const Arg *LTOArg = Args.getLastArg(Ids: options::OPT_foffload_lto,
5562 Ids: options::OPT_foffload_lto_EQ);
5563 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
5564 !Args.hasFlag(Pos: options::OPT_offload_new_driver,
5565 Neg: options::OPT_no_offload_new_driver,
5566 Default: C.getActiveOffloadKinds() != Action::OFK_None) &&
5567 !Triple.isAMDGPU() && !Triple.isSPIRV()) {
5568 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5569 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5570 << Triple.getTriple();
5571 } else if (Triple.isNVPTX() && !IsRDCMode &&
5572 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5573 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5574 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5575 << "-fno-gpu-rdc";
5576 } else {
5577 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5578 CmdArgs.push_back(Elt: Args.MakeArgString(
5579 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5580 // PS4 uses the legacy LTO API, which does not support some of the
5581 // features enabled by -flto-unit.
5582 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5583 CmdArgs.push_back(Elt: "-flto-unit");
5584 }
5585 }
5586 }
5587
5588 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5589
5590 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5591 if (!types::isLLVMIR(Id: Input.getType()))
5592 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5593 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5594 }
5595
5596 if (Triple.isPPC())
5597 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5598 Neg: options::OPT_mno_regnames);
5599
5600 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5601 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5602
5603 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5604 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5605
5606 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5607 Ids: options::OPT_fmemory_profile_EQ,
5608 Ids: options::OPT_fno_memory_profile);
5609 if (MemProfArg &&
5610 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5611 MemProfArg->render(Args, Output&: CmdArgs);
5612
5613 if (auto *MemProfUseArg =
5614 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5615 if (MemProfArg)
5616 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5617 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5618 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5619 Ids: options::OPT_fprofile_generate_EQ))
5620 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5621 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5622 MemProfUseArg->render(Args, Output&: CmdArgs);
5623 }
5624
5625 // Embed-bitcode option.
5626 // Only white-listed flags below are allowed to be embedded.
5627 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5628 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5629 // Add flags implied by -fembed-bitcode.
5630 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5631 // Disable all llvm IR level optimizations.
5632 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5633
5634 // Render target options.
5635 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
5636 DeviceOffloadKind: JA.getOffloadingDeviceKind());
5637
5638 // reject options that shouldn't be supported in bitcode
5639 // also reject kernel/kext
5640 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5641 options::OPT_mkernel,
5642 options::OPT_fapple_kext,
5643 options::OPT_ffunction_sections,
5644 options::OPT_fno_function_sections,
5645 options::OPT_fdata_sections,
5646 options::OPT_fno_data_sections,
5647 options::OPT_fbasic_block_sections_EQ,
5648 options::OPT_funique_internal_linkage_names,
5649 options::OPT_fno_unique_internal_linkage_names,
5650 options::OPT_funique_section_names,
5651 options::OPT_fno_unique_section_names,
5652 options::OPT_funique_basic_block_section_names,
5653 options::OPT_fno_unique_basic_block_section_names,
5654 options::OPT_mrestrict_it,
5655 options::OPT_mno_restrict_it,
5656 options::OPT_mstackrealign,
5657 options::OPT_mno_stackrealign,
5658 options::OPT_mstack_alignment,
5659 options::OPT_mcmodel_EQ,
5660 options::OPT_mlong_calls,
5661 options::OPT_mno_long_calls,
5662 options::OPT_ggnu_pubnames,
5663 options::OPT_gdwarf_aranges,
5664 options::OPT_fdebug_types_section,
5665 options::OPT_fno_debug_types_section,
5666 options::OPT_fdwarf_directory_asm,
5667 options::OPT_fno_dwarf_directory_asm,
5668 options::OPT_mrelax_all,
5669 options::OPT_mno_relax_all,
5670 options::OPT_ftrap_function_EQ,
5671 options::OPT_ffixed_r9,
5672 options::OPT_mfix_cortex_a53_835769,
5673 options::OPT_mno_fix_cortex_a53_835769,
5674 options::OPT_ffixed_x18,
5675 options::OPT_mglobal_merge,
5676 options::OPT_mno_global_merge,
5677 options::OPT_mred_zone,
5678 options::OPT_mno_red_zone,
5679 options::OPT_Wa_COMMA,
5680 options::OPT_Xassembler,
5681 options::OPT_mllvm,
5682 options::OPT_mmlir,
5683 };
5684 for (const auto &A : Args)
5685 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5686 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5687
5688 // Render the CodeGen options that need to be passed.
5689 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5690 Neg: options::OPT_fno_optimize_sibling_calls);
5691
5692 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5693 CmdArgs, JA);
5694
5695 // Render ABI arguments
5696 switch (TC.getArch()) {
5697 default: break;
5698 case llvm::Triple::arm:
5699 case llvm::Triple::armeb:
5700 case llvm::Triple::thumbeb:
5701 RenderARMABI(D, Triple, Args, CmdArgs);
5702 break;
5703 case llvm::Triple::aarch64:
5704 case llvm::Triple::aarch64_32:
5705 case llvm::Triple::aarch64_be:
5706 RenderAArch64ABI(Triple, Args, CmdArgs);
5707 break;
5708 }
5709
5710 // Input/Output file.
5711 if (Output.getType() == types::TY_Dependencies) {
5712 // Handled with other dependency code.
5713 } else if (Output.isFilename()) {
5714 CmdArgs.push_back(Elt: "-o");
5715 CmdArgs.push_back(Elt: Output.getFilename());
5716 } else {
5717 assert(Output.isNothing() && "Input output.");
5718 }
5719
5720 for (const auto &II : Inputs) {
5721 addDashXForInput(Args, Input: II, CmdArgs);
5722 if (II.isFilename())
5723 CmdArgs.push_back(Elt: II.getFilename());
5724 else
5725 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5726 }
5727
5728 C.addCommand(Cmd: std::make_unique<Command>(
5729 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getDriverProgramPath(),
5730 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5731 return;
5732 }
5733
5734 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5735 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5736
5737 // We normally speed up the clang process a bit by skipping destructors at
5738 // exit, but when we're generating diagnostics we can rely on some of the
5739 // cleanup.
5740 if (!C.isForDiagnostics())
5741 CmdArgs.push_back(Elt: "-disable-free");
5742 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5743
5744#ifdef NDEBUG
5745 const bool IsAssertBuild = false;
5746#else
5747 const bool IsAssertBuild = true;
5748#endif
5749
5750 // Disable the verification pass in no-asserts builds unless otherwise
5751 // specified.
5752 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5753 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5754 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5755 }
5756
5757 // Discard value names in no-asserts builds unless otherwise specified.
5758 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5759 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5760 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5761 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5762 return types::isLLVMIR(Id: II.getType());
5763 })) {
5764 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5765 }
5766 CmdArgs.push_back(Elt: "-discard-value-names");
5767 }
5768
5769 // Set the main file name, so that debug info works even with
5770 // -save-temps.
5771 CmdArgs.push_back(Elt: "-main-file-name");
5772 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5773
5774 // Some flags which affect the language (via preprocessor
5775 // defines).
5776 if (Args.hasArg(Ids: options::OPT_static))
5777 CmdArgs.push_back(Elt: "-static-define");
5778
5779 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5780
5781 if (Args.hasArg(Ids: options::OPT_municode))
5782 CmdArgs.push_back(Elt: "-DUNICODE");
5783
5784 if (isa<AnalyzeJobAction>(Val: JA))
5785 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5786
5787 if (isa<AnalyzeJobAction>(Val: JA) ||
5788 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5789 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5790
5791 // Enable compatilibily mode to avoid analyzer-config related errors.
5792 // Since we can't access frontend flags through hasArg, let's manually iterate
5793 // through them.
5794 bool FoundAnalyzerConfig = false;
5795 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5796 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5797 FoundAnalyzerConfig = true;
5798 break;
5799 }
5800 if (!FoundAnalyzerConfig)
5801 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5802 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5803 FoundAnalyzerConfig = true;
5804 break;
5805 }
5806 if (FoundAnalyzerConfig)
5807 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5808
5809 CheckCodeGenerationOptions(D, Args);
5810
5811 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5812 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5813 if (FunctionAlignment) {
5814 CmdArgs.push_back(Elt: "-function-alignment");
5815 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(FunctionAlignment)));
5816 }
5817
5818 if (const Arg *A =
5819 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5820 unsigned Value = 0;
5821 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5822 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5823 << A->getAsString(Args) << A->getValue();
5824 else if (!llvm::isPowerOf2_32(Value))
5825 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5826 << A->getAsString(Args) << A->getValue();
5827
5828 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5829 Twine(std::min(a: Value, b: 65536u))));
5830 }
5831
5832 // We support -falign-loops=N where N is a power of 2. GCC supports more
5833 // forms.
5834 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5835 unsigned Value = 0;
5836 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5837 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5838 << A->getAsString(Args) << A->getValue();
5839 else if (Value & (Value - 1))
5840 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5841 << A->getAsString(Args) << A->getValue();
5842 // Treat =0 as unspecified (use the target preference).
5843 if (Value)
5844 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5845 Twine(std::min(a: Value, b: 65536u))));
5846 }
5847
5848 if (Triple.isOSzOS()) {
5849 // On z/OS some of the system header feature macros need to
5850 // be defined to enable most cross platform projects to build
5851 // successfully. Ths include the libc++ library. A
5852 // complicating factor is that users can define these
5853 // macros to the same or different values. We need to add
5854 // the definition for these macros to the compilation command
5855 // if the user hasn't already defined them.
5856
5857 auto findMacroDefinition = [&](const std::string &Macro) {
5858 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5859 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5860 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5861 });
5862 };
5863
5864 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5865 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5866 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5867 // _OPEN_DEFAULT is required for XL compat
5868 if (!findMacroDefinition("_OPEN_DEFAULT"))
5869 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5870 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5871 // _XOPEN_SOURCE=600 is required for libcxx.
5872 if (!findMacroDefinition("_XOPEN_SOURCE"))
5873 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5874 }
5875 }
5876
5877 llvm::Reloc::Model RelocationModel;
5878 unsigned PICLevel;
5879 bool IsPIE;
5880 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5881 Arg *LastPICDataRelArg =
5882 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5883 Ids: options::OPT_mpic_data_is_text_relative);
5884 bool NoPICDataIsTextRelative = false;
5885 if (LastPICDataRelArg) {
5886 if (LastPICDataRelArg->getOption().matches(
5887 ID: options::OPT_mno_pic_data_is_text_relative)) {
5888 NoPICDataIsTextRelative = true;
5889 if (!PICLevel)
5890 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5891 << "-mno-pic-data-is-text-relative"
5892 << "-fpic/-fpie";
5893 }
5894 if (!Triple.isSystemZ())
5895 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5896 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5897 : "-mpic-data-is-text-relative")
5898 << RawTriple.str();
5899 }
5900
5901 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5902 RelocationModel == llvm::Reloc::ROPI_RWPI;
5903 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5904 RelocationModel == llvm::Reloc::ROPI_RWPI;
5905
5906 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5907 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5908 if (IsROPI)
5909 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5910 if (IsRWPI)
5911 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5912 }
5913
5914 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5915 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5916 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5917
5918 const char *RMName = RelocationModelName(Model: RelocationModel);
5919 if (RMName) {
5920 CmdArgs.push_back(Elt: "-mrelocation-model");
5921 CmdArgs.push_back(Elt: RMName);
5922 }
5923 if (PICLevel > 0) {
5924 CmdArgs.push_back(Elt: "-pic-level");
5925 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5926 if (IsPIE)
5927 CmdArgs.push_back(Elt: "-pic-is-pie");
5928 if (NoPICDataIsTextRelative)
5929 CmdArgs.push_back(Elt: "-mcmodel=medium");
5930 }
5931
5932 if (RelocationModel == llvm::Reloc::ROPI ||
5933 RelocationModel == llvm::Reloc::ROPI_RWPI)
5934 CmdArgs.push_back(Elt: "-fropi");
5935 if (RelocationModel == llvm::Reloc::RWPI ||
5936 RelocationModel == llvm::Reloc::ROPI_RWPI)
5937 CmdArgs.push_back(Elt: "-frwpi");
5938
5939 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5940 CmdArgs.push_back(Elt: "-meabi");
5941 CmdArgs.push_back(Elt: A->getValue());
5942 }
5943
5944 // -fsemantic-interposition is forwarded to CC1: set the
5945 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5946 // make default visibility external linkage definitions dso_preemptable.
5947 //
5948 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5949 // aliases (make default visibility external linkage definitions dso_local).
5950 // This is the CC1 default for ELF to match COFF/Mach-O.
5951 //
5952 // Otherwise use Clang's traditional behavior: like
5953 // -fno-semantic-interposition but local aliases are not used. So references
5954 // can be interposed if not optimized out.
5955 if (Triple.isOSBinFormatELF()) {
5956 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5957 Ids: options::OPT_fno_semantic_interposition);
5958 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5959 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5960 bool SupportsLocalAlias =
5961 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5962 if (!A)
5963 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5964 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5965 A->render(Args, Output&: CmdArgs);
5966 else if (!SupportsLocalAlias)
5967 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5968 }
5969 }
5970
5971 {
5972 std::string Model;
5973 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
5974 if (!TC.isThreadModelSupported(Model: A->getValue()))
5975 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
5976 << A->getValue() << A->getAsString(Args);
5977 Model = A->getValue();
5978 } else
5979 Model = TC.getThreadModel();
5980 if (Model != "posix") {
5981 CmdArgs.push_back(Elt: "-mthread-model");
5982 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5983 }
5984 }
5985
5986 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
5987 StringRef Name = A->getValue();
5988 if (Name == "SVML") {
5989 if (Triple.getArch() != llvm::Triple::x86 &&
5990 Triple.getArch() != llvm::Triple::x86_64)
5991 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5992 << Name << Triple.getArchName();
5993 } else if (Name == "AMDLIBM") {
5994 if (Triple.getArch() != llvm::Triple::x86 &&
5995 Triple.getArch() != llvm::Triple::x86_64)
5996 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5997 << Name << Triple.getArchName();
5998 } else if (Name == "libmvec") {
5999 if (Triple.getArch() != llvm::Triple::x86 &&
6000 Triple.getArch() != llvm::Triple::x86_64 &&
6001 Triple.getArch() != llvm::Triple::aarch64 &&
6002 Triple.getArch() != llvm::Triple::aarch64_be)
6003 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6004 << Name << Triple.getArchName();
6005 } else if (Name == "SLEEF" || Name == "ArmPL") {
6006 if (Triple.getArch() != llvm::Triple::aarch64 &&
6007 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6008 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6009 << Name << Triple.getArchName();
6010 }
6011 A->render(Args, Output&: CmdArgs);
6012 }
6013
6014 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
6015 Neg: options::OPT_fno_merge_all_constants, Default: false))
6016 CmdArgs.push_back(Elt: "-fmerge-all-constants");
6017
6018 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
6019 Neg: options::OPT_fno_delete_null_pointer_checks);
6020
6021 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
6022 Neg: options::OPT_fno_lifetime_dse);
6023
6024 // LLVM Code Generator Options.
6025
6026 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
6027 if (!Triple.isOSAIX() || Triple.isPPC32())
6028 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6029 << A->getSpelling() << RawTriple.str();
6030 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
6031 }
6032
6033 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
6034 // Emit the unsupported option error until the Clang's library integration
6035 // support for 128-bit long double is available for AIX.
6036 if (Triple.isOSAIX())
6037 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6038 << A->getSpelling() << RawTriple.str();
6039 }
6040
6041 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
6042 StringRef V = A->getValue(), V1 = V;
6043 unsigned Size;
6044 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
6045 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6046 << V << A->getOption().getName();
6047 else
6048 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
6049 }
6050
6051 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
6052 Neg: options::OPT_fno_jump_tables);
6053 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
6054 Neg: options::OPT_fno_profile_sample_accurate);
6055 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
6056 Neg: options::OPT_fno_preserve_as_comments);
6057
6058 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
6059 CmdArgs.push_back(Elt: "-mregparm");
6060 CmdArgs.push_back(Elt: A->getValue());
6061 }
6062
6063 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
6064 Ids: options::OPT_msvr4_struct_return)) {
6065 if (!TC.getTriple().isPPC32()) {
6066 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6067 << A->getSpelling() << RawTriple.str();
6068 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
6069 CmdArgs.push_back(Elt: "-maix-struct-return");
6070 } else {
6071 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6072 CmdArgs.push_back(Elt: "-msvr4-struct-return");
6073 }
6074 }
6075
6076 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
6077 Ids: options::OPT_freg_struct_return)) {
6078 if (TC.getArch() != llvm::Triple::x86) {
6079 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6080 << A->getSpelling() << RawTriple.str();
6081 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
6082 CmdArgs.push_back(Elt: "-fpcc-struct-return");
6083 } else {
6084 assert(A->getOption().matches(options::OPT_freg_struct_return));
6085 CmdArgs.push_back(Elt: "-freg-struct-return");
6086 }
6087 }
6088
6089 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
6090 if (Triple.getArch() == llvm::Triple::m68k)
6091 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
6092 else
6093 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
6094 }
6095
6096 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
6097 // enable-matrix is needed by both the LangOpts and by LLVM.
6098 CmdArgs.push_back(Elt: "-fenable-matrix");
6099 CmdArgs.push_back(Elt: "-mllvm");
6100 CmdArgs.push_back(Elt: "-enable-matrix");
6101 // Only handle default layout if matrix is enabled
6102 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
6103 StringRef Val = A->getValue();
6104 if (Val == "row-major" || Val == "column-major") {
6105 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
6106 CmdArgs.push_back(Elt: "-mllvm");
6107 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
6108
6109 } else {
6110 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6111 }
6112 }
6113 }
6114
6115 CodeGenOptions::FramePointerKind FPKeepKind =
6116 getFramePointerKind(Args, Triple: RawTriple);
6117 const char *FPKeepKindStr = nullptr;
6118 switch (FPKeepKind) {
6119 case CodeGenOptions::FramePointerKind::None:
6120 FPKeepKindStr = "-mframe-pointer=none";
6121 break;
6122 case CodeGenOptions::FramePointerKind::Reserved:
6123 FPKeepKindStr = "-mframe-pointer=reserved";
6124 break;
6125 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
6126 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6127 break;
6128 case CodeGenOptions::FramePointerKind::NonLeaf:
6129 FPKeepKindStr = "-mframe-pointer=non-leaf";
6130 break;
6131 case CodeGenOptions::FramePointerKind::All:
6132 FPKeepKindStr = "-mframe-pointer=all";
6133 break;
6134 }
6135 assert(FPKeepKindStr && "unknown FramePointerKind");
6136 CmdArgs.push_back(Elt: FPKeepKindStr);
6137
6138 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
6139 Neg: options::OPT_fno_zero_initialized_in_bss);
6140
6141 bool OFastEnabled = isOptimizationLevelFast(Args);
6142 if (Args.hasArg(Ids: options::OPT_Ofast))
6143 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
6144 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6145 // enabled. This alias option is being used to simplify the hasFlag logic.
6146 OptSpecifier StrictAliasingAliasOption =
6147 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6148 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6149 // doesn't do any TBAA.
6150 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
6151 Neg: options::OPT_fno_strict_aliasing,
6152 Default: !IsWindowsMSVC && !IsUEFI))
6153 CmdArgs.push_back(Elt: "-relaxed-aliasing");
6154 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
6155 Default: false))
6156 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
6157 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
6158 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
6159 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
6160
6161 if (Arg *A = Args.getLastArg(Ids: options::OPT_fstrict_bool,
6162 Ids: options::OPT_fno_strict_bool,
6163 Ids: options::OPT_fno_strict_bool_EQ)) {
6164 StringRef BFM = "";
6165 if (A->getOption().matches(ID: options::OPT_fstrict_bool))
6166 BFM = "strict";
6167 else if (A->getOption().matches(ID: options::OPT_fno_strict_bool))
6168 BFM = "nonstrict";
6169 else if (A->getValue() == StringRef("truncate"))
6170 BFM = "truncate";
6171 else if (A->getValue() == StringRef("nonzero"))
6172 BFM = "nonzero";
6173 else
6174 D.Diag(DiagID: diag::err_drv_invalid_value)
6175 << A->getAsString(Args) << A->getValue();
6176 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-load-bool-from-mem=" + BFM));
6177 } else if (KernelOrKext) {
6178 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6179 CmdArgs.push_back(Elt: "-load-bool-from-mem=truncate");
6180 }
6181
6182 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
6183 Neg: options::OPT_fno_strict_enums);
6184 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
6185 Neg: options::OPT_fno_strict_return);
6186 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
6187 Neg: options::OPT_fno_allow_editor_placeholders);
6188 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
6189 Neg: options::OPT_fno_strict_vtable_pointers);
6190 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
6191 Neg: options::OPT_fno_force_emit_vtables);
6192 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
6193 Neg: options::OPT_fno_optimize_sibling_calls);
6194 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
6195 Neg: options::OPT_fno_escaping_block_tail_calls);
6196
6197 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
6198 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
6199
6200 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6201 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6202
6203 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6204 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6205
6206 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
6207 Ids: options::OPT_fno_disable_block_signature_string);
6208
6209 // Handle segmented stacks.
6210 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
6211 Neg: options::OPT_fno_split_stack);
6212
6213 // -fprotect-parens=0 is default.
6214 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
6215 Neg: options::OPT_fno_protect_parens, Default: false))
6216 CmdArgs.push_back(Elt: "-fprotect-parens");
6217
6218 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6219
6220 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
6221 Neg: options::OPT_fno_atomic_remote_memory);
6222 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
6223 Neg: options::OPT_fno_atomic_fine_grained_memory);
6224 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
6225 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
6226
6227 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
6228 const llvm::Triple::ArchType Arch = TC.getArch();
6229 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6230 StringRef V = A->getValue();
6231 if (V == "64")
6232 CmdArgs.push_back(Elt: "-fextend-arguments=64");
6233 else if (V != "32")
6234 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6235 << A->getValue() << A->getOption().getName();
6236 } else
6237 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6238 << A->getOption().getName() << TripleStr;
6239 }
6240
6241 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
6242 if (TC.getArch() == llvm::Triple::avr)
6243 A->render(Args, Output&: CmdArgs);
6244 else
6245 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6246 << A->getAsString(Args) << TripleStr;
6247 }
6248
6249 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
6250 if (TC.getTriple().isX86())
6251 A->render(Args, Output&: CmdArgs);
6252 else if (TC.getTriple().isPPC() &&
6253 (A->getOption().getID() != options::OPT_mlong_double_80))
6254 A->render(Args, Output&: CmdArgs);
6255 else
6256 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6257 << A->getAsString(Args) << TripleStr;
6258 }
6259
6260 // Decide whether to use verbose asm. Verbose assembly is the default on
6261 // toolchains which have the integrated assembler on by default.
6262 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6263 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
6264 Default: IsIntegratedAssemblerDefault))
6265 CmdArgs.push_back(Elt: "-fno-verbose-asm");
6266
6267 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6268 // use that to indicate the MC default in the backend.
6269 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
6270 StringRef V = A->getValue();
6271 unsigned Num;
6272 if (V == "none")
6273 A->render(Args, Output&: CmdArgs);
6274 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
6275 (V.empty() || (V.consume_front(Prefix: ".") &&
6276 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
6277 A->render(Args, Output&: CmdArgs);
6278 else
6279 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6280 << A->getValue() << A->getOption().getName();
6281 }
6282
6283 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6284 // option to disable integrated-as explicitly.
6285 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
6286 CmdArgs.push_back(Elt: "-no-integrated-as");
6287
6288 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
6289 CmdArgs.push_back(Elt: "-mdebug-pass");
6290 CmdArgs.push_back(Elt: "Structure");
6291 }
6292 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
6293 CmdArgs.push_back(Elt: "-mdebug-pass");
6294 CmdArgs.push_back(Elt: "Arguments");
6295 }
6296
6297 // Enable -mconstructor-aliases except on darwin, where we have to work around
6298 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6299 // code, where aliases aren't supported.
6300 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6301 CmdArgs.push_back(Elt: "-mconstructor-aliases");
6302
6303 // Darwin's kernel doesn't support guard variables; just die if we
6304 // try to use them.
6305 if (KernelOrKext && RawTriple.isOSDarwin())
6306 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6307
6308 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6309 Ids: options::OPT_mno_ms_bitfields)) {
6310 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6311 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6312 else
6313 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6314 }
6315
6316 if (Triple.isOSCygMing()) {
6317 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6318 Neg: options::OPT_fno_auto_import);
6319 }
6320
6321 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6322 Default: Triple.isX86() && IsWindowsMSVC))
6323 CmdArgs.push_back(Elt: "-fms-volatile");
6324
6325 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6326 // defaults to -fno-direct-access-external-data. Pass the option if different
6327 // from the default.
6328 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6329 Ids: options::OPT_fno_direct_access_external_data)) {
6330 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6331 (PICLevel == 0))
6332 A->render(Args, Output&: CmdArgs);
6333 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6334 // Some targets default to -fno-direct-access-external-data even for
6335 // -fno-pic.
6336 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6337 }
6338
6339 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6340 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6341
6342 // -fhosted is default.
6343 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6344 // use Freestanding.
6345 bool Freestanding =
6346 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6347 KernelOrKext;
6348 if (Freestanding)
6349 CmdArgs.push_back(Elt: "-ffreestanding");
6350
6351 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6352
6353 BoundArch OffloadArch = JA.getOffloadingArch();
6354 auto SanitizeArgs =
6355 TC.getSanitizerArgs(JobArgs: Args, BA: OffloadArch, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6356 Args.AddLastArg(Output&: CmdArgs,
6357 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6358
6359 // This is a coarse approximation of what llvm-gcc actually does, both
6360 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6361 // complicated ways.
6362 bool IsAsyncUnwindTablesDefault =
6363 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6364 bool IsSyncUnwindTablesDefault =
6365 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6366
6367 bool AsyncUnwindTables = Args.hasFlag(
6368 Pos: options::OPT_fasynchronous_unwind_tables,
6369 Neg: options::OPT_fno_asynchronous_unwind_tables,
6370 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6371 !Freestanding);
6372 bool UnwindTables =
6373 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6374 Default: IsSyncUnwindTablesDefault && !Freestanding);
6375 if (AsyncUnwindTables)
6376 CmdArgs.push_back(Elt: "-funwind-tables=2");
6377 else if (UnwindTables)
6378 CmdArgs.push_back(Elt: "-funwind-tables=1");
6379
6380 // Sframe unwind tables are independent of the other types. Although also
6381 // defined for aarch64, only x86_64 support is implemented at the moment.
6382 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6383 if (Triple.isOSBinFormatELF() && Triple.isX86())
6384 CmdArgs.push_back(Elt: "--gsframe");
6385 else
6386 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6387 << A->getOption().getName() << TripleStr;
6388 }
6389
6390 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6391 // `--gpu-use-aux-triple-only` is specified.
6392 if (AuxTriple && !Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only)) {
6393 const ArgList &HostArgs =
6394 C.getArgsForToolChain(TC: nullptr, BA: BoundArch(), DeviceOffloadKind: Action::OFK_None);
6395 std::string HostCPU = getCPUName(D, Args: HostArgs, T: *AuxTriple, /*FromAs*/ false);
6396 if (!HostCPU.empty()) {
6397 CmdArgs.push_back(Elt: "-aux-target-cpu");
6398 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6399 }
6400 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6401 /*ForAS*/ false, /*IsAux*/ true);
6402 }
6403
6404 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, BA: JA.getOffloadingArch(),
6405 DeviceOffloadKind: JA.getOffloadingDeviceKind());
6406
6407 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6408
6409 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6410 StringRef Value = A->getValue();
6411 unsigned TLSSize = 0;
6412 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6413 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6414 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6415 << A->getOption().getName() << TripleStr;
6416 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6417 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6418 << A->getOption().getName() << Value;
6419 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6420 }
6421
6422 if (isTLSDESCEnabled(TC, Args))
6423 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6424
6425 // Add the target cpu
6426 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6427 if (!CPU.empty()) {
6428 CmdArgs.push_back(Elt: "-target-cpu");
6429 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6430 }
6431
6432 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6433
6434 // Add clang-cl arguments.
6435 types::ID InputType = Input.getType();
6436 if (D.IsCLMode())
6437 AddClangCLArgs(Args, InputType, CmdArgs);
6438
6439 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6440 llvm::codegenoptions::NoDebugInfo;
6441 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6442 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6443 DebugInfoKind, DwarfFission);
6444
6445 // Add the split debug info name to the command lines here so we
6446 // can propagate it to the backend.
6447 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6448 (TC.getTriple().isOSBinFormatELF() ||
6449 TC.getTriple().isOSBinFormatWasm() ||
6450 TC.getTriple().isOSBinFormatCOFF()) &&
6451 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6452 isa<BackendJobAction>(Val: JA));
6453 if (SplitDWARF) {
6454 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6455 CmdArgs.push_back(Elt: "-split-dwarf-file");
6456 CmdArgs.push_back(Elt: SplitDWARFOut);
6457 if (DwarfFission == DwarfFissionKind::Split) {
6458 CmdArgs.push_back(Elt: "-split-dwarf-output");
6459 CmdArgs.push_back(Elt: SplitDWARFOut);
6460 }
6461 }
6462
6463 // Pass the linker version in use.
6464 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6465 CmdArgs.push_back(Elt: "-target-linker-version");
6466 CmdArgs.push_back(Elt: A->getValue());
6467 }
6468
6469 // Explicitly error on some things we know we don't support and can't just
6470 // ignore.
6471 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6472 Arg *Unsupported;
6473 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6474 TC.getArch() == llvm::Triple::x86) {
6475 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6476 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6477 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6478 << Unsupported->getOption().getName();
6479 }
6480 // The faltivec option has been superseded by the maltivec option.
6481 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6482 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6483 << Unsupported->getOption().getName()
6484 << "please use -maltivec and include altivec.h explicitly";
6485 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6486 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6487 << Unsupported->getOption().getName() << "please use -mno-altivec";
6488 }
6489
6490 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6491
6492 if (Args.getLastArg(Ids: options::OPT_H)) {
6493 CmdArgs.push_back(Elt: "-H");
6494 CmdArgs.push_back(Elt: "-sys-header-deps");
6495 }
6496 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6497
6498 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6499 CmdArgs.push_back(Elt: "-header-include-file");
6500 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6501 ? D.CCPrintHeadersFilename.c_str()
6502 : "-");
6503 CmdArgs.push_back(Elt: "-sys-header-deps");
6504 CmdArgs.push_back(Elt: Args.MakeArgString(
6505 Str: "-header-include-format=" +
6506 Twine(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6507 CmdArgs.push_back(Elt: Args.MakeArgString(
6508 Str: "-header-include-filtering=" +
6509 Twine(headerIncludeFilteringKindToString(K: D.CCPrintHeadersFiltering))));
6510 }
6511 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6512 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6513
6514 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6515 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6516 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6517 ? D.CCLogDiagnosticsFilename.c_str()
6518 : "-");
6519 }
6520
6521 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6522 // crashes.
6523 if (D.CCGenDiagnostics)
6524 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6525
6526 // Allow backend to put its diagnostic files in the same place as frontend
6527 // crash diagnostics files.
6528 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6529 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6530 CmdArgs.push_back(Elt: "-mllvm");
6531 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6532 }
6533
6534 addSeparateSectionFlags(Triple, Args, CmdArgs);
6535
6536 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6537 Ids: options::OPT_fno_basic_block_address_map)) {
6538 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6539 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6540 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6541 A->render(Args, Output&: CmdArgs);
6542 } else {
6543 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6544 << A->getAsString(Args) << TripleStr;
6545 }
6546 }
6547
6548 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6549 StringRef Val = A->getValue();
6550 if (Val == "labels") {
6551 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6552 << A->getAsString(Args) << /*hasReplacement=*/true
6553 << "-fbasic-block-address-map";
6554 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6555 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6556 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6557 D.Diag(DiagID: diag::err_drv_invalid_value)
6558 << A->getAsString(Args) << A->getValue();
6559 else
6560 A->render(Args, Output&: CmdArgs);
6561 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6562 // "all" is not supported on AArch64 since branch relaxation creates new
6563 // basic blocks for some cross-section branches.
6564 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6565 D.Diag(DiagID: diag::err_drv_invalid_value)
6566 << A->getAsString(Args) << A->getValue();
6567 else
6568 A->render(Args, Output&: CmdArgs);
6569 } else if (Triple.isNVPTX()) {
6570 // Do not pass the option to the GPU compilation. We still want it enabled
6571 // for the host-side compilation, so seeing it here is not an error.
6572 } else if (Val != "none") {
6573 // =none is allowed everywhere. It's useful for overriding the option
6574 // and is the same as not specifying the option.
6575 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6576 << A->getAsString(Args) << TripleStr;
6577 }
6578 }
6579
6580 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6581 Neg: options::OPT_fno_unique_section_names);
6582 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6583 Neg: options::OPT_fno_separate_named_sections);
6584 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6585 Neg: options::OPT_fno_unique_internal_linkage_names);
6586 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6587 Neg: options::OPT_fno_unique_basic_block_section_names);
6588
6589 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
6590 Ids: options::OPT_fno_split_machine_functions)) {
6591 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
6592 // This codegen pass is only available on x86 and AArch64 ELF targets.
6593 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6594 A->render(Args, Output&: CmdArgs);
6595 else
6596 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6597 << A->getAsString(Args) << TripleStr;
6598 }
6599 }
6600
6601 if (Arg *A =
6602 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6603 Ids: options::OPT_fno_partition_static_data_sections)) {
6604 if (!A->getOption().matches(
6605 ID: options::OPT_fno_partition_static_data_sections)) {
6606 // This codegen pass is only available on x86 and AArch64 ELF targets.
6607 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6608 A->render(Args, Output&: CmdArgs);
6609 CmdArgs.push_back(Elt: "-mllvm");
6610 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6611 } else
6612 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6613 << A->getAsString(Args) << TripleStr;
6614 }
6615 }
6616
6617 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6618 Ids: options::OPT_finstrument_functions_after_inlining,
6619 Ids: options::OPT_finstrument_function_entry_bare);
6620 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6621 Ids: options::OPT_fno_convergent_functions);
6622
6623 // NVPTX doesn't support PGO or coverage
6624 if (!Triple.isNVPTX())
6625 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6626
6627 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6628
6629 if (getLastProfileSampleUseArg(Args) &&
6630 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6631 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6632 CmdArgs.push_back(Elt: "-mllvm");
6633 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6634 }
6635
6636 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6637 if (RawTriple.isPS() &&
6638 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6639 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6640 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6641 }
6642
6643 // Pass options for controlling the default header search paths.
6644 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6645 CmdArgs.push_back(Elt: "-nostdsysteminc");
6646 CmdArgs.push_back(Elt: "-nobuiltininc");
6647 } else {
6648 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6649 CmdArgs.push_back(Elt: "-nostdsysteminc");
6650 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6651 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6652 }
6653
6654 // Pass the path to compiler resource files.
6655 CmdArgs.push_back(Elt: "-resource-dir");
6656 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6657
6658 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6659
6660 // Add preprocessing options like -I, -D, etc. if we are using the
6661 // preprocessor.
6662 //
6663 // FIXME: Support -fpreprocessed
6664 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6665 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6666
6667 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6668 // that "The compiler can only warn and ignore the option if not recognized".
6669 // When building with ccache, it will pass -D options to clang even on
6670 // preprocessed inputs and configure concludes that -fPIC is not supported.
6671 Args.ClaimAllArgs(Id0: options::OPT_D);
6672
6673 // Warn about ignored options to clang.
6674 for (const Arg *A :
6675 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6676 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6677 A->claim();
6678 }
6679
6680 for (const Arg *A :
6681 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6682 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6683 A->claim();
6684 }
6685
6686 claimNoWarnArgs(Args);
6687
6688 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6689
6690 for (const Arg *A :
6691 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6692 A->claim();
6693 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6694 unsigned WarningNumber;
6695 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6696 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6697 << A->getAsString(Args) << A->getValue();
6698 continue;
6699 }
6700
6701 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6702 CmdArgs.push_back(Elt: Args.MakeArgString(
6703 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6704 }
6705 continue;
6706 }
6707 A->render(Args, Output&: CmdArgs);
6708 }
6709
6710 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6711
6712 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6713 CmdArgs.push_back(Elt: "-pedantic");
6714 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6715 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6716
6717 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6718 Neg: options::OPT_fno_fixed_point);
6719
6720 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6721 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6722
6723 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6724 A->render(Args, Output&: CmdArgs);
6725
6726 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6727 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6728
6729 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6730 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6731
6732 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6733 A->render(Args, Output&: CmdArgs);
6734
6735 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6736 // (-ansi is equivalent to -std=c89 or -std=c++98).
6737 //
6738 // If a std is supplied, only add -trigraphs if it follows the
6739 // option.
6740 bool ImplyVCPPCVer = false;
6741 bool ImplyVCPPCXXVer = false;
6742 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6743 if (Std) {
6744 if (Std->getOption().matches(ID: options::OPT_ansi))
6745 if (types::isCXX(Id: InputType))
6746 CmdArgs.push_back(Elt: "-std=c++98");
6747 else
6748 CmdArgs.push_back(Elt: "-std=c89");
6749 else {
6750 if (IsSYCL) {
6751 const LangStandard *LangStd =
6752 LangStandard::getLangStandardForName(Name: Std->getValue());
6753 if (LangStd) {
6754 // Use of -std= with 'C' is not supported for SYCL.
6755 if (LangStd->getLanguage() == Language::C)
6756 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
6757 << Std->getAsString(Args) << "-fsycl";
6758 // SYCL requires C++17 or later.
6759 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6760 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6761 }
6762 }
6763 Std->render(Args, Output&: CmdArgs);
6764 }
6765
6766 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6767 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6768 Ids: options::OPT_ftrigraphs,
6769 Ids: options::OPT_fno_trigraphs))
6770 if (A != Std)
6771 A->render(Args, Output&: CmdArgs);
6772 } else {
6773 // Honor -std-default.
6774 //
6775 // FIXME: Clang doesn't correctly handle -std= when the input language
6776 // doesn't match. For the time being just ignore this for C++ inputs;
6777 // eventually we want to do all the standard defaulting here instead of
6778 // splitting it between the driver and clang -cc1.
6779 if (!types::isCXX(Id: InputType)) {
6780 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6781 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6782 /*Joined=*/true);
6783 } else
6784 ImplyVCPPCVer = true;
6785 }
6786 else if (IsWindowsMSVC)
6787 ImplyVCPPCXXVer = true;
6788
6789 if (IsSYCL && types::isCXX(Id: InputType) &&
6790 !Args.hasArg(Ids: options::OPT__SLASH_std) && !IsWindowsMSVC)
6791 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6792 // on the command line will override. On Windows MSVC, this is handled
6793 // by the ImplyVCPPCXXVer path below.
6794 CmdArgs.push_back(Elt: "-std=c++17");
6795
6796 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6797 Ids: options::OPT_fno_trigraphs);
6798 }
6799
6800 // GCC's behavior for -Wwrite-strings is a bit strange:
6801 // * In C, this "warning flag" changes the types of string literals from
6802 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6803 // for the discarded qualifier.
6804 // * In C++, this is just a normal warning flag.
6805 //
6806 // Implementing this warning correctly in C is hard, so we follow GCC's
6807 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6808 // a non-const char* in C, rather than using this crude hack.
6809 if (!types::isCXX(Id: InputType)) {
6810 // FIXME: This should behave just like a warning flag, and thus should also
6811 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6812 Arg *WriteStrings =
6813 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6814 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6815 if (WriteStrings &&
6816 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6817 CmdArgs.push_back(Elt: "-fconst-strings");
6818 }
6819
6820 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6821 // during C++ compilation, which it is by default. GCC keeps this define even
6822 // in the presence of '-w', match this behavior bug-for-bug.
6823 if (types::isCXX(Id: InputType) &&
6824 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6825 Default: true)) {
6826 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6827 }
6828
6829 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6830 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6831 if (Asm->getOption().matches(ID: options::OPT_fasm))
6832 CmdArgs.push_back(Elt: "-fgnu-keywords");
6833 else
6834 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6835 }
6836
6837 if (!ShouldEnableAutolink(Args, TC, JA))
6838 CmdArgs.push_back(Elt: "-fno-autolink");
6839
6840 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6841 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6842 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6843 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6844
6845 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6846
6847 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6848 Args.ClaimAllArgs(Id0: options::OPT_fexperimental_new_constant_interpreter);
6849 Args.AddLastArg(Output&: CmdArgs,
6850 Ids: options::OPT_fno_experimental_new_constant_interpreter);
6851 } else {
6852 Args.ClaimAllArgs(Id0: options::OPT_fno_experimental_new_constant_interpreter);
6853 Args.AddLastArg(Output&: CmdArgs,
6854 Ids: options::OPT_fexperimental_new_constant_interpreter);
6855 }
6856
6857 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6858 CmdArgs.push_back(Elt: "-fbracket-depth");
6859 CmdArgs.push_back(Elt: A->getValue());
6860 }
6861
6862 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6863 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6864 if (A->getNumValues()) {
6865 StringRef bytes = A->getValue();
6866 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6867 } else
6868 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6869 }
6870
6871 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6872 CmdArgs.push_back(Elt: "-relocatable-pch");
6873
6874 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6875 static const char *kCFABIs[] = {
6876 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6877 };
6878
6879 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6880 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6881 else
6882 A->render(Args, Output&: CmdArgs);
6883 }
6884
6885 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6886 CmdArgs.push_back(Elt: "-fconstant-string-class");
6887 CmdArgs.push_back(Elt: A->getValue());
6888 }
6889
6890 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_array_class_EQ)) {
6891 CmdArgs.push_back(Elt: "-fconstant-array-class");
6892 CmdArgs.push_back(Elt: A->getValue());
6893 }
6894 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_dictionary_class_EQ)) {
6895 CmdArgs.push_back(Elt: "-fconstant-dictionary-class");
6896 CmdArgs.push_back(Elt: A->getValue());
6897 }
6898 if (Arg *A =
6899 Args.getLastArg(Ids: options::OPT_fconstant_integer_number_class_EQ)) {
6900 CmdArgs.push_back(Elt: "-fconstant-integer-number-class");
6901 CmdArgs.push_back(Elt: A->getValue());
6902 }
6903 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_float_number_class_EQ)) {
6904 CmdArgs.push_back(Elt: "-fconstant-float-number-class");
6905 CmdArgs.push_back(Elt: A->getValue());
6906 }
6907 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_double_number_class_EQ)) {
6908 CmdArgs.push_back(Elt: "-fconstant-double-number-class");
6909 CmdArgs.push_back(Elt: A->getValue());
6910 }
6911
6912 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6913 CmdArgs.push_back(Elt: "-ftabstop");
6914 CmdArgs.push_back(Elt: A->getValue());
6915 }
6916
6917 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6918 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6919 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6920
6921 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6922 Neg: options::OPT_fno_stack_size_section);
6923
6924 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6925 CmdArgs.push_back(Elt: "-stack-usage-file");
6926
6927 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6928 SmallString<128> OutputFilename(OutputOpt->getValue());
6929 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6930 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6931 } else
6932 CmdArgs.push_back(
6933 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6934 }
6935
6936 CmdArgs.push_back(Elt: "-ferror-limit");
6937 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6938 CmdArgs.push_back(Elt: A->getValue());
6939 else
6940 CmdArgs.push_back(Elt: "19");
6941
6942 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6943 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6944 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6945 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6946 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6947
6948 // Pass -fmessage-length=.
6949 unsigned MessageLength = 0;
6950 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6951 StringRef V(A->getValue());
6952 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6953 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6954 << V << A->getOption().getName();
6955 } else {
6956 // If -fmessage-length=N was not specified, determine whether this is a
6957 // terminal and, if so, implicitly define -fmessage-length appropriately.
6958 MessageLength = llvm::sys::Process::StandardErrColumns();
6959 }
6960 if (MessageLength != 0)
6961 CmdArgs.push_back(
6962 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6963
6964 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6965 CmdArgs.push_back(
6966 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6967
6968 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6969 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6970 Twine(A->getValue(N: 0))));
6971
6972 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6973 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6974 Ids: options::OPT_fvisibility_ms_compat)) {
6975 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6976 A->render(Args, Output&: CmdArgs);
6977 } else {
6978 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6979 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6980 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6981 }
6982 } else if (IsOpenMPDevice) {
6983 // When compiling for the OpenMP device we want protected visibility by
6984 // default. This prevents the device from accidentally preempting code on
6985 // the host, makes the system more robust, and improves performance.
6986 CmdArgs.push_back(Elt: "-fvisibility=protected");
6987 }
6988
6989 // PS4/PS5 process these options in addClangTargetOptions.
6990 if (!RawTriple.isPS()) {
6991 if (const Arg *A =
6992 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
6993 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
6994 if (A->getOption().matches(
6995 ID: options::OPT_fvisibility_from_dllstorageclass)) {
6996 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6997 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
6998 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
6999 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
7000 Args.AddLastArg(Output&: CmdArgs,
7001 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7002 }
7003 }
7004 }
7005
7006 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
7007 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
7008 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
7009
7010 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
7011 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
7012
7013 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7014 // -fvisibility-global-new-delete=force-hidden.
7015 if (const Arg *A =
7016 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7017 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
7018 << A->getAsString(Args) << /*hasReplacement=*/true
7019 << "-fvisibility-global-new-delete=force-hidden";
7020 }
7021
7022 if (const Arg *A =
7023 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
7024 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
7025 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
7026 A->render(Args, Output&: CmdArgs);
7027 } else {
7028 assert(A->getOption().matches(
7029 options::OPT_fvisibility_global_new_delete_hidden));
7030 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
7031 }
7032 }
7033
7034 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
7035
7036 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
7037 Neg: options::OPT_fno_new_infallible, Default: false))
7038 CmdArgs.push_back(Elt: "-fnew-infallible");
7039
7040 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
7041 Neg: options::OPT_foperator_names, Default: false))
7042 CmdArgs.push_back(Elt: "-fno-operator-names");
7043
7044 // Forward -f (flag) options which we can pass directly.
7045 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
7046 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
7047 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
7048 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
7049 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
7050 Ids: options::OPT_fno_raw_string_literals);
7051
7052 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
7053 Default: Triple.hasDefaultEmulatedTLS()))
7054 CmdArgs.push_back(Elt: "-femulated-tls");
7055
7056 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
7057 Neg: options::OPT_fno_check_new);
7058
7059 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
7060 // FIXME: There's no reason for this to be restricted to some backend.
7061 // The backend code needs to be changed to include the appropriate function
7062 // calls automatically.
7063 StringRef Value = A->getValue();
7064 if (!Triple.isX86() && !Triple.isAArch64() &&
7065 !(Triple.isRISCV() && (Value == "skip" || Value.contains(Other: "gpr"))))
7066 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7067 << A->getAsString(Args) << TripleStr;
7068 }
7069
7070 // AltiVec-like language extensions aren't relevant for assembling.
7071 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
7072 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
7073
7074 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
7075 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
7076
7077 // Forward flags for OpenMP. We don't do this if the current action is an
7078 // device offloading action other than OpenMP.
7079 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
7080 Neg: options::OPT_fno_openmp, Default: false) &&
7081 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7082 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
7083 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
7084 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
7085
7086 // Determine if target-fast optimizations should be enabled
7087 bool TargetFastUsed =
7088 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
7089 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
7090 switch (D.getOpenMPRuntime(Args)) {
7091 case Driver::OMPRT_OMP:
7092 case Driver::OMPRT_IOMP5:
7093 // Clang can generate useful OpenMP code for these two runtime libraries.
7094 CmdArgs.push_back(Elt: "-fopenmp");
7095
7096 // If no option regarding the use of TLS in OpenMP codegeneration is
7097 // given, decide a default based on the target. Otherwise rely on the
7098 // options and pass the right information to the frontend.
7099 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
7100 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7101 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
7102 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7103 Ids: options::OPT_fno_openmp_simd);
7104 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
7105 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7106 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
7107 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
7108 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
7109 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
7110 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7111 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7112 // effect: the teams reduction buffer is sized at kernel launch by the
7113 // offload plugin to match the actual number of teams. Honoring a
7114 // smaller user-supplied value would silently truncate the buffer for
7115 // larger launches.
7116 if (Arg *A = Args.getLastArg(
7117 Ids: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7118 D.Diag(DiagID: diag::warn_drv_deprecated_custom)
7119 << A->getAsString(Args)
7120 << "the value is ignored; the teams reduction buffer is sized "
7121 "automatically at kernel launch";
7122 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
7123 Neg: options::OPT_fno_openmp_optimistic_collapse,
7124 /*Default=*/false))
7125 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
7126
7127 // When in OpenMP offloading mode with NVPTX target, forward
7128 // cuda-mode flag
7129 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
7130 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7131 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
7132
7133 // When in OpenMP offloading mode, enable debugging on the device.
7134 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
7135 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
7136 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
7137 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
7138
7139 // When in OpenMP offloading mode, forward assumptions information about
7140 // thread and team counts in the device.
7141 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
7142 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
7143 /*Default=*/false))
7144 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
7145 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
7146 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
7147 /*Default=*/false))
7148 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
7149
7150 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7151 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
7152 Neg: options::OPT_fno_openmp_assume_no_thread_state,
7153 /*Default=*/TargetFastUsed))
7154 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
7155
7156 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7157 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
7158 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
7159 /*Default=*/TargetFastUsed))
7160 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
7161
7162 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
7163 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
7164 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
7165 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
7166 break;
7167 default:
7168 // By default, if Clang doesn't know how to generate useful OpenMP code
7169 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7170 // down to the actual compilation.
7171 // FIXME: It would be better to have a mode which *only* omits IR
7172 // generation based on the OpenMP support so that we get consistent
7173 // semantic analysis, etc.
7174 break;
7175 }
7176 } else {
7177 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
7178 Ids: options::OPT_fno_openmp_simd);
7179 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
7180 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
7181 Neg: options::OPT_fno_openmp_extensions);
7182 }
7183 // Forward the offload runtime change to code generation, liboffload implies
7184 // new driver. Otherwise, check if we should forward the new driver to change
7185 // offloading code generation.
7186 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
7187 Neg: options::OPT_fno_offload_via_llvm, Default: false)) {
7188 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
7189 } else if (Args.hasFlag(Pos: options::OPT_offload_new_driver,
7190 Neg: options::OPT_no_offload_new_driver,
7191 Default: C.getActiveOffloadKinds() != Action::OFK_None)) {
7192 CmdArgs.push_back(Elt: "--offload-new-driver");
7193 }
7194
7195 const XRayArgs &XRay = TC.getXRayArgs(Args);
7196 XRay.addArgs(TC, Args, CmdArgs, InputType);
7197
7198 for (const auto &Filename :
7199 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
7200 if (D.getVFS().exists(Path: Filename))
7201 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
7202 else
7203 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
7204 }
7205
7206 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
7207 StringRef S0 = A->getValue(), S = S0;
7208 unsigned Size, Offset = 0;
7209 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7210 !Triple.isX86() && !Triple.isSystemZ() &&
7211 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7212 Triple.getArch() == llvm::Triple::ppc64 ||
7213 Triple.getArch() == llvm::Triple::ppc64le)))
7214 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7215 << A->getAsString(Args) << TripleStr;
7216 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
7217 (!S.empty() &&
7218 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
7219 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
7220 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7221 << S0 << A->getOption().getName();
7222 else if (Size < Offset)
7223 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
7224 else {
7225 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
7226 CmdArgs.push_back(Elt: Args.MakeArgString(
7227 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
7228 if (!S.empty())
7229 CmdArgs.push_back(
7230 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
7231 }
7232 }
7233
7234 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
7235
7236 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
7237 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
7238
7239 for (const auto &A :
7240 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
7241 CmdArgs.push_back(
7242 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
7243
7244 if (TC.SupportsProfiling()) {
7245 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
7246
7247 llvm::Triple::ArchType Arch = TC.getArch();
7248 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
7249 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7250 A->render(Args, Output&: CmdArgs);
7251 else
7252 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7253 << A->getAsString(Args) << TripleStr;
7254 }
7255 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
7256 if (Arch == llvm::Triple::systemz)
7257 A->render(Args, Output&: CmdArgs);
7258 else
7259 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7260 << A->getAsString(Args) << TripleStr;
7261 }
7262 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
7263 if (Arch == llvm::Triple::systemz)
7264 A->render(Args, Output&: CmdArgs);
7265 else
7266 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7267 << A->getAsString(Args) << TripleStr;
7268 }
7269 }
7270
7271 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
7272 if (TC.getTriple().isOSzOS()) {
7273 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7274 << A->getAsString(Args) << TripleStr;
7275 }
7276 }
7277 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
7278 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7279 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7280 << A->getAsString(Args) << TripleStr;
7281 }
7282 }
7283 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
7284 if (A->getOption().matches(ID: options::OPT_p)) {
7285 A->claim();
7286 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
7287 CmdArgs.push_back(Elt: "-pg");
7288 }
7289 }
7290
7291 // Reject AIX-specific link options on other targets.
7292 if (!TC.getTriple().isOSAIX()) {
7293 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
7294 Ids: options::OPT_mxcoff_build_id_EQ)) {
7295 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7296 << A->getSpelling() << TripleStr;
7297 }
7298 }
7299
7300 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
7301 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
7302 CmdArgs.push_back(Elt: "-fapple-kext");
7303
7304 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
7305 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
7306 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
7307 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
7308 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
7309 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
7310 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
7311 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
7312 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
7313 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
7314 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
7315
7316 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
7317 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
7318 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
7319 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
7320 }
7321
7322 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
7323 CmdArgs.push_back(Elt: "-ftrapv-handler");
7324 CmdArgs.push_back(Elt: A->getValue());
7325 }
7326
7327 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
7328
7329 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
7330 Ids: options::OPT_fno_finite_loops);
7331
7332 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
7333 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
7334 Ids: options::OPT_fno_unroll_loops);
7335 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
7336 Ids: options::OPT_fno_loop_interchange);
7337 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
7338 Neg: options::OPT_fno_experimental_loop_fusion);
7339
7340 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
7341
7342 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
7343
7344 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
7345 Neg: options::OPT_mno_speculative_load_hardening);
7346
7347 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7348 RenderSCPOptions(TC, Args, CmdArgs);
7349 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7350
7351 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7352
7353 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7354 Neg: options::OPT_mno_stackrealign);
7355
7356 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7357 StringRef Value = A->getValue();
7358 int64_t Alignment = 0;
7359 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7360 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7361 << Value << A->getOption().getName();
7362 else if (Alignment & (Alignment - 1))
7363 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7364 << A->getAsString(Args) << Value;
7365 else
7366 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7367 }
7368
7369 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7370 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7371
7372 if (!Size.empty())
7373 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7374 else
7375 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7376 }
7377
7378 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7379 Neg: options::OPT_mno_stack_arg_probe);
7380
7381 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7382 Ids: options::OPT_mno_restrict_it)) {
7383 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7384 CmdArgs.push_back(Elt: "-mllvm");
7385 CmdArgs.push_back(Elt: "-arm-restrict-it");
7386 } else {
7387 CmdArgs.push_back(Elt: "-mllvm");
7388 CmdArgs.push_back(Elt: "-arm-default-it");
7389 }
7390 }
7391
7392 // Forward -cl options to -cc1
7393 RenderOpenCLOptions(Args, CmdArgs, InputType);
7394
7395 // Forward hlsl options to -cc1
7396 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7397
7398 // Forward OpenACC options to -cc1
7399 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7400
7401 if (IsHIP) {
7402 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7403 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7404 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7405 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7406 Neg: options::OPT_fno_gpu_allow_device_init);
7407 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7408 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7409 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7410 Neg: options::OPT_fno_hip_kernel_arg_name);
7411 }
7412
7413 if (IsCuda || IsHIP) {
7414 if (IsRDCMode)
7415 CmdArgs.push_back(Elt: "-fgpu-rdc");
7416 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7417 Neg: options::OPT_fno_gpu_defer_diag);
7418 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7419 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7420 Default: false)) {
7421 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7422 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7423 }
7424 }
7425
7426 // Forward --no-offloadlib to -cc1.
7427 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7428 CmdArgs.push_back(Elt: "--no-offloadlib");
7429
7430 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7431 CmdArgs.push_back(
7432 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7433
7434 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7435 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7436 SA->getValue()));
7437 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7438 // Emit IBT endbr64 instructions by default
7439 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7440 // jump-table can generate indirect jumps, which are not permitted
7441 CmdArgs.push_back(Elt: "-fno-jump-tables");
7442 }
7443
7444 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7445 CmdArgs.push_back(
7446 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7447
7448 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7449
7450 // Forward -f options with positive and negative forms; we translate these by
7451 // hand. Do not propagate PGO options to the GPU-side compilations as the
7452 // profile info is for the host-side compilation only.
7453 if (!(IsCudaDevice || IsHIPDevice)) {
7454 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7455 auto *PGOArg = Args.getLastArg(
7456 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7457 Ids: options::OPT_fcs_profile_generate,
7458 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7459 Ids: options::OPT_fprofile_use_EQ);
7460 if (PGOArg)
7461 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7462 << "SampleUse with PGO options";
7463
7464 StringRef fname = A->getValue();
7465 if (!llvm::sys::fs::exists(Path: fname))
7466 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7467 else
7468 A->render(Args, Output&: CmdArgs);
7469 }
7470 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7471
7472 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7473 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7474 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7475 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7476 // off.
7477 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7478 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7479 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7480 }
7481 }
7482 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7483
7484 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7485 Neg: options::OPT_fno_assume_sane_operator_new);
7486
7487 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7488 CmdArgs.push_back(Elt: "-fapinotes");
7489 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7490 Neg: options::OPT_fno_apinotes_modules, Default: false))
7491 CmdArgs.push_back(Elt: "-fapinotes-modules");
7492 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7493
7494 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7495 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7496 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7497
7498 // -fblocks=0 is default.
7499 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7500 Default: TC.IsBlocksDefault()) ||
7501 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7502 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7503 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7504 CmdArgs.push_back(Elt: "-fblocks");
7505
7506 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7507 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7508 }
7509
7510 // -fencode-extended-block-signature=1 is default.
7511 if (TC.IsEncodeExtendedBlockSignatureDefault())
7512 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7513
7514 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7515 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7516 types::isCXX(Id: InputType))
7517 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7518
7519 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7520 /*Default=*/false))
7521 CmdArgs.push_back(Elt: "-fdefer-ts");
7522
7523 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7524 Ids: options::OPT_fno_double_square_bracket_attributes);
7525
7526 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7527 Neg: options::OPT_fno_access_control);
7528 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7529 Neg: options::OPT_fno_elide_constructors);
7530
7531 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7532
7533 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7534 (RTTIMode == ToolChain::RM_Disabled)))
7535 CmdArgs.push_back(Elt: "-fno-rtti");
7536
7537 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7538 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7539 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7540 CmdArgs.push_back(Elt: "-fshort-enums");
7541
7542 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7543
7544 // -fuse-cxa-atexit is default.
7545 if (!Args.hasFlag(
7546 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7547 Default: !RawTriple.isOSAIX() &&
7548 (!RawTriple.isOSWindows() ||
7549 RawTriple.isWindowsCygwinEnvironment()) &&
7550 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7551 RawTriple.hasEnvironment())) ||
7552 KernelOrKext)
7553 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7554
7555 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7556 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7557 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7558 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7559
7560 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7561 Neg: options::OPT_fno_use_line_directives);
7562
7563 // -fno-minimize-whitespace is default.
7564 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7565 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7566 types::ID InputType = Inputs[0].getType();
7567 if (!isDerivedFromC(Id: InputType))
7568 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7569 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7570 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7571 }
7572
7573 // -fno-keep-system-includes is default.
7574 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7575 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7576 types::ID InputType = Inputs[0].getType();
7577 if (!isDerivedFromC(Id: InputType))
7578 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7579 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7580 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7581 }
7582
7583 // -fms-extensions=0 is default.
7584 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7585 Default: IsWindowsMSVC || IsUEFI))
7586 CmdArgs.push_back(Elt: "-fms-extensions");
7587
7588 // -fms-compatibility=0 is default.
7589 bool IsMSVCCompat = Args.hasFlag(
7590 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7591 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7592 Neg: options::OPT_fno_ms_extensions, Default: true)));
7593 if (IsMSVCCompat) {
7594 CmdArgs.push_back(Elt: "-fms-compatibility");
7595 if (!types::isCXX(Id: Input.getType()) &&
7596 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7597 CmdArgs.push_back(Elt: "-fms-define-stdc");
7598 }
7599
7600 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7601 // clang and flang.
7602 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7603
7604 // -fms-anonymous-structs is disabled by default.
7605 // Determine whether to enable Microsoft named anonymous struct/union support.
7606 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7607 // where the feature can be:
7608 // - Explicitly enabled via -fms-anonymous-structs.
7609 // - Explicitly disabled via fno-ms-anonymous-structs
7610 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7611 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7612 //
7613 // When multiple relevent options are present, the last option on the command
7614 // line takes precedence. This allows users to selectively override implicit
7615 // enablement. Examples:
7616 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7617 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7618 auto MSAnonymousStructsOptionToUseOrNull =
7619 [](const ArgList &Args) -> const char * {
7620 const char *Option = nullptr;
7621 constexpr const char *Enable = "-fms-anonymous-structs";
7622 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7623
7624 // Iterate through all arguments in order to implement "last flag wins".
7625 for (const Arg *A : Args) {
7626 switch (A->getOption().getID()) {
7627 case options::OPT_fms_anonymous_structs:
7628 A->claim();
7629 Option = Enable;
7630 break;
7631 case options::OPT_fno_ms_anonymous_structs:
7632 A->claim();
7633 Option = Disable;
7634 break;
7635 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7636 // feature.
7637 case options::OPT_fms_extensions:
7638 case options::OPT_fms_compatibility:
7639 Option = Enable;
7640 break;
7641 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7642 // disables the feature.
7643 case options::OPT_fno_ms_extensions:
7644 case options::OPT_fno_ms_compatibility:
7645 Option = Disable;
7646 break;
7647 default:
7648 break;
7649 }
7650 }
7651 return Option;
7652 };
7653
7654 // Only pass a flag to CC1 if a relevant option was seen
7655 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7656 CmdArgs.push_back(Elt: MSAnonOpt);
7657
7658 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7659 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7660 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7661
7662 // Handle -fgcc-version, if present.
7663 VersionTuple GNUCVer;
7664 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7665 // Check that the version has 1 to 3 components and the minor and patch
7666 // versions fit in two decimal digits.
7667 StringRef Val = A->getValue();
7668 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7669 bool Invalid = GNUCVer.tryParse(string: Val);
7670 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7671 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7672 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7673 D.Diag(DiagID: diag::err_drv_invalid_value)
7674 << A->getAsString(Args) << A->getValue();
7675 }
7676 } else if (!IsMSVCCompat) {
7677 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7678 GNUCVer = VersionTuple(4, 2, 1);
7679 }
7680 if (!GNUCVer.empty()) {
7681 CmdArgs.push_back(
7682 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7683 }
7684
7685 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7686 if (!MSVT.empty())
7687 CmdArgs.push_back(
7688 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7689
7690 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7691 if (ImplyVCPPCVer) {
7692 StringRef LanguageStandard;
7693 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7694 Std = StdArg;
7695 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7696 .Case(S: "c11", Value: "-std=c11")
7697 .Case(S: "c17", Value: "-std=c17")
7698 // If you add cases below for spellings that are
7699 // not in LangStandards.def, update
7700 // TransferableCommand::tryParseStdArg() in
7701 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7702 // to match.
7703 // TODO: add c23 when MSVC supports it.
7704 .Case(S: "clatest", Value: "-std=c23")
7705 .Default(Value: "");
7706 if (LanguageStandard.empty())
7707 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7708 << StdArg->getAsString(Args);
7709 }
7710 CmdArgs.push_back(Elt: LanguageStandard.data());
7711 }
7712 if (ImplyVCPPCXXVer) {
7713 StringRef LanguageStandard;
7714 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7715 Std = StdArg;
7716 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7717 .Case(S: "c++14", Value: "-std=c++14")
7718 .Case(S: "c++17", Value: "-std=c++17")
7719 .Case(S: "c++20", Value: "-std=c++20")
7720 // If you add cases below for spellings that are
7721 // not in LangStandards.def, update
7722 // TransferableCommand::tryParseStdArg() in
7723 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7724 // to match.
7725 // TODO add c++23, c++26, c++29 when MSVC supports
7726 // it.
7727 .Case(S: "c++23preview", Value: "-std=c++23")
7728 .Case(S: "c++26preview", Value: "-std=c++26")
7729 .Case(S: "c++latest", Value: "-std=c++2d")
7730 .Default(Value: "");
7731 if (IsSYCL) {
7732 const LangStandard *LangStd =
7733 LangStandard::getLangStandardForName(Name: StdArg->getValue());
7734 if (LangStd) {
7735 // Use of /std: with 'C' is not supported for SYCL.
7736 if (LangStd->getLanguage() == Language::C)
7737 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7738 << StdArg->getAsString(Args) << "-fsycl";
7739 // SYCL requires C++17 or later.
7740 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7741 D.Diag(DiagID: diag::err_drv_sycl_requires_cxx17)
7742 << StdArg->getAsString(Args);
7743 }
7744 }
7745 if (LanguageStandard.empty())
7746 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7747 << StdArg->getAsString(Args);
7748 }
7749
7750 if (LanguageStandard.empty()) {
7751 if (IsSYCL)
7752 // For SYCL, C++17 is the default.
7753 LanguageStandard = "-std=c++17";
7754 else if (IsMSVC2015Compatible)
7755 LanguageStandard = "-std=c++14";
7756 else
7757 LanguageStandard = "-std=c++11";
7758 }
7759
7760 CmdArgs.push_back(Elt: LanguageStandard.data());
7761 }
7762
7763 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7764 Neg: options::OPT_fno_borland_extensions);
7765
7766 // -fno-declspec is default, except for PS4/PS5.
7767 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7768 Default: RawTriple.isPS()))
7769 CmdArgs.push_back(Elt: "-fdeclspec");
7770 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7771 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7772
7773 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7774 // than 19.
7775 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7776 Neg: options::OPT_fno_threadsafe_statics,
7777 Default: !types::isOpenCL(Id: InputType) &&
7778 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7779 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7780
7781 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7782 Default: true))
7783 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7784
7785 // Add -fno-assumptions, if it was specified.
7786 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7787 Default: true))
7788 CmdArgs.push_back(Elt: "-fno-assumptions");
7789
7790 // -fgnu-keywords default varies depending on language; only pass if
7791 // specified.
7792 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7793 Ids: options::OPT_fno_gnu_keywords);
7794
7795 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7796 Neg: options::OPT_fno_gnu89_inline);
7797
7798 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7799 Ids: options::OPT_finline_hint_functions,
7800 Ids: options::OPT_fno_inline_functions);
7801 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7802 if (A->getOption().matches(ID: options::OPT_fno_inline))
7803 A->render(Args, Output&: CmdArgs);
7804 } else if (InlineArg) {
7805 InlineArg->render(Args, Output&: CmdArgs);
7806 }
7807
7808 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7809
7810 // FIXME: Find a better way to determine whether we are in C++20.
7811 bool HaveCxx20 =
7812 Std &&
7813 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7814 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7815 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7816 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7817 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7818 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7819 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++26preview") ||
7820 Std->containsValue(Value: "c++2d") || Std->containsValue(Value: "gnu++2d") ||
7821 Std->containsValue(Value: "c++latest") || Std->containsValue(Value: "gnu++latest"));
7822 bool HaveModules =
7823 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7824
7825 // -fdelayed-template-parsing is default when targeting MSVC.
7826 // Many old Windows SDK versions require this to parse.
7827 //
7828 // According to
7829 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7830 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7831 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7832 // not enable -fdelayed-template-parsing by default after C++20.
7833 //
7834 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7835 // able to disable this by default at some point.
7836 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7837 Neg: options::OPT_fno_delayed_template_parsing,
7838 Default: IsWindowsMSVC && !HaveCxx20)) {
7839 if (HaveCxx20)
7840 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7841
7842 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7843 }
7844
7845 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7846 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7847 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7848 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7849 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7850 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7851 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7852 Default: false))
7853 CmdArgs.push_back(Elt: "-fmodules-codegen");
7854 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7855 Default: false))
7856 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7857
7858 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7859 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7860 Input, CmdArgs);
7861
7862 if (types::isObjC(Id: Input.getType()) &&
7863 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7864 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7865 Default: !Runtime.isNeXTFamily()))
7866 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7867
7868 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7869 Neg: options::OPT_fno_application_extension, Default: false))
7870 CmdArgs.push_back(Elt: "-fapplication-extension");
7871
7872 // Handle GCC-style exception args.
7873 bool EH = false;
7874 if (!C.getDriver().IsCLMode())
7875 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7876 IsDeviceOffloadAction, objcRuntime: Runtime, CmdArgs);
7877
7878 // Handle exception personalities
7879 Arg *A = Args.getLastArg(
7880 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7881 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions);
7882 if (A) {
7883 const Option &Opt = A->getOption();
7884 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7885 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7886 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7887 CmdArgs.push_back(Elt: "-exception-model=seh");
7888 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7889 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7890 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7891 CmdArgs.push_back(Elt: "-exception-model=wasm");
7892 } else {
7893 switch (TC.GetExceptionModel(Args)) {
7894 default:
7895 break;
7896 case llvm::ExceptionHandling::DwarfCFI:
7897 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7898 break;
7899 case llvm::ExceptionHandling::SjLj:
7900 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7901 break;
7902 case llvm::ExceptionHandling::WinEH:
7903 CmdArgs.push_back(Elt: "-exception-model=seh");
7904 break;
7905 }
7906 }
7907
7908 // Unwind information version for x64 Windows.
7909 // Forward the new unified flag if present, otherwise translate legacy flags.
7910 if (const Arg *A = Args.getLastArg(Ids: options::OPT_winx64_eh_unwind_EQ)) {
7911 A->claim();
7912 CmdArgs.push_back(
7913 Elt: Args.MakeArgString(Str: Twine("-fwinx64-eh-unwind=") + A->getValue()));
7914 } else if (const Arg *A =
7915 Args.getLastArg(Ids: options::OPT_winx64_eh_unwindv2_EQ)) {
7916 A->claim();
7917 StringRef Val = A->getValue();
7918 if (Val == "best-effort")
7919 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
7920 else if (Val == "required")
7921 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
7922 // "disabled" maps to v1 default, nothing to forward.
7923 else if (Val != "disabled")
7924 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7925 }
7926
7927 // Control Flow Guard mechanism for Windows.
7928 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_win_cfg_mechanism);
7929
7930 // C++ "sane" operator new.
7931 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7932 Neg: options::OPT_fno_assume_sane_operator_new);
7933
7934 // -fassume-unique-vtables is on by default.
7935 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7936 Neg: options::OPT_fno_assume_unique_vtables);
7937
7938 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7939 // by default.
7940 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7941 Ids: options::OPT_fno_sized_deallocation);
7942
7943 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7944 // by default.
7945 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7946 Ids: options::OPT_fno_aligned_allocation,
7947 Ids: options::OPT_faligned_new_EQ)) {
7948 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7949 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7950 else
7951 CmdArgs.push_back(Elt: "-faligned-allocation");
7952 }
7953
7954 // The default new alignment can be specified using a dedicated option or via
7955 // a GCC-compatible option that also turns on aligned allocation.
7956 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7957 Ids: options::OPT_faligned_new_EQ))
7958 CmdArgs.push_back(
7959 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7960
7961 // -fconstant-cfstrings is default, and may be subject to argument translation
7962 // on Darwin.
7963 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7964 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7965 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7966 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7967 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7968
7969 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7970 Neg: options::OPT_fno_pascal_strings);
7971
7972 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7973 // -fno-pack-struct doesn't apply to -fpack-struct=.
7974 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7975 CmdArgs.push_back(
7976 Elt: Args.MakeArgString(Str: "-fpack-struct=" + Twine(A->getValue())));
7977 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7978 Neg: options::OPT_fno_pack_struct, Default: false)) {
7979 CmdArgs.push_back(Elt: "-fpack-struct=1");
7980 }
7981
7982 // Handle -fmax-type-align=N and -fno-type-align
7983 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
7984 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
7985 if (!SkipMaxTypeAlign) {
7986 std::string MaxTypeAlignStr = "-fmax-type-align=";
7987 MaxTypeAlignStr += A->getValue();
7988 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7989 }
7990 } else if (RawTriple.isOSDarwin()) {
7991 if (!SkipMaxTypeAlign) {
7992 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7993 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7994 }
7995 }
7996
7997 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
7998 CmdArgs.push_back(Elt: "-Qn");
7999
8000 // -fno-common is the default, set -fcommon only when that flag is set.
8001 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
8002
8003 // -fsigned-bitfields is default, and clang doesn't yet support
8004 // -funsigned-bitfields.
8005 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
8006 Neg: options::OPT_funsigned_bitfields, Default: true))
8007 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
8008 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
8009
8010 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8011 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
8012 D.Diag(DiagID: diag::err_drv_clang_unsupported)
8013 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
8014
8015 // -finput_charset=UTF-8 is default. Reject others
8016 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
8017 StringRef value = inputCharset->getValue();
8018 if (!value.equals_insensitive(RHS: "utf-8"))
8019 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8020 << value;
8021 }
8022
8023 // -fexec_charset=UTF-8 is default. Reject others
8024 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
8025 StringRef value = execCharset->getValue();
8026 if (!value.equals_insensitive(RHS: "utf-8"))
8027 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8028 << value;
8029 }
8030
8031 RenderDiagnosticsOptions(D, Args, CmdArgs);
8032
8033 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
8034 Neg: options::OPT_fno_asm_blocks);
8035
8036 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
8037 Neg: options::OPT_fno_gnu_inline_asm);
8038
8039 handleVectorizeLoopsArgs(Args, CmdArgs);
8040 handleVectorizeSLPArgs(Args, CmdArgs);
8041
8042 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
8043 if (!VecWidth.empty())
8044 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
8045
8046 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
8047 Args.AddLastArg(Output&: CmdArgs,
8048 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
8049
8050 // -fdollars-in-identifiers default varies depending on platform and
8051 // language; only pass if specified.
8052 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
8053 Ids: options::OPT_fno_dollars_in_identifiers)) {
8054 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
8055 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
8056 else
8057 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
8058 }
8059
8060 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
8061 Neg: options::OPT_fno_apple_pragma_pack);
8062
8063 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8064 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8065 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8066
8067 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
8068 Neg: options::OPT_fno_rewrite_imports, Default: false);
8069 if (RewriteImports)
8070 CmdArgs.push_back(Elt: "-frewrite-imports");
8071
8072 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
8073 Neg: options::OPT_fno_directives_only);
8074
8075 // Enable rewrite includes if the user's asked for it or if we're generating
8076 // diagnostics.
8077 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8078 // nice to enable this when doing a crashdump for modules as well.
8079 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
8080 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
8081 (C.isForDiagnostics() && !HaveModules))
8082 CmdArgs.push_back(Elt: "-frewrite-includes");
8083
8084 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
8085 Neg: options::OPT_fno_zos_extensions, Default: false))
8086 CmdArgs.push_back(Elt: "-fzos-extensions");
8087 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
8088 CmdArgs.push_back(Elt: "-fno-zos-extensions");
8089
8090 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8091 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
8092 Ids: options::OPT_traditional_cpp)) {
8093 if (isa<PreprocessJobAction>(Val: JA))
8094 CmdArgs.push_back(Elt: "-traditional-cpp");
8095 else
8096 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
8097 }
8098
8099 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
8100 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
8101 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
8102
8103 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
8104
8105 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
8106 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
8107 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_compilation_unit_id);
8108 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_include_local_entities);
8109 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_no_extract_from_system_headers);
8110 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_source_transformation);
8111 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_global_scope_analysis_result);
8112 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_src_edit_file);
8113 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_transformation_report_file);
8114
8115 // Handle serialized diagnostics.
8116 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
8117 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
8118 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
8119 }
8120
8121 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
8122 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
8123
8124 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
8125 A->render(Args, Output&: CmdArgs);
8126 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
8127 A && A->containsValue(Value: "g")) {
8128 // Set -fextend-variable-liveness=all by default at -Og.
8129 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
8130 }
8131
8132 // Forward -fcomment-block-commands to -cc1.
8133 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
8134 // Forward -fparse-all-comments to -cc1.
8135 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
8136
8137 // Turn -fplugin=name.so into -load name.so
8138 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
8139 CmdArgs.push_back(Elt: "-load");
8140 CmdArgs.push_back(Elt: A->getValue());
8141 A->claim();
8142 }
8143
8144 // Turn -fplugin-arg-pluginname-key=value into
8145 // -plugin-arg-pluginname key=value
8146 // GCC has an actual plugin_argument struct with key/value pairs that it
8147 // passes to its plugins, but we don't, so just pass it on as-is.
8148 //
8149 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8150 // argument key are allowed to contain dashes. GCC therefore only
8151 // allows dashes in the key. We do the same.
8152 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
8153 auto ArgValue = StringRef(A->getValue());
8154 auto FirstDashIndex = ArgValue.find(C: '-');
8155 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
8156 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
8157
8158 A->claim();
8159 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8160 if (PluginName.empty()) {
8161 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8162 } else {
8163 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
8164 << PluginName << A->getAsString(Args);
8165 }
8166 continue;
8167 }
8168
8169 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
8170 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
8171 }
8172
8173 // Forward -fpass-plugin=name.so to -cc1.
8174 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
8175 CmdArgs.push_back(
8176 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
8177 A->claim();
8178 }
8179
8180 // Forward --vfsoverlay to -cc1.
8181 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
8182 CmdArgs.push_back(Elt: "--vfsoverlay");
8183 CmdArgs.push_back(Elt: A->getValue());
8184 A->claim();
8185 }
8186
8187 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
8188 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
8189
8190 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
8191 Neg: options::OPT_fno_experimental_late_parse_attributes);
8192
8193 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
8194 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
8195 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
8196 A->render(Args, Output&: CmdArgs);
8197 else
8198 CmdArgs.push_back(Elt: Args.MakeArgString(
8199 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8200 }
8201
8202 if (Args.hasFlag(
8203 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
8204 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8205 Default: false) ||
8206 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8207 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
8208 Default: false))
8209 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
8210
8211 if (!IsCudaDevice) {
8212 Args.addOptInFlag(
8213 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
8214 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
8215 Args.addOptInFlag(
8216 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
8217 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
8218 }
8219
8220 // Setup statistics file output.
8221 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8222 if (!StatsFile.empty()) {
8223 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
8224 if (D.CCPrintInternalStats)
8225 CmdArgs.push_back(Elt: "-stats-file-append");
8226 }
8227
8228 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8229 // parser.
8230 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
8231 Arg->claim();
8232 // -finclude-default-header flag is for preprocessor,
8233 // do not pass it to other cc1 commands when save-temps is enabled
8234 if (C.getDriver().isSaveTempsEnabled() &&
8235 !isa<PreprocessJobAction>(Val: JA)) {
8236 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8237 continue;
8238 }
8239 CmdArgs.push_back(Elt: Arg->getValue());
8240 }
8241 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
8242 A->claim();
8243
8244 // We translate this by hand to the -cc1 argument, since nightly test uses
8245 // it and developers have been trained to spell it with -mllvm. Both
8246 // spellings are now deprecated and should be removed.
8247 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
8248 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
8249 } else {
8250 A->render(Args, Output&: CmdArgs);
8251 }
8252 }
8253
8254 // This needs to run after -Xclang argument forwarding to pick up the target
8255 // features enabled through -Xclang -target-feature flags.
8256 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8257
8258 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
8259
8260#if CLANG_ENABLE_CIR
8261 // Forward -mmlir arguments to to the MLIR option parser.
8262 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8263 A->claim();
8264 A->render(Args, CmdArgs);
8265 }
8266#endif // CLANG_ENABLE_CIR
8267
8268 // With -save-temps, we want to save the unoptimized bitcode output from the
8269 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8270 // by the frontend.
8271 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8272 // has slightly different breakdown between stages.
8273 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8274 // pristine IR generated by the frontend. Ideally, a new compile action should
8275 // be added so both IR can be captured.
8276 if ((C.getDriver().isSaveTempsEnabled() ||
8277 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
8278 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8279 isa<CompileJobAction>(Val: JA))
8280 CmdArgs.push_back(Elt: "-disable-llvm-passes");
8281
8282 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
8283
8284 const char *Exec = D.getDriverProgramPath();
8285
8286 // Optionally embed the -cc1 level arguments into the debug info or a
8287 // section, for build analysis.
8288 // Also record command line arguments into the debug info if
8289 // -grecord-gcc-switches options is set on.
8290 // By default, -gno-record-gcc-switches is set on and no recording.
8291 auto GRecordSwitches = false;
8292 auto FRecordSwitches = false;
8293 bool DXRecordSwitches = false;
8294 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches,
8295 DXRecordCommandLine&: DXRecordSwitches)) {
8296 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8297 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8298 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8299 CmdArgs.push_back(Elt: FlagsArgString);
8300 }
8301 if (FRecordSwitches) {
8302 CmdArgs.push_back(Elt: "-record-command-line");
8303 CmdArgs.push_back(Elt: FlagsArgString);
8304 }
8305 if (DXRecordSwitches) {
8306 CmdArgs.push_back(Elt: "-fdx-record-command-line");
8307 CmdArgs.push_back(Elt: FlagsArgString);
8308 }
8309 }
8310
8311 // Host-side offloading compilation receives all device-side outputs. Include
8312 // them in the host compilation depending on the target. If the host inputs
8313 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8314 if ((IsCuda || IsHIP) && CudaDeviceInput) {
8315 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
8316 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
8317 } else if (!HostOffloadingInputs.empty()) {
8318 if ((IsCuda || IsHIP) && !IsRDCMode) {
8319 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8320 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
8321 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
8322 } else {
8323 for (const InputInfo Input : HostOffloadingInputs)
8324 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
8325 TC.getInputFilename(Input)));
8326 }
8327 }
8328
8329 if (IsCuda) {
8330 if (Args.hasFlag(Pos: options::OPT_fcuda_short_ptr,
8331 Neg: options::OPT_fno_cuda_short_ptr, Default: false))
8332 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
8333 }
8334
8335 if (IsCuda || IsHIP) {
8336 // Determine the original source input.
8337 const Action *SourceAction = &JA;
8338 while (SourceAction->getKind() != Action::InputClass) {
8339 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8340 SourceAction = SourceAction->getInputs()[0];
8341 }
8342 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
8343 if (!CUID.empty())
8344 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
8345
8346 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8347 // be overriden by -fno-gpu-approx-transcendentals.
8348 bool UseApproxTranscendentals = Args.hasFlag(
8349 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
8350 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
8351 Neg: options::OPT_fno_gpu_approx_transcendentals,
8352 Default: UseApproxTranscendentals))
8353 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
8354 } else {
8355 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
8356 Ids: options::OPT_fno_gpu_approx_transcendentals);
8357 }
8358
8359 if (IsHIP) {
8360 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
8361 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
8362 }
8363
8364 Args.AddAllArgs(Output&: CmdArgs,
8365 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8366
8367 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
8368 Ids: options::OPT_fno_offload_uniform_block);
8369
8370 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
8371 Ids: options::OPT_fno_offload_implicit_host_device_templates);
8372
8373 if (IsCudaDevice || IsHIPDevice) {
8374 StringRef InlineThresh =
8375 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
8376 if (!InlineThresh.empty()) {
8377 std::string ArgStr =
8378 std::string("-inline-threshold=") + InlineThresh.str();
8379 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
8380 }
8381 }
8382
8383 if (IsHIPDevice)
8384 Args.addOptOutFlag(Output&: CmdArgs,
8385 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8386 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8387
8388 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8389 // to specify the result of the compile phase on the host, so the meaningful
8390 // device declarations can be identified. Also, -fopenmp-is-target-device is
8391 // passed along to tell the frontend that it is generating code for a device,
8392 // so that only the relevant declarations are emitted.
8393 if (IsOpenMPDevice) {
8394 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
8395 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8396 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
8397 CmdArgs.push_back(Elt: "-fcuda-is-device");
8398
8399 if (OpenMPDeviceInput) {
8400 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
8401 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
8402 }
8403 }
8404
8405 if (Triple.isAMDGPU() ||
8406 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8407 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8408
8409 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8410 Neg: options::OPT_mno_unsafe_fp_atomics);
8411 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8412 Neg: options::OPT_mno_amdgpu_ieee);
8413 }
8414
8415 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8416
8417 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8418 Neg: options::OPT_fno_devirtualize_speculatively,
8419 /*Default value*/ Default: false))
8420 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8421
8422 bool VirtualFunctionElimination =
8423 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8424 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8425 if (VirtualFunctionElimination) {
8426 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8427 // in the future).
8428 if (LTOMode != LTOK_Full)
8429 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8430 << "-fvirtual-function-elimination"
8431 << "-flto=full";
8432
8433 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8434 }
8435
8436 // VFE requires whole-program-vtables, and enables it by default.
8437 bool WholeProgramVTables = Args.hasFlag(
8438 Pos: options::OPT_fwhole_program_vtables,
8439 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8440 if (VirtualFunctionElimination && !WholeProgramVTables) {
8441 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8442 << "-fno-whole-program-vtables"
8443 << "-fvirtual-function-elimination";
8444 }
8445
8446 if (WholeProgramVTables) {
8447 // PS4 uses the legacy LTO API, which does not support this feature in
8448 // ThinLTO mode.
8449 bool IsPS4 = getToolChain().getTriple().isPS4();
8450
8451 // Check if we passed LTO options but they were suppressed because this is a
8452 // device offloading action, or we passed device offload LTO options which
8453 // were suppressed because this is not the device offload action.
8454 // Check if we are using PS4 in regular LTO mode.
8455 // Otherwise, issue an error.
8456
8457 auto OtherLTOMode = TC.getLTOMode(
8458 Args, Kind: IsDeviceOffloadAction ? Action::OFK_None
8459 : static_cast<Action::OffloadKind>(
8460 C.getActiveOffloadKinds()));
8461 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8462
8463 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8464 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8465 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8466 << "-fwhole-program-vtables"
8467 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8468
8469 // Propagate -fwhole-program-vtables if this is an LTO compile.
8470 if (IsUsingLTO)
8471 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8472 }
8473
8474 bool DefaultsSplitLTOUnit =
8475 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8476 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8477 (!Triple.isPS4() && UnifiedLTO);
8478 bool SplitLTOUnit =
8479 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8480 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8481 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8482 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8483 << "-fsanitize=cfi";
8484 if (SplitLTOUnit)
8485 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8486
8487 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8488 Ids: options::OPT_fno_fat_lto_objects)) {
8489 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8490 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8491 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8492 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8493 << A->getAsString(Args) << TC.getTripleString();
8494 }
8495 CmdArgs.push_back(Elt: Args.MakeArgString(
8496 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8497 CmdArgs.push_back(Elt: "-flto-unit");
8498 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8499 A->render(Args, Output&: CmdArgs);
8500 }
8501 }
8502
8503 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8504
8505 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8506 Ids: options::OPT_fno_force_enable_int128)) {
8507 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8508 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8509 }
8510
8511 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8512 Neg: options::OPT_fno_keep_static_consts);
8513 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8514 Neg: options::OPT_fno_keep_persistent_storage_variables);
8515 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8516 Neg: options::OPT_fno_complete_member_pointers);
8517 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8518 A->render(Args, Output&: CmdArgs);
8519
8520 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8521
8522 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8523
8524 if (Triple.isAArch64() &&
8525 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8526 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8527 // Disable Function Multiversioning on AArch64 target.
8528 CmdArgs.push_back(Elt: "-target-feature");
8529 CmdArgs.push_back(Elt: "-fmv");
8530 }
8531
8532 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8533 Default: (TC.getTriple().isOSBinFormatELF() ||
8534 TC.getTriple().isOSBinFormatCOFF()) &&
8535 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8536 !TC.getTriple().isOSNetBSD() &&
8537 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8538 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8539 CmdArgs.push_back(Elt: "-faddrsig");
8540
8541 const bool HasDefaultDwarf2CFIASM =
8542 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8543 (EH || UnwindTables || AsyncUnwindTables ||
8544 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8545 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8546 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8547 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8548
8549 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8550 std::string Str = A->getAsString(Args);
8551 if (!TC.getTriple().isOSBinFormatELF())
8552 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8553 << Str << TC.getTripleString();
8554 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8555 }
8556
8557 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8558 // the -cc1 command easier to edit when reproducing compiler crashes.
8559 if (Output.getType() == types::TY_Dependencies) {
8560 // Handled with other dependency code.
8561 } else if (Output.isFilename()) {
8562 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8563 Output.getType() == clang::driver::types::TY_IFS) {
8564 SmallString<128> OutputFilename(Output.getFilename());
8565 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8566 CmdArgs.push_back(Elt: "-o");
8567 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8568 } else {
8569 CmdArgs.push_back(Elt: "-o");
8570 CmdArgs.push_back(Elt: Output.getFilename());
8571 }
8572 } else {
8573 assert(Output.isNothing() && "Invalid output.");
8574 }
8575
8576 addDashXForInput(Args, Input, CmdArgs);
8577
8578 ArrayRef<InputInfo> FrontendInputs = Input;
8579 if (IsExtractAPI)
8580 FrontendInputs = ExtractAPIInputs;
8581 else if (Input.isNothing())
8582 FrontendInputs = {};
8583
8584 for (const InputInfo &Input : FrontendInputs) {
8585 if (Input.isFilename())
8586 CmdArgs.push_back(Elt: Input.getFilename());
8587 else
8588 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8589 }
8590
8591 if (D.CC1Main && !D.CCGenDiagnostics) {
8592 // Invoke the CC1 directly in this process
8593 C.addCommand(Cmd: std::make_unique<CC1Command>(
8594 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8595 args: Output, args: D.getPrependArg()));
8596 } else {
8597 C.addCommand(Cmd: std::make_unique<Command>(
8598 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8599 args: Output, args: D.getPrependArg()));
8600 }
8601
8602 // Make the compile command echo its inputs for /showFilenames.
8603 if (Output.getType() == types::TY_Object &&
8604 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8605 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8606 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8607 }
8608
8609 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8610 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8611 !Args.hasArg(Ids: options::OPT_mfentry))
8612 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8613 << A->getAsString(Args);
8614
8615 // Claim some arguments which clang supports automatically.
8616
8617 // -fpch-preprocess is used with gcc to add a special marker in the output to
8618 // include the PCH file.
8619 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8620
8621 // Claim some arguments which clang doesn't support, but we don't
8622 // care to warn the user about.
8623 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8624 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8625
8626 // Disable warnings for clang -E -emit-llvm foo.c
8627 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8628}
8629
8630Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8631 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8632 // as it is for other tools. Some operations on a Tool actually test
8633 // whether that tool is Clang based on the Tool's Name as a string.
8634 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8635
8636Clang::~Clang() {}
8637
8638/// Add options related to the Objective-C runtime/ABI.
8639///
8640/// Returns true if the runtime is non-fragile.
8641ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8642 const InputInfoList &inputs,
8643 ArgStringList &cmdArgs,
8644 RewriteKind rewriteKind) const {
8645 // Look for the controlling runtime option.
8646 Arg *runtimeArg =
8647 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8648 Ids: options::OPT_fobjc_runtime_EQ);
8649
8650 // Just forward -fobjc-runtime= to the frontend. This supercedes
8651 // options about fragility.
8652 if (runtimeArg &&
8653 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8654 ObjCRuntime runtime;
8655 StringRef value = runtimeArg->getValue();
8656 if (runtime.tryParse(input: value)) {
8657 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8658 << value;
8659 }
8660 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8661 (runtime.getVersion() >= VersionTuple(2, 0)))
8662 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8663 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8664 getToolChain().getDriver().Diag(
8665 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8666 << runtime.getVersion().getMajor();
8667 }
8668
8669 runtimeArg->render(Args: args, Output&: cmdArgs);
8670 return runtime;
8671 }
8672
8673 // Otherwise, we'll need the ABI "version". Version numbers are
8674 // slightly confusing for historical reasons:
8675 // 1 - Traditional "fragile" ABI
8676 // 2 - Non-fragile ABI, version 1
8677 // 3 - Non-fragile ABI, version 2
8678 unsigned objcABIVersion = 1;
8679 // If -fobjc-abi-version= is present, use that to set the version.
8680 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8681 StringRef value = abiArg->getValue();
8682 if (value == "1")
8683 objcABIVersion = 1;
8684 else if (value == "2")
8685 objcABIVersion = 2;
8686 else if (value == "3")
8687 objcABIVersion = 3;
8688 else
8689 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8690 } else {
8691 // Otherwise, determine if we are using the non-fragile ABI.
8692 bool nonFragileABIIsDefault =
8693 (rewriteKind == RK_NonFragile ||
8694 (rewriteKind == RK_None &&
8695 getToolChain().IsObjCNonFragileABIDefault()));
8696 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8697 Neg: options::OPT_fno_objc_nonfragile_abi,
8698 Default: nonFragileABIIsDefault)) {
8699// Determine the non-fragile ABI version to use.
8700#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8701 unsigned nonFragileABIVersion = 1;
8702#else
8703 unsigned nonFragileABIVersion = 2;
8704#endif
8705
8706 if (Arg *abiArg =
8707 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8708 StringRef value = abiArg->getValue();
8709 if (value == "1")
8710 nonFragileABIVersion = 1;
8711 else if (value == "2")
8712 nonFragileABIVersion = 2;
8713 else
8714 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8715 << value;
8716 }
8717
8718 objcABIVersion = 1 + nonFragileABIVersion;
8719 } else {
8720 objcABIVersion = 1;
8721 }
8722 }
8723
8724 // We don't actually care about the ABI version other than whether
8725 // it's non-fragile.
8726 bool isNonFragile = objcABIVersion != 1;
8727
8728 // If we have no runtime argument, ask the toolchain for its default runtime.
8729 // However, the rewriter only really supports the Mac runtime, so assume that.
8730 ObjCRuntime runtime;
8731 if (!runtimeArg) {
8732 switch (rewriteKind) {
8733 case RK_None:
8734 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8735 break;
8736 case RK_Fragile:
8737 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8738 break;
8739 case RK_NonFragile:
8740 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8741 break;
8742 }
8743
8744 // -fnext-runtime
8745 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8746 // On Darwin, make this use the default behavior for the toolchain.
8747 if (getToolChain().getTriple().isOSDarwin()) {
8748 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8749
8750 // Otherwise, build for a generic macosx port.
8751 } else {
8752 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8753 }
8754
8755 // -fgnu-runtime
8756 } else {
8757 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8758 // Legacy behaviour is to target the gnustep runtime if we are in
8759 // non-fragile mode or the GCC runtime in fragile mode.
8760 if (isNonFragile)
8761 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8762 else
8763 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8764 }
8765
8766 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8767 return types::isObjC(Id: input.getType());
8768 }))
8769 cmdArgs.push_back(
8770 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8771 return runtime;
8772}
8773
8774static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8775 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8776 I += HaveDash;
8777 return !HaveDash;
8778}
8779
8780namespace {
8781struct EHFlags {
8782 bool Synch = false;
8783 bool Asynch = false;
8784 bool NoUnwindC = false;
8785};
8786} // end anonymous namespace
8787
8788/// /EH controls whether to run destructor cleanups when exceptions are
8789/// thrown. There are three modifiers:
8790/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8791/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8792/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8793/// - c: Assume that extern "C" functions are implicitly nounwind.
8794/// The default is /EHs-c-, meaning cleanups are disabled.
8795static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8796 bool isWindowsMSVC) {
8797 EHFlags EH;
8798
8799 std::vector<std::string> EHArgs =
8800 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8801 for (const auto &EHVal : EHArgs) {
8802 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8803 switch (EHVal[I]) {
8804 case 'a':
8805 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8806 if (EH.Asynch) {
8807 // Async exceptions are Windows MSVC only.
8808 if (!isWindowsMSVC) {
8809 EH.Asynch = false;
8810 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8811 continue;
8812 }
8813 EH.Synch = false;
8814 }
8815 continue;
8816 case 'c':
8817 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8818 continue;
8819 case 's':
8820 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8821 if (EH.Synch)
8822 EH.Asynch = false;
8823 continue;
8824 default:
8825 break;
8826 }
8827 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8828 break;
8829 }
8830 }
8831 // The /GX, /GX- flags are only processed if there are not /EH flags.
8832 // The default is that /GX is not specified.
8833 if (EHArgs.empty() &&
8834 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8835 /*Default=*/false)) {
8836 EH.Synch = true;
8837 EH.NoUnwindC = true;
8838 }
8839
8840 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8841 EH.Synch = false;
8842 EH.NoUnwindC = false;
8843 EH.Asynch = false;
8844 }
8845
8846 return EH;
8847}
8848
8849void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8850 ArgStringList &CmdArgs) const {
8851 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8852
8853 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8854
8855 if (Arg *ShowIncludes =
8856 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8857 Ids: options::OPT__SLASH_showIncludes_user)) {
8858 CmdArgs.push_back(Elt: "--show-includes");
8859 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8860 CmdArgs.push_back(Elt: "-sys-header-deps");
8861 }
8862
8863 // This controls whether or not we emit RTTI data for polymorphic types.
8864 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8865 /*Default=*/false))
8866 CmdArgs.push_back(Elt: "-fno-rtti-data");
8867
8868 // This controls whether or not we emit stack-protector instrumentation.
8869 // In MSVC, Buffer Security Check (/GS) is on by default.
8870 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8871 /*Default=*/true)) {
8872 CmdArgs.push_back(Elt: "-stack-protector");
8873 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8874 }
8875
8876 const Driver &D = getToolChain().getDriver();
8877
8878 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8879 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8880 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8881 if (types::isCXX(Id: InputType))
8882 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8883 CmdArgs.push_back(Elt: "-fexceptions");
8884 if (EH.Asynch)
8885 CmdArgs.push_back(Elt: "-fasync-exceptions");
8886 }
8887 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8888 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8889
8890 // /EP should expand to -E -P.
8891 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8892 CmdArgs.push_back(Elt: "-E");
8893 CmdArgs.push_back(Elt: "-P");
8894 }
8895
8896 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8897 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8898 Default: false)) {
8899 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8900 }
8901
8902 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8903 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8904 CmdArgs.push_back(Elt: "-fno-wchar");
8905 }
8906
8907 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8908 llvm::Triple::ArchType Arch = getToolChain().getArch();
8909 std::vector<std::string> Values =
8910 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8911 if (!Values.empty()) {
8912 llvm::SmallSet<std::string, 4> SupportedArches;
8913 if (Arch == llvm::Triple::x86)
8914 SupportedArches.insert(V: "IA32");
8915
8916 for (auto &V : Values)
8917 if (!SupportedArches.contains(V))
8918 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8919 << std::string("/arch:").append(str: V) << "/kernel";
8920 }
8921
8922 CmdArgs.push_back(Elt: "-fno-rtti");
8923 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8924 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8925 << "/kernel";
8926 }
8927
8928 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8929 Ids: options::OPT__SLASH_vlen_EQ_256,
8930 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8931 llvm::Triple::ArchType AT = getToolChain().getArch();
8932 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8933 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8934 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8935 "AVX10.2"};
8936
8937 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8938 if (Arch512.contains(V: Arch))
8939 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8940 else
8941 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8942 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8943 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8944 if (Arch512.contains(V: Arch))
8945 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8946 else if (Arch != "AVX" && Arch != "AVX2")
8947 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8948 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8949 } else {
8950 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8951 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8952 }
8953 } else {
8954 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8955 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8956 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8957 CmdArgs.push_back(Elt: "-target-feature");
8958 CmdArgs.push_back(Elt: "-amx-tile");
8959 }
8960 if (Arch == "AVX10.2") {
8961 CmdArgs.push_back(Elt: "-target-feature");
8962 CmdArgs.push_back(Elt: "+avx10.2");
8963 }
8964 }
8965
8966 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8967 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8968 if (MostGeneralArg && BestCaseArg)
8969 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8970 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8971
8972 if (MostGeneralArg) {
8973 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8974 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8975 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
8976
8977 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8978 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8979 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8980 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8981 << FirstConflict->getAsString(Args)
8982 << SecondConflict->getAsString(Args);
8983
8984 if (SingleArg)
8985 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8986 else if (MultipleArg)
8987 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8988 else
8989 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8990 }
8991
8992 if (Args.hasArg(Ids: options::OPT_regcall4))
8993 CmdArgs.push_back(Elt: "-regcall4");
8994
8995 // Parse the default calling convention options.
8996 if (Arg *CCArg =
8997 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
8998 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
8999 Ids: options::OPT__SLASH_Gregcall)) {
9000 unsigned DCCOptId = CCArg->getOption().getID();
9001 const char *DCCFlag = nullptr;
9002 bool ArchSupported = !isNVPTX;
9003 llvm::Triple::ArchType Arch = getToolChain().getArch();
9004 switch (DCCOptId) {
9005 case options::OPT__SLASH_Gd:
9006 DCCFlag = "-fdefault-calling-conv=cdecl";
9007 break;
9008 case options::OPT__SLASH_Gr:
9009 ArchSupported = Arch == llvm::Triple::x86;
9010 DCCFlag = "-fdefault-calling-conv=fastcall";
9011 break;
9012 case options::OPT__SLASH_Gz:
9013 ArchSupported = Arch == llvm::Triple::x86;
9014 DCCFlag = "-fdefault-calling-conv=stdcall";
9015 break;
9016 case options::OPT__SLASH_Gv:
9017 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9018 DCCFlag = "-fdefault-calling-conv=vectorcall";
9019 break;
9020 case options::OPT__SLASH_Gregcall:
9021 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9022 DCCFlag = "-fdefault-calling-conv=regcall";
9023 break;
9024 }
9025
9026 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9027 if (ArchSupported && DCCFlag)
9028 CmdArgs.push_back(Elt: DCCFlag);
9029 }
9030
9031 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
9032 CmdArgs.push_back(Elt: "-regcall4");
9033
9034 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
9035
9036 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
9037 CmdArgs.push_back(Elt: "-fdiagnostics-format");
9038 CmdArgs.push_back(Elt: "msvc");
9039 }
9040
9041 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
9042 CmdArgs.push_back(Elt: "-fms-kernel");
9043
9044 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9045 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9046 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
9047 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-required");
9048 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
9049 CmdArgs.push_back(Elt: "-fwinx64-eh-unwind=v2-best-effort");
9050
9051 // Handle the various /guard options. We don't immediately push back clang
9052 // args since there are /d2 args that can modify the behavior of /guard:cf.
9053 bool HasCFGuard = false;
9054 bool HasCFGuardNoChecks = false;
9055 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
9056 StringRef GuardArgs = A->getValue();
9057 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9058 // "ehcont-".
9059 if (GuardArgs.equals_insensitive(RHS: "cf")) {
9060 // Emit CFG instrumentation and the table of address-taken functions.
9061 HasCFGuard = true;
9062 HasCFGuardNoChecks = false;
9063 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
9064 // Emit only the table of address-taken functions.
9065 HasCFGuard = false;
9066 HasCFGuardNoChecks = true;
9067 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
9068 // Emit EH continuation table.
9069 CmdArgs.push_back(Elt: "-ehcontguard");
9070 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
9071 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
9072 // Do nothing, but we might want to emit a security warning in future.
9073 } else {
9074 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9075 }
9076 A->claim();
9077 }
9078
9079 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9080 // If CFG is not enabled, it is a no-op.
9081 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
9082 if (HasCFGuard) {
9083 HasCFGuard = false;
9084 HasCFGuardNoChecks = true;
9085 }
9086 }
9087
9088 if (HasCFGuard)
9089 CmdArgs.push_back(Elt: "-cfguard");
9090 else if (HasCFGuardNoChecks)
9091 CmdArgs.push_back(Elt: "-cfguard-no-checks");
9092
9093 // Control Flow Guard mechanism for Windows.
9094 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch_))
9095 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=check");
9096 else if (Args.hasArg(Ids: options::OPT__SLASH_d2guardcfgdispatch))
9097 CmdArgs.push_back(Elt: "-fwin-cfg-mechanism=dispatch");
9098
9099 for (const auto &FuncOverride :
9100 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
9101 CmdArgs.push_back(Elt: Args.MakeArgString(
9102 Str: Twine("-loader-replaceable-function=") + FuncOverride));
9103 }
9104
9105 if (Args.hasArg(Ids: options::OPT__SLASH_experimental_deterministic)) {
9106 CmdArgs.push_back(Elt: "-Wdate-time");
9107
9108 if (Args.hasArg(Ids: options::OPT_mincremental_linker_compatible)) {
9109 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
9110 << "/experimental:deterministic"
9111 << "/Brepro-";
9112 }
9113 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9114 // deterministic result, but we force this timestamp to 0, which also
9115 // produces deterministic result.
9116 CmdArgs.push_back(Elt: "-mno-incremental-linker-compatible");
9117 }
9118
9119 bool HasNoDateTime = Args.hasFlag(Pos: options::OPT__SLASH_d1nodatetime,
9120 Neg: options::OPT__SLASH_d1nodatetime_, Default: false);
9121
9122 if (HasNoDateTime)
9123 CmdArgs.push_back(Elt: "-init-datetime-macros=undefined");
9124
9125 // /Brepro is an alias for -mincremental-linker-compatible option.
9126 if (!Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
9127 Neg: options::OPT_mno_incremental_linker_compatible,
9128 Default: getToolChain()
9129 .getTriple()
9130 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9131 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9132 // This option does not allow the user redefinitions for these macros.
9133 if (!HasNoDateTime)
9134 CmdArgs.push_back(Elt: "-init-datetime-macros=literalone");
9135 }
9136}
9137
9138const char *Clang::getBaseInputName(const ArgList &Args,
9139 const InputInfo &Input) {
9140 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
9141}
9142
9143const char *Clang::getBaseInputStem(const ArgList &Args,
9144 const InputInfoList &Inputs) {
9145 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
9146
9147 if (const char *End = strrchr(s: Str, c: '.'))
9148 return Args.MakeArgString(Str: std::string(Str, End));
9149
9150 return Str;
9151}
9152
9153const char *Clang::getDependencyFileName(const ArgList &Args,
9154 const InputInfoList &Inputs) {
9155 // FIXME: Think about this more.
9156
9157 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
9158 SmallString<128> OutputFilename(OutputOpt->getValue());
9159 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
9160 return Args.MakeArgString(Str: OutputFilename);
9161 }
9162
9163 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
9164}
9165
9166// Begin ClangAs
9167
9168void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9169 ArgStringList &CmdArgs) const {
9170 StringRef CPUName;
9171 StringRef ABIName;
9172 const llvm::Triple &Triple = getToolChain().getTriple();
9173 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9174
9175 CmdArgs.push_back(Elt: "-target-abi");
9176 CmdArgs.push_back(Elt: ABIName.data());
9177}
9178
9179void ClangAs::AddX86TargetArgs(const ArgList &Args,
9180 ArgStringList &CmdArgs) const {
9181 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
9182 /*IsLTO=*/false);
9183
9184 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
9185 StringRef Value = A->getValue();
9186 if (Value == "intel" || Value == "att") {
9187 CmdArgs.push_back(Elt: "-mllvm");
9188 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
9189 } else {
9190 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
9191 << A->getSpelling() << Value;
9192 }
9193 }
9194}
9195
9196void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9197 ArgStringList &CmdArgs) const {
9198 CmdArgs.push_back(Elt: "-target-abi");
9199 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
9200 Triple: getToolChain().getTriple())
9201 .data());
9202}
9203
9204void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9205 ArgStringList &CmdArgs) const {
9206 const llvm::Triple &Triple = getToolChain().getTriple();
9207 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9208
9209 CmdArgs.push_back(Elt: "-target-abi");
9210 CmdArgs.push_back(Elt: ABIName.data());
9211
9212 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9213 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9214 CmdArgs.push_back(Elt: "-mllvm");
9215 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
9216 }
9217}
9218
9219void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
9220 const InputInfo &Output, const InputInfoList &Inputs,
9221 const ArgList &Args,
9222 const char *LinkingOutput) const {
9223 ArgStringList CmdArgs;
9224
9225 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9226 const InputInfo &Input = Inputs[0];
9227
9228 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9229 const std::string &TripleStr = Triple.getTriple();
9230 const auto &D = getToolChain().getDriver();
9231
9232 // Don't warn about "clang -w -c foo.s"
9233 Args.ClaimAllArgs(Id0: options::OPT_w);
9234 // and "clang -emit-llvm -c foo.s"
9235 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
9236
9237 claimNoWarnArgs(Args);
9238
9239 // Invoke ourselves in -cc1as mode.
9240 //
9241 // FIXME: Implement custom jobs for internal actions.
9242 CmdArgs.push_back(Elt: "-cc1as");
9243
9244 // Add the "effective" target triple.
9245 CmdArgs.push_back(Elt: "-triple");
9246 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
9247
9248 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
9249
9250 // Set the output mode, we currently only expect to be used as a real
9251 // assembler.
9252 CmdArgs.push_back(Elt: "-filetype");
9253 CmdArgs.push_back(Elt: "obj");
9254
9255 // Set the main file name, so that debug info works even with
9256 // -save-temps or preprocessed assembly.
9257 CmdArgs.push_back(Elt: "-main-file-name");
9258 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
9259
9260 // Add the target cpu
9261 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
9262 if (!CPU.empty()) {
9263 CmdArgs.push_back(Elt: "-target-cpu");
9264 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
9265 }
9266
9267 // Add the target features
9268 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
9269
9270 // Ignore explicit -force_cpusubtype_ALL option.
9271 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
9272
9273 // Pass along any -I options so we get proper .include search paths.
9274 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
9275
9276 // Pass along any --embed-dir or similar options so we get proper embed paths.
9277 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
9278
9279 // Determine the original source input.
9280 auto FindSource = [](const Action *S) -> const Action * {
9281 while (S->getKind() != Action::InputClass) {
9282 assert(!S->getInputs().empty() && "unexpected root action!");
9283 S = S->getInputs()[0];
9284 }
9285 return S;
9286 };
9287 const Action *SourceAction = FindSource(&JA);
9288
9289 // Forward -g and handle debug info related flags, assuming we are dealing
9290 // with an actual assembly file.
9291 bool WantDebug = false;
9292 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
9293 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
9294 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
9295 !A->getOption().matches(ID: options::OPT_ggdb0);
9296
9297 // If a -gdwarf argument appeared, remember it.
9298 bool EmitDwarf = false;
9299 if (const Arg *A = getDwarfNArg(Args))
9300 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9301
9302 bool EmitCodeView = false;
9303 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
9304 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
9305
9306 // If the user asked for debug info but did not explicitly specify -gcodeview
9307 // or -gdwarf, ask the toolchain for the default format.
9308 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9309 switch (getToolChain().getDefaultDebugFormat()) {
9310 case llvm::codegenoptions::DIF_CodeView:
9311 EmitCodeView = true;
9312 break;
9313 case llvm::codegenoptions::DIF_DWARF:
9314 EmitDwarf = true;
9315 break;
9316 }
9317 }
9318
9319 // If the arguments don't imply DWARF, don't emit any debug info here.
9320 if (!EmitDwarf)
9321 WantDebug = false;
9322
9323 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9324 llvm::codegenoptions::NoDebugInfo;
9325
9326 // Add the -fdebug-compilation-dir flag if needed.
9327 const char *DebugCompilationDir =
9328 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
9329
9330 if (SourceAction->getType() == types::TY_Asm ||
9331 SourceAction->getType() == types::TY_PP_Asm) {
9332 // You might think that it would be ok to set DebugInfoKind outside of
9333 // the guard for source type, however there is a test which asserts
9334 // that some assembler invocation receives no -debug-info-kind,
9335 // and it's not clear whether that test is just overly restrictive.
9336 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9337 : llvm::codegenoptions::NoDebugInfo);
9338
9339 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
9340 CmdArgs);
9341
9342 // Set the AT_producer to the clang version when using the integrated
9343 // assembler on assembly source files.
9344 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
9345 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
9346
9347 // And pass along -I options
9348 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
9349 }
9350 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
9351 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9352 DebuggerTuning: llvm::DebuggerKind::Default);
9353 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
9354 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
9355
9356 // Handle -fPIC et al -- the relocation-model affects the assembler
9357 // for some targets.
9358 llvm::Reloc::Model RelocationModel;
9359 unsigned PICLevel;
9360 bool IsPIE;
9361 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
9362 ParsePICArgs(ToolChain: getToolChain(), Args);
9363
9364 const char *RMName = RelocationModelName(Model: RelocationModel);
9365 if (RMName) {
9366 CmdArgs.push_back(Elt: "-mrelocation-model");
9367 CmdArgs.push_back(Elt: RMName);
9368 }
9369
9370 // Optionally embed the -cc1as level arguments into the debug info, for build
9371 // analysis.
9372 if (getToolChain().UseDwarfDebugFlags()) {
9373 ArgStringList OriginalArgs;
9374 for (const auto &Arg : Args)
9375 Arg->render(Args, Output&: OriginalArgs);
9376
9377 SmallString<256> Flags;
9378 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9379 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
9380 for (const char *OriginalArg : OriginalArgs) {
9381 SmallString<128> EscapedArg;
9382 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
9383 Flags += " ";
9384 Flags += EscapedArg;
9385 }
9386 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
9387 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
9388 }
9389
9390 // FIXME: Add -static support, once we have it.
9391
9392 // Add target specific flags.
9393 switch (getToolChain().getArch()) {
9394 default:
9395 break;
9396
9397 case llvm::Triple::mips:
9398 case llvm::Triple::mipsel:
9399 case llvm::Triple::mips64:
9400 case llvm::Triple::mips64el:
9401 AddMIPSTargetArgs(Args, CmdArgs);
9402 break;
9403
9404 case llvm::Triple::x86:
9405 case llvm::Triple::x86_64:
9406 AddX86TargetArgs(Args, CmdArgs);
9407 break;
9408
9409 case llvm::Triple::arm:
9410 case llvm::Triple::armeb:
9411 case llvm::Triple::thumb:
9412 case llvm::Triple::thumbeb:
9413 // This isn't in AddARMTargetArgs because we want to do this for assembly
9414 // only, not C/C++.
9415 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9416 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9417 CmdArgs.push_back(Elt: "-mllvm");
9418 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
9419 }
9420 break;
9421
9422 case llvm::Triple::aarch64:
9423 case llvm::Triple::aarch64_32:
9424 case llvm::Triple::aarch64_be:
9425 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
9426 CmdArgs.push_back(Elt: "-mllvm");
9427 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
9428 }
9429 break;
9430
9431 case llvm::Triple::loongarch32:
9432 case llvm::Triple::loongarch64:
9433 AddLoongArchTargetArgs(Args, CmdArgs);
9434 break;
9435
9436 case llvm::Triple::riscv32:
9437 case llvm::Triple::riscv64:
9438 case llvm::Triple::riscv32be:
9439 case llvm::Triple::riscv64be:
9440 AddRISCVTargetArgs(Args, CmdArgs);
9441 break;
9442
9443 case llvm::Triple::hexagon:
9444 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
9445 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
9446 CmdArgs.push_back(Elt: "-mllvm");
9447 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
9448 }
9449 break;
9450 }
9451
9452 // Consume all the warning flags. Usually this would be handled more
9453 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9454 // doesn't handle that so rather than warning about unused flags that are
9455 // actually used, we'll lie by omission instead.
9456 // FIXME: Stop lying and consume only the appropriate driver flags
9457 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9458
9459 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9460 D: getToolChain().getDriver());
9461
9462 // Forward -Xclangas arguments to -cc1as
9463 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9464 Arg->claim();
9465 CmdArgs.push_back(Elt: Arg->getValue());
9466 }
9467
9468 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9469
9470 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9471 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9472 OutputFileName: Output.getFilename());
9473
9474 // Fixup any previous commands that use -object-file-name because when we
9475 // generated them, the final .obj name wasn't yet known.
9476 for (Command &J : C.getJobs()) {
9477 if (SourceAction != FindSource(&J.getSource()))
9478 continue;
9479 auto &JArgs = J.getArguments();
9480 for (unsigned I = 0; I < JArgs.size(); ++I) {
9481 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9482 Output.isFilename()) {
9483 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9484 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9485 OutputFileName: Output.getFilename());
9486 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9487 J.replaceArguments(List: NewArgs);
9488 break;
9489 }
9490 }
9491 }
9492
9493 assert(Output.isFilename() && "Unexpected lipo output.");
9494 CmdArgs.push_back(Elt: "-o");
9495 CmdArgs.push_back(Elt: Output.getFilename());
9496
9497 const llvm::Triple &T = getToolChain().getTriple();
9498 Arg *A;
9499 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9500 T.isOSBinFormatELF()) {
9501 CmdArgs.push_back(Elt: "-split-dwarf-output");
9502 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9503 }
9504
9505 if (Triple.isAMDGPU())
9506 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9507
9508 assert(Input.isFilename() && "Invalid input.");
9509 CmdArgs.push_back(Elt: Input.getFilename());
9510
9511 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9512 if (D.CC1Main && !D.CCGenDiagnostics) {
9513 // Invoke cc1as directly in this process.
9514 C.addCommand(Cmd: std::make_unique<CC1Command>(
9515 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9516 args: Output, args: D.getPrependArg()));
9517 } else {
9518 C.addCommand(Cmd: std::make_unique<Command>(
9519 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9520 args: Output, args: D.getPrependArg()));
9521 }
9522}
9523
9524// Begin OffloadBundler
9525void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9526 const InputInfo &Output,
9527 const InputInfoList &Inputs,
9528 const llvm::opt::ArgList &TCArgs,
9529 const char *LinkingOutput) const {
9530 // The version with only one output is expected to refer to a bundling job.
9531 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9532
9533 // The bundling command looks like this:
9534 // clang-offload-bundler -type=bc
9535 // -targets=host-triple,openmp-triple1,openmp-triple2
9536 // -output=output_file
9537 // -input=unbundle_file_host
9538 // -input=unbundle_file_tgt1
9539 // -input=unbundle_file_tgt2
9540
9541 ArgStringList CmdArgs;
9542
9543 // Get the type.
9544 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9545 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9546
9547 assert(JA.getInputs().size() == Inputs.size() &&
9548 "Not have inputs for all dependence actions??");
9549
9550 // Get the targets.
9551 SmallString<128> Triples;
9552 Triples += "-targets=";
9553 for (unsigned I = 0; I < Inputs.size(); ++I) {
9554 if (I)
9555 Triples += ',';
9556
9557 // Find ToolChain for this input.
9558 Action::OffloadKind CurKind = Action::OFK_Host;
9559 const ToolChain *CurTC = &getToolChain();
9560 const Action *CurDep = JA.getInputs()[I];
9561
9562 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9563 CurTC = nullptr;
9564 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) {
9565 assert(CurTC == nullptr && "Expected one dependence!");
9566 CurKind = A->getOffloadingDeviceKind();
9567 CurTC = TC;
9568 });
9569 }
9570 Triples += Action::GetOffloadKindName(Kind: CurKind);
9571 Triples += '-';
9572 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9573 Args: TCArgs, BA: CurDep->getOffloadingArch()))
9574 .normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9575
9576 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9577 Triples += '-';
9578 Triples += CurDep->getOffloadingArch().ArchName;
9579 }
9580 }
9581 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9582
9583 // Get bundled file command.
9584 CmdArgs.push_back(
9585 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9586
9587 // Get unbundled files command.
9588 for (unsigned I = 0; I < Inputs.size(); ++I) {
9589 SmallString<128> UB;
9590 UB += "-input=";
9591
9592 // Find ToolChain for this input.
9593 const ToolChain *CurTC = &getToolChain();
9594 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9595 CurTC = nullptr;
9596 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, BoundArch) {
9597 assert(CurTC == nullptr && "Expected one dependence!");
9598 CurTC = TC;
9599 });
9600 UB += C.addTempFile(
9601 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9602 } else {
9603 UB += CurTC->getInputFilename(Input: Inputs[I]);
9604 }
9605 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9606 }
9607 addOffloadCompressArgs(TCArgs, CmdArgs);
9608 // All the inputs are encoded as commands.
9609 C.addCommand(Cmd: std::make_unique<Command>(
9610 args: JA, args: *this, args: ResponseFileSupport::None(),
9611 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9612 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9613}
9614
9615void OffloadBundler::ConstructJobMultipleOutputs(
9616 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9617 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9618 const char *LinkingOutput) const {
9619 // The version with multiple outputs is expected to refer to a unbundling job.
9620 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
9621
9622 // The unbundling command looks like this:
9623 // clang-offload-bundler -type=bc
9624 // -targets=host-triple,openmp-triple1,openmp-triple2
9625 // -input=input_file
9626 // -output=unbundle_file_host
9627 // -output=unbundle_file_tgt1
9628 // -output=unbundle_file_tgt2
9629 // -unbundle
9630
9631 ArgStringList CmdArgs;
9632
9633 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9634 InputInfo Input = Inputs.front();
9635
9636 // Get the type.
9637 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9638 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
9639
9640 // Get the targets.
9641 SmallString<128> Triples;
9642 Triples += "-targets=";
9643 auto DepInfo = UA.getDependentActionsInfo();
9644 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9645 if (I)
9646 Triples += ',';
9647
9648 auto &Dep = DepInfo[I];
9649 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
9650 Triples += '-';
9651 Triples += llvm::Triple(Dep.DependentToolChain->ComputeEffectiveClangTriple(
9652 Args: TCArgs, BA: Dep.DependentBoundArch))
9653 .normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9654
9655 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9656 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9657 !Dep.DependentBoundArch.empty()) {
9658 Triples += '-';
9659 Triples += Dep.DependentBoundArch.ArchName;
9660 }
9661 }
9662
9663 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9664
9665 // Get bundled file command.
9666 CmdArgs.push_back(
9667 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
9668
9669 // Get unbundled files command.
9670 for (unsigned I = 0; I < Outputs.size(); ++I) {
9671 SmallString<128> UB;
9672 UB += "-output=";
9673 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
9674 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9675 }
9676 CmdArgs.push_back(Elt: "-unbundle");
9677 CmdArgs.push_back(Elt: "-allow-missing-bundles");
9678 if (TCArgs.hasArg(Ids: options::OPT_v))
9679 CmdArgs.push_back(Elt: "-verbose");
9680
9681 // All the inputs are encoded as commands.
9682 C.addCommand(Cmd: std::make_unique<Command>(
9683 args: JA, args: *this, args: ResponseFileSupport::None(),
9684 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9685 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Outputs));
9686}
9687
9688void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9689 const InputInfo &Output,
9690 const InputInfoList &Inputs,
9691 const llvm::opt::ArgList &Args,
9692 const char *LinkingOutput) const {
9693 ArgStringList CmdArgs;
9694
9695 // Add the output file name.
9696 assert(Output.isFilename() && "Invalid output.");
9697 CmdArgs.push_back(Elt: "-o");
9698 CmdArgs.push_back(Elt: Output.getFilename());
9699
9700 // Create the inputs to bundle the needed metadata.
9701 for (const InputInfo &Input : Inputs) {
9702 const Action *OffloadAction = Input.getAction();
9703 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9704 const ArgList &TCArgs =
9705 C.getArgsForToolChain(TC, BA: OffloadAction->getOffloadingArch(),
9706 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9707 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9708 BoundArch Arch = OffloadAction->getOffloadingArch();
9709 if (Arch.empty())
9710 Arch = BoundArch(TCArgs.getLastArgValue(Id: options::OPT_march_EQ));
9711
9712 StringRef Kind =
9713 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9714
9715 ArgStringList Features;
9716 SmallVector<StringRef> FeatureArgs;
9717 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9718 ForAS: false);
9719 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9720 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9721
9722 // TODO: We need to pass in the full target-id and handle it properly in the
9723 // linker wrapper.
9724 SmallVector<std::string> Parts{
9725 "file=" + File.str(),
9726 "triple=" + TC->ComputeEffectiveClangTriple(Args: TCArgs, BA: Arch),
9727 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9728 "kind=" + Kind.str(),
9729 };
9730
9731 if (TC->isUsingLTO(Args: TCArgs, Kind: OffloadAction->getOffloadingDeviceKind()))
9732 for (StringRef Feature : FeatureArgs)
9733 Parts.emplace_back(Args: "feature=" + Feature.str());
9734
9735 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9736 }
9737
9738 C.addCommand(Cmd: std::make_unique<Command>(
9739 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9740 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9741 args&: CmdArgs, args: Inputs, args: Output));
9742}
9743
9744// Options that need the profile compiler-rt library on the target toolchain.
9745// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9746// too.
9747static bool requiresProfileRT(unsigned ID) {
9748 switch (ID) {
9749 case options::OPT_fprofile_generate:
9750 case options::OPT_fprofile_generate_EQ:
9751 case options::OPT_fprofile_instr_generate:
9752 case options::OPT_fprofile_instr_generate_EQ:
9753 case options::OPT_fcoverage_mapping:
9754 case options::OPT_fno_coverage_mapping:
9755 case options::OPT_fcoverage_compilation_dir_EQ:
9756 case options::OPT_ffile_compilation_dir_EQ:
9757 case options::OPT_fcoverage_prefix_map_EQ:
9758 return true;
9759 default:
9760 return false;
9761 }
9762}
9763
9764// Options that need the ubsan compiler-rt library on the target toolchain.
9765static bool requiresUBSanRT(unsigned ID) {
9766 switch (ID) {
9767 case options::OPT_fsanitize_EQ:
9768 case options::OPT_fno_sanitize_EQ:
9769 case options::OPT_fsanitize_minimal_runtime:
9770 case options::OPT_fno_sanitize_minimal_runtime:
9771 return true;
9772 default:
9773 return false;
9774 }
9775}
9776
9777void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9778 const InputInfo &Output,
9779 const InputInfoList &Inputs,
9780 const ArgList &Args,
9781 const char *LinkingOutput) const {
9782 using namespace options;
9783
9784 // A list of permitted options that will be forwarded to the embedded device
9785 // compilation job.
9786 const llvm::DenseSet<unsigned> CompilerOptions{
9787 OPT_v,
9788 OPT_hip_path_EQ,
9789 OPT_O_Group,
9790 OPT_g_Group,
9791 OPT_g_flags_Group,
9792 OPT_R_value_Group,
9793 OPT_R_Group,
9794 OPT_Xcuda_ptxas,
9795 OPT_ftime_report,
9796 OPT_ftime_trace,
9797 OPT_ftime_trace_EQ,
9798 OPT_ftime_trace_granularity_EQ,
9799 OPT_ftime_trace_verbose,
9800 OPT_opt_record_file,
9801 OPT_opt_record_format,
9802 OPT_opt_record_passes,
9803 OPT_fsave_optimization_record,
9804 OPT_fsave_optimization_record_EQ,
9805 OPT_fno_save_optimization_record,
9806 OPT_foptimization_record_file_EQ,
9807 OPT_foptimization_record_passes_EQ,
9808 OPT_save_temps,
9809 OPT_save_temps_EQ,
9810 OPT_mcode_object_version_EQ,
9811 OPT_load,
9812 OPT_no_canonical_prefixes,
9813 OPT_fno_lto,
9814 OPT_flto,
9815 OPT_flto_partitions_EQ,
9816 OPT_flto_EQ,
9817 OPT_hipspv_pass_plugin_EQ,
9818 OPT_use_spirv_backend,
9819 OPT_no_use_spirv_backend,
9820 OPT_fmultilib_flag,
9821 OPT_fprofile_generate,
9822 OPT_fprofile_generate_EQ,
9823 OPT_fprofile_instr_generate,
9824 OPT_fprofile_instr_generate_EQ,
9825 OPT_fcoverage_mapping,
9826 OPT_fno_coverage_mapping,
9827 OPT_fcoverage_compilation_dir_EQ,
9828 OPT_ffile_compilation_dir_EQ,
9829 OPT_fcoverage_prefix_map_EQ,
9830 OPT_fsanitize_EQ,
9831 OPT_fno_sanitize_EQ,
9832 OPT_fsanitize_minimal_runtime,
9833 OPT_fno_sanitize_minimal_runtime,
9834 OPT_fsanitize_trap_EQ,
9835 OPT_fno_sanitize_trap_EQ,
9836 OPT_fslp_vectorize,
9837 OPT_fno_slp_vectorize,
9838 OPT_hipstdpar};
9839 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9840 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9841 return TC.getVFS().exists(
9842 Path: TC.getCompilerRT(Args, Component: Name, Type: ToolChain::FT_Static));
9843 };
9844 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9845 unsigned ID = A->getOption().getID();
9846 // Don't forward profiling arguments if the toolchain doesn't support it.
9847 // Without this check using it on the host would result in linker errors.
9848 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9849 // together to avoid a device cc1 diagnostic.
9850 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9851 return false;
9852 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9853 // Without this check using it on the host would result in linker errors.
9854 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9855 return false;
9856 // Don't forward -mllvm to toolchains that don't support LLVM.
9857 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9858 };
9859 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9860 const ToolChain &TC) {
9861 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9862 if (A->getOption().matches(ID: OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9863 return false;
9864 return (Set.contains(V: A->getOption().getID()) ||
9865 (A->getOption().getGroup().isValid() &&
9866 Set.contains(V: A->getOption().getGroup().getID()))) &&
9867 ShouldForwardForToolChain(A, TC);
9868 };
9869
9870 ArgStringList CmdArgs;
9871 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9872 Action::OFK_HIP, Action::OFK_SYCL}) {
9873 auto TCRange = C.getOffloadToolChains(Kind);
9874 for (auto &I : llvm::make_range(p: TCRange)) {
9875 const ToolChain *TC = I.second;
9876
9877 // We do not use a bound architecture here so options passed only to a
9878 // specific architecture via -Xarch_<cpu> will not be forwarded.
9879 ArgStringList CompilerArgs;
9880 ArgStringList LinkerArgs;
9881 const DerivedArgList &ToolChainArgs =
9882 C.getArgsForToolChain(TC, /*BA=*/{}, DeviceOffloadKind: Kind);
9883 for (Arg *A : ToolChainArgs) {
9884 if (A->getOption().matches(ID: OPT_Zlinker_input))
9885 LinkerArgs.emplace_back(Args: A->getValue());
9886 else if (ShouldForward(CompilerOptions, A, *TC)) {
9887 A->claim();
9888 A->render(Args, Output&: CompilerArgs);
9889 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9890 A->claim();
9891 A->render(Args, Output&: LinkerArgs);
9892 }
9893 }
9894
9895 // If the user explicitly requested it via `--offload-arch` we should
9896 // extract it from any static libraries if present.
9897 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9898 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9899
9900 // If this is OpenMP the device linker will need `-lompdevice`.
9901 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9902 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9903 LinkerArgs.emplace_back(Args: "-lompdevice");
9904
9905 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9906 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9907 // flags to normal compilation.
9908 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9909 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9910 if (TC->getTriple().isSPIRV() &&
9911 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9912 Kind != Action::OFK_SYCL && !TC->isUsingLTO(Args: ToolChainArgs, Kind)) {
9913 // For SPIR-V some functions will be defined by the runtime so allow
9914 // unresolved symbols in `spirv-link`.
9915 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9916 // Don't optimize out exported symbols.
9917 LinkerArgs.emplace_back(Args: "--create-library");
9918 }
9919
9920 // Forward the SYCL device image split option to clang-sycl-linker.
9921 // The driver and clang-sycl-linker share the same value vocabulary, so
9922 // the value is passed through verbatim after validation.
9923 if (Kind == Action::OFK_SYCL) {
9924 if (Arg *A =
9925 ToolChainArgs.getLastArg(Ids: OPT_fsycl_device_image_split_EQ)) {
9926 StringRef Mode = A->getValue();
9927 if (Mode != "kernel" && Mode != "translation_unit" &&
9928 Mode != "link_unit")
9929 C.getDriver().Diag(DiagID: clang::diag::err_drv_invalid_value)
9930 << A->getSpelling() << Mode;
9931 else
9932 LinkerArgs.emplace_back(
9933 Args: Args.MakeArgString(Str: "--module-split-mode=" + Mode));
9934 }
9935 }
9936
9937 // Forward all of these to the appropriate toolchain.
9938 for (StringRef Arg : CompilerArgs)
9939 CmdArgs.push_back(Elt: Args.MakeArgString(
9940 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9941 for (StringRef Arg : LinkerArgs)
9942 CmdArgs.push_back(Elt: Args.MakeArgString(
9943 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9944
9945 // Forward the LTO mode for this toolchain.
9946 auto DeviceLTOMode = TC->getLTOMode(Args: ToolChainArgs, Kind);
9947 if (DeviceLTOMode == LTOK_Full)
9948 CmdArgs.push_back(Elt: Args.MakeArgString(
9949 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9950 else if (DeviceLTOMode == LTOK_Thin) {
9951 CmdArgs.push_back(Elt: Args.MakeArgString(
9952 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9953 if (TC->getTriple().isAMDGPU()) {
9954 CmdArgs.push_back(
9955 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9956 "=-plugin-opt=-force-import-all"));
9957 CmdArgs.push_back(
9958 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9959 "=-plugin-opt=-avail-extern-to-local"));
9960 CmdArgs.push_back(Elt: Args.MakeArgString(
9961 Str: "--device-linker=" + TC->getTripleString() +
9962 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9963 if (Kind == Action::OFK_OpenMP) {
9964 CmdArgs.push_back(
9965 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9966 "=-plugin-opt=-amdgpu-internalize-symbols"));
9967 }
9968 }
9969 }
9970 }
9971 }
9972
9973 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9974 CmdArgs.push_back(
9975 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
9976 else
9977 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
9978 getToolChain().getTripleString()));
9979
9980 // CMake hack, suppress passing verbose arguments for the special-case HIP
9981 // non-RDC mode compilation. This confuses default CMake implicit linker
9982 // argument parsing when the language is set to HIP and the system linker is
9983 // also `ld.lld`.
9984 if (Args.hasArg(Ids: options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9985 CmdArgs.push_back(Elt: "--wrapper-verbose");
9986 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ)) {
9987 CmdArgs.push_back(
9988 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9989 CmdArgs.push_back(Elt: Args.MakeArgString(
9990 Str: Twine("--device-compiler=--cuda-path=") + A->getValue()));
9991 }
9992 if (Arg *A = Args.getLastArg(Ids: options::OPT_rocm_path_EQ)) {
9993 CmdArgs.push_back(Elt: Args.MakeArgString(
9994 Str: Twine("--device-compiler=--rocm-path=") + A->getValue()));
9995 }
9996
9997 // Construct the link job so we can wrap around it.
9998 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9999 const auto &LinkCommand = C.getJobs().getJobs().back();
10000
10001 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10002 // wrapper.
10003 for (Arg *A :
10004 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
10005 StringRef Val = A->getValue(N: 0);
10006 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10007 auto WrapperOption =
10008 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10009 if (Val.empty())
10010 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
10011 else
10012 CmdArgs.push_back(Elt: Args.MakeArgString(
10013 Str: WrapperOption +
10014 ToolChain::normalizeOffloadTriple(OrigTT: Val.drop_front()).str() + "=" +
10015 A->getValue(N: 1)));
10016 }
10017 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
10018 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
10019
10020 // Embed bitcode instead of an object in JIT mode.
10021 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
10022 Neg: options::OPT_fno_openmp_target_jit, Default: false))
10023 CmdArgs.push_back(Elt: "--embed-bitcode");
10024
10025 // Save temporary files created by the linker wrapper.
10026 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
10027 Args.hasArg(Ids: options::OPT_save_temps))
10028 CmdArgs.push_back(Elt: "--save-temps");
10029
10030 // Pass in the C library for GPUs if present and not disabled.
10031 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
10032 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
10033 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
10034 Ids: options::OPT_nogpulibc)) {
10035 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
10036 // The device C library is only available for NVPTX and AMDGPU targets
10037 // and we only link it by default for OpenMP currently.
10038 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10039 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
10040 return;
10041 bool HasLibC = TC.getStdlibIncludePath().has_value();
10042 if (HasLibC) {
10043 CmdArgs.push_back(Elt: Args.MakeArgString(
10044 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10045 CmdArgs.push_back(Elt: Args.MakeArgString(
10046 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10047 }
10048 auto HasCompilerRT = getToolChain().getVFS().exists(
10049 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
10050 /*IsFortran=*/false));
10051 if (HasCompilerRT)
10052 CmdArgs.push_back(
10053 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10054 "-lclang_rt.builtins"));
10055
10056 bool HasFlangRT = getToolChain().getVFS().exists(
10057 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
10058 /*IsFortran=*/true));
10059 if (HasFlangRT && C.getDriver().IsFlangMode())
10060 CmdArgs.push_back(
10061 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
10062 "-lflang_rt.runtime"));
10063 });
10064 }
10065
10066 // Add the linker arguments to be forwarded by the wrapper.
10067 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
10068 LinkCommand->getExecutable()));
10069
10070 // We use action type to differentiate two use cases of the linker wrapper.
10071 // TY_Image for normal linker wrapper work.
10072 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
10073 assert(JA.getType() == types::TY_HIP_FATBIN ||
10074 JA.getType() == types::TY_Image);
10075 if (JA.getType() == types::TY_HIP_FATBIN) {
10076 CmdArgs.push_back(Elt: "--emit-fatbin-only");
10077 CmdArgs.append(IL: {"-o", Output.getFilename()});
10078 for (auto Input : Inputs)
10079 CmdArgs.push_back(Elt: Input.getFilename());
10080 } else {
10081 for (const char *LinkArg : LinkCommand->getArguments())
10082 CmdArgs.push_back(Elt: LinkArg);
10083 }
10084
10085 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
10086
10087 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10088 if (OffloadJobs.A) {
10089 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10090 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
10091 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10092 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=" +
10093 Twine(OffloadJobs.NumThreads)));
10094 } else if (!OffloadJobs.A->isClaimed()) {
10095 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
10096 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10097 }
10098 }
10099
10100 // Propagate -no-canonical-prefixes.
10101 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
10102 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
10103
10104 const char *Exec =
10105 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
10106
10107 // Replace the executable and arguments of the link job with the
10108 // wrapper.
10109 LinkCommand->replaceExecutable(Exe: Exec);
10110 LinkCommand->replaceArguments(List: CmdArgs);
10111}
10112