1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/ARM.h"
11#include "Arch/LoongArch.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
14#include "Arch/RISCV.h"
15#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Hexagon.h"
18#include "PS4CPU.h"
19#include "clang/Basic/CLWarnings.h"
20#include "clang/Basic/CodeGenOptions.h"
21#include "clang/Basic/HeaderInclude.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/MakeSupport.h"
24#include "clang/Basic/ObjCRuntime.h"
25#include "clang/Basic/Version.h"
26#include "clang/Config/config.h"
27#include "clang/Driver/Action.h"
28#include "clang/Driver/CommonArgs.h"
29#include "clang/Driver/Distro.h"
30#include "clang/Driver/InputInfo.h"
31#include "clang/Driver/Options.h"
32#include "clang/Driver/SanitizerArgs.h"
33#include "clang/Driver/Types.h"
34#include "clang/Driver/XRayArgs.h"
35#include "llvm/ADT/ScopeExit.h"
36#include "llvm/ADT/SmallSet.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/BinaryFormat/Magic.h"
39#include "llvm/Config/llvm-config.h"
40#include "llvm/Frontend/Debug/Options.h"
41#include "llvm/Object/ObjectFile.h"
42#include "llvm/Option/ArgList.h"
43#include "llvm/Support/CodeGen.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/Compression.h"
46#include "llvm/Support/Error.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Path.h"
49#include "llvm/Support/Process.h"
50#include "llvm/Support/YAMLParser.h"
51#include "llvm/TargetParser/AArch64TargetParser.h"
52#include "llvm/TargetParser/ARMTargetParserCommon.h"
53#include "llvm/TargetParser/Host.h"
54#include "llvm/TargetParser/LoongArchTargetParser.h"
55#include "llvm/TargetParser/PPCTargetParser.h"
56#include "llvm/TargetParser/RISCVISAInfo.h"
57#include "llvm/TargetParser/RISCVTargetParser.h"
58#include <cctype>
59
60using namespace clang::driver;
61using namespace clang::driver::tools;
62using namespace clang;
63using namespace llvm::opt;
64
65static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
66 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
67 options::OPT_fminimize_whitespace,
68 options::OPT_fno_minimize_whitespace,
69 options::OPT_fkeep_system_includes,
70 options::OPT_fno_keep_system_includes)) {
71 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
72 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
73 D.Diag(clang::diag::DiagID: err_drv_argument_only_allowed_with)
74 << A->getBaseArg().getAsString(Args)
75 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
76 }
77 }
78}
79
80static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
81 // In gcc, only ARM checks this, but it seems reasonable to check universally.
82 if (Args.hasArg(options::OPT_static))
83 if (const Arg *A =
84 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
85 D.Diag(diag::DiagID: err_drv_argument_not_allowed_with) << A->getAsString(Args)
86 << "-static";
87}
88
89/// Apply \a Work on the current tool chain \a RegularToolChain and any other
90/// offloading tool chain that is associated with the current action \a JA.
91static void
92forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
93 const ToolChain &RegularToolChain,
94 llvm::function_ref<void(const ToolChain &)> Work) {
95 // Apply Work on the current/regular tool chain.
96 Work(RegularToolChain);
97
98 // Apply Work on all the offloading tool chains associated with the current
99 // action.
100 if (JA.isHostOffloading(OKind: Action::OFK_Cuda))
101 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
102 else if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda))
103 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
104 else if (JA.isHostOffloading(OKind: Action::OFK_HIP))
105 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
106 else if (JA.isDeviceOffloading(OKind: Action::OFK_HIP))
107 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
108
109 if (JA.isHostOffloading(OKind: Action::OFK_OpenMP)) {
110 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
111 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
112 Work(*II->second);
113 } else if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
114 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
115
116 if (JA.isHostOffloading(OKind: Action::OFK_SYCL)) {
117 auto TCs = C.getOffloadToolChains<Action::OFK_SYCL>();
118 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
119 Work(*II->second);
120 } else if (JA.isDeviceOffloading(OKind: Action::OFK_SYCL))
121 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
122
123 //
124 // TODO: Add support for other offloading programming models here.
125 //
126}
127
128static bool
129shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
130 const llvm::Triple &Triple) {
131 // We use the zero-cost exception tables for Objective-C if the non-fragile
132 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
133 // later.
134 if (runtime.isNonFragile())
135 return true;
136
137 if (!Triple.isMacOSX())
138 return false;
139
140 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
141 (Triple.getArch() == llvm::Triple::x86_64 ||
142 Triple.getArch() == llvm::Triple::arm));
143}
144
145/// Adds exception related arguments to the driver command arguments. There's a
146/// main flag, -fexceptions and also language specific flags to enable/disable
147/// C++ and Objective-C exceptions. This makes it possible to for example
148/// disable C++ exceptions but enable Objective-C exceptions.
149static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
150 const ToolChain &TC, bool KernelOrKext,
151 const ObjCRuntime &objcRuntime,
152 ArgStringList &CmdArgs) {
153 const llvm::Triple &Triple = TC.getTriple();
154
155 if (KernelOrKext) {
156 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
157 // arguments now to avoid warnings about unused arguments.
158 Args.ClaimAllArgs(options::OPT_fexceptions);
159 Args.ClaimAllArgs(options::OPT_fno_exceptions);
160 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
161 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
162 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
163 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
164 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
165 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
166 return false;
167 }
168
169 // See if the user explicitly enabled exceptions.
170 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
171 false);
172
173 // Async exceptions are Windows MSVC only.
174 if (Triple.isWindowsMSVCEnvironment()) {
175 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
176 options::OPT_fno_async_exceptions, false);
177 if (EHa) {
178 CmdArgs.push_back(Elt: "-fasync-exceptions");
179 EH = true;
180 }
181 }
182
183 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
184 // is not necessarily sensible, but follows GCC.
185 if (types::isObjC(Id: InputType) &&
186 Args.hasFlag(options::OPT_fobjc_exceptions,
187 options::OPT_fno_objc_exceptions, true)) {
188 CmdArgs.push_back(Elt: "-fobjc-exceptions");
189
190 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
191 }
192
193 if (types::isCXX(Id: InputType)) {
194 // Disable C++ EH by default on XCore and PS4/PS5.
195 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
196 !Triple.isPS() && !Triple.isDriverKit();
197 Arg *ExceptionArg = Args.getLastArg(
198 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
199 options::OPT_fexceptions, options::OPT_fno_exceptions);
200 if (ExceptionArg)
201 CXXExceptionsEnabled =
202 ExceptionArg->getOption().matches(options::ID: OPT_fcxx_exceptions) ||
203 ExceptionArg->getOption().matches(options::ID: OPT_fexceptions);
204
205 if (CXXExceptionsEnabled) {
206 CmdArgs.push_back(Elt: "-fcxx-exceptions");
207
208 EH = true;
209 }
210 }
211
212 // OPT_fignore_exceptions means exception could still be thrown,
213 // but no clean up or catch would happen in current module.
214 // So we do not set EH to false.
215 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
216
217 Args.addOptInFlag(Output&: CmdArgs, options::Pos: OPT_fassume_nothrow_exception_dtor,
218 options::Neg: OPT_fno_assume_nothrow_exception_dtor);
219
220 if (EH)
221 CmdArgs.push_back(Elt: "-fexceptions");
222 return EH;
223}
224
225static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
226 const JobAction &JA) {
227 bool Default = true;
228 if (TC.getTriple().isOSDarwin()) {
229 // The native darwin assembler doesn't support the linker_option directives,
230 // so we disable them if we think the .s file will be passed to it.
231 Default = TC.useIntegratedAs();
232 }
233 // The linker_option directives are intended for host compilation.
234 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
235 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
236 Default = false;
237 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
238 Default);
239}
240
241/// Add a CC1 option to specify the debug compilation directory.
242static const char *addDebugCompDirArg(const ArgList &Args,
243 ArgStringList &CmdArgs,
244 const llvm::vfs::FileSystem &VFS) {
245 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
246 options::OPT_fdebug_compilation_dir_EQ)) {
247 if (A->getOption().matches(options::ID: OPT_ffile_compilation_dir_EQ))
248 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fdebug-compilation-dir=") +
249 A->getValue()));
250 else
251 A->render(Args, Output&: CmdArgs);
252 } else if (llvm::ErrorOr<std::string> CWD =
253 VFS.getCurrentWorkingDirectory()) {
254 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + *CWD));
255 }
256 StringRef Path(CmdArgs.back());
257 return Path.substr(Start: Path.find(C: '=') + 1).data();
258}
259
260static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
261 const char *DebugCompilationDir,
262 const char *OutputFileName) {
263 // No need to generate a value for -object-file-name if it was provided.
264 for (auto *Arg : Args.filtered(options::OPT_Xclang))
265 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
266 return;
267
268 if (Args.hasArg(options::OPT_object_file_name_EQ))
269 return;
270
271 SmallString<128> ObjFileNameForDebug(OutputFileName);
272 if (ObjFileNameForDebug != "-" &&
273 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
274 (!DebugCompilationDir ||
275 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
276 // Make the path absolute in the debug infos like MSVC does.
277 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
278 }
279 // If the object file name is a relative path, then always use Windows
280 // backslash style as -object-file-name is used for embedding object file path
281 // in codeview and it can only be generated when targeting on Windows.
282 // Otherwise, just use native absolute path.
283 llvm::sys::path::Style Style =
284 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
285 ? llvm::sys::path::Style::native
286 : llvm::sys::path::Style::windows_backslash;
287 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
288 style: Style);
289 CmdArgs.push_back(
290 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
291}
292
293/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
294static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
295 const ArgList &Args, ArgStringList &CmdArgs) {
296 auto AddOneArg = [&](StringRef Map, StringRef Name) {
297 if (!Map.contains(C: '='))
298 D.Diag(diag::DiagID: err_drv_invalid_argument_to_option) << Map << Name;
299 else
300 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
301 };
302
303 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
304 options::OPT_fdebug_prefix_map_EQ)) {
305 AddOneArg(A->getValue(), A->getOption().getName());
306 A->claim();
307 }
308 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
309 if (GlobalRemapEntry.empty())
310 return;
311 AddOneArg(GlobalRemapEntry, "environment");
312}
313
314/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
315static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
316 ArgStringList &CmdArgs) {
317 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
318 options::OPT_fmacro_prefix_map_EQ)) {
319 StringRef Map = A->getValue();
320 if (!Map.contains('='))
321 D.Diag(diag::err_drv_invalid_argument_to_option)
322 << Map << A->getOption().getName();
323 else
324 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
325 A->claim();
326 }
327}
328
329/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
330static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
331 ArgStringList &CmdArgs) {
332 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
333 options::OPT_fcoverage_prefix_map_EQ)) {
334 StringRef Map = A->getValue();
335 if (!Map.contains('='))
336 D.Diag(diag::err_drv_invalid_argument_to_option)
337 << Map << A->getOption().getName();
338 else
339 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
340 A->claim();
341 }
342}
343
344/// Add -x lang to \p CmdArgs for \p Input.
345static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
346 ArgStringList &CmdArgs) {
347 // When using -verify-pch, we don't want to provide the type
348 // 'precompiled-header' if it was inferred from the file extension
349 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
350 return;
351
352 CmdArgs.push_back(Elt: "-x");
353 if (Args.hasArg(options::OPT_rewrite_objc))
354 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
355 else {
356 // Map the driver type to the frontend type. This is mostly an identity
357 // mapping, except that the distinction between module interface units
358 // and other source files does not exist at the frontend layer.
359 const char *ClangType;
360 switch (Input.getType()) {
361 case types::TY_CXXModule:
362 ClangType = "c++";
363 break;
364 case types::TY_PP_CXXModule:
365 ClangType = "c++-cpp-output";
366 break;
367 default:
368 ClangType = types::getTypeName(Id: Input.getType());
369 break;
370 }
371 CmdArgs.push_back(Elt: ClangType);
372 }
373}
374
375static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
376 const JobAction &JA, const InputInfo &Output,
377 const ArgList &Args, SanitizerArgs &SanArgs,
378 ArgStringList &CmdArgs) {
379 const Driver &D = TC.getDriver();
380 const llvm::Triple &T = TC.getTriple();
381 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
382 options::OPT_fprofile_generate_EQ,
383 options::OPT_fno_profile_generate);
384 if (PGOGenerateArg &&
385 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
386 PGOGenerateArg = nullptr;
387
388 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
389
390 auto *ProfileGenerateArg = Args.getLastArg(
391 options::OPT_fprofile_instr_generate,
392 options::OPT_fprofile_instr_generate_EQ,
393 options::OPT_fno_profile_instr_generate);
394 if (ProfileGenerateArg &&
395 ProfileGenerateArg->getOption().matches(
396 options::OPT_fno_profile_instr_generate))
397 ProfileGenerateArg = nullptr;
398
399 if (PGOGenerateArg && ProfileGenerateArg)
400 D.Diag(diag::err_drv_argument_not_allowed_with)
401 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
402
403 auto *ProfileUseArg = getLastProfileUseArg(Args);
404
405 if (PGOGenerateArg && ProfileUseArg)
406 D.Diag(diag::err_drv_argument_not_allowed_with)
407 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
408
409 if (ProfileGenerateArg && ProfileUseArg)
410 D.Diag(diag::err_drv_argument_not_allowed_with)
411 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
412
413 if (CSPGOGenerateArg && PGOGenerateArg) {
414 D.Diag(diag::err_drv_argument_not_allowed_with)
415 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
416 PGOGenerateArg = nullptr;
417 }
418
419 if (TC.getTriple().isOSAIX()) {
420 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
421 D.Diag(diag::err_drv_unsupported_opt_for_target)
422 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
423 }
424
425 if (ProfileGenerateArg) {
426 if (ProfileGenerateArg->getOption().matches(
427 options::OPT_fprofile_instr_generate_EQ))
428 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
429 ProfileGenerateArg->getValue()));
430 // The default is to use Clang Instrumentation.
431 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
432 if (TC.getTriple().isWindowsMSVCEnvironment() &&
433 Args.hasFlag(options::OPT_frtlib_defaultlib,
434 options::OPT_fno_rtlib_defaultlib, true)) {
435 // Add dependent lib for clang_rt.profile
436 CmdArgs.push_back(Elt: Args.MakeArgString(
437 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
438 }
439 }
440
441 if (auto *ColdFuncCoverageArg = Args.getLastArg(
442 options::OPT_fprofile_generate_cold_function_coverage,
443 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
444 SmallString<128> Path(
445 ColdFuncCoverageArg->getOption().matches(
446 options::OPT_fprofile_generate_cold_function_coverage_EQ)
447 ? ColdFuncCoverageArg->getValue()
448 : "");
449 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
450 // FIXME: Idealy the file path should be passed through
451 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
452 // shared with other profile use path(see PGOOptions), we need to refactor
453 // PGOOptions to make it work.
454 CmdArgs.push_back(Elt: "-mllvm");
455 CmdArgs.push_back(Elt: Args.MakeArgString(
456 Str: Twine("--instrument-cold-function-only-path=") + Path));
457 CmdArgs.push_back(Elt: "-mllvm");
458 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
459 CmdArgs.push_back(Elt: "-mllvm");
460 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
461 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
462 }
463
464 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
465 if (!PGOGenerateArg && !CSPGOGenerateArg)
466 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
467 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
468 CmdArgs.push_back(Elt: "-mllvm");
469 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
470 }
471
472 Arg *PGOGenArg = nullptr;
473 if (PGOGenerateArg) {
474 assert(!CSPGOGenerateArg);
475 PGOGenArg = PGOGenerateArg;
476 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
477 }
478 if (CSPGOGenerateArg) {
479 assert(!PGOGenerateArg);
480 PGOGenArg = CSPGOGenerateArg;
481 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
482 }
483 if (PGOGenArg) {
484 if (TC.getTriple().isWindowsMSVCEnvironment() &&
485 Args.hasFlag(options::OPT_frtlib_defaultlib,
486 options::OPT_fno_rtlib_defaultlib, true)) {
487 // Add dependent lib for clang_rt.profile
488 CmdArgs.push_back(Elt: Args.MakeArgString(
489 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
490 }
491 if (PGOGenArg->getOption().matches(
492 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
493 : options::OPT_fcs_profile_generate_EQ)) {
494 SmallString<128> Path(PGOGenArg->getValue());
495 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
496 CmdArgs.push_back(
497 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
498 }
499 }
500
501 if (ProfileUseArg) {
502 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
503 CmdArgs.push_back(Elt: Args.MakeArgString(
504 Str: Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
505 else if ((ProfileUseArg->getOption().matches(
506 options::OPT_fprofile_use_EQ) ||
507 ProfileUseArg->getOption().matches(
508 options::OPT_fprofile_instr_use))) {
509 SmallString<128> Path(
510 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
511 if (Path.empty() || llvm::sys::fs::is_directory(Path))
512 llvm::sys::path::append(path&: Path, a: "default.profdata");
513 CmdArgs.push_back(
514 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-use-path=") + Path));
515 }
516 }
517
518 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
519 options::OPT_fno_test_coverage, false) ||
520 Args.hasArg(options::OPT_coverage);
521 bool EmitCovData = TC.needsGCovInstrumentation(Args);
522
523 if (Args.hasFlag(options::OPT_fcoverage_mapping,
524 options::OPT_fno_coverage_mapping, false)) {
525 if (!ProfileGenerateArg)
526 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
527 << "-fcoverage-mapping"
528 << "-fprofile-instr-generate";
529
530 CmdArgs.push_back(Elt: "-fcoverage-mapping");
531 }
532
533 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
534 false)) {
535 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
536 options::OPT_fno_coverage_mapping, false))
537 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
538 << "-fcoverage-mcdc"
539 << "-fcoverage-mapping";
540
541 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
542 }
543
544 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
545 options::OPT_fcoverage_compilation_dir_EQ)) {
546 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
547 CmdArgs.push_back(Elt: Args.MakeArgString(
548 Str: Twine("-fcoverage-compilation-dir=") + A->getValue()));
549 else
550 A->render(Args, Output&: CmdArgs);
551 } else if (llvm::ErrorOr<std::string> CWD =
552 D.getVFS().getCurrentWorkingDirectory()) {
553 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-compilation-dir=" + *CWD));
554 }
555
556 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
557 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
558 if (!Args.hasArg(options::OPT_coverage))
559 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
560 << "-fprofile-exclude-files="
561 << "--coverage";
562
563 StringRef v = Arg->getValue();
564 CmdArgs.push_back(
565 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
566 }
567
568 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
569 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
570 if (!Args.hasArg(options::OPT_coverage))
571 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
572 << "-fprofile-filter-files="
573 << "--coverage";
574
575 StringRef v = Arg->getValue();
576 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
577 }
578
579 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
580 StringRef Val = A->getValue();
581 if (Val == "atomic" || Val == "prefer-atomic")
582 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
583 else if (Val != "single")
584 D.Diag(diag::err_drv_unsupported_option_argument)
585 << A->getSpelling() << Val;
586 }
587 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
588 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
589 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
590 << A->getSpelling()
591 << "-fprofile-generate, -fprofile-instr-generate, or "
592 "-fcs-profile-generate";
593 else {
594 CmdArgs.push_back(Elt: "-fprofile-continuous");
595 // Platforms that require a bias variable:
596 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
597 CmdArgs.push_back(Elt: "-mllvm");
598 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
599 }
600 // -fprofile-instr-generate does not decide the profile file name in the
601 // FE, and so it does not define the filename symbol
602 // (__llvm_profile_filename). Instead, the runtime uses the name
603 // "default.profraw" for the profile file. When continuous mode is ON, we
604 // will create the filename symbol so that we can insert the "%c"
605 // modifier.
606 if (ProfileGenerateArg &&
607 (ProfileGenerateArg->getOption().matches(
608 options::OPT_fprofile_instr_generate) ||
609 (ProfileGenerateArg->getOption().matches(
610 options::OPT_fprofile_instr_generate_EQ) &&
611 strlen(ProfileGenerateArg->getValue()) == 0)))
612 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
613 }
614 }
615
616 int FunctionGroups = 1;
617 int SelectedFunctionGroup = 0;
618 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
619 StringRef Val = A->getValue();
620 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
621 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
622 }
623 if (const auto *A =
624 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
625 StringRef Val = A->getValue();
626 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
627 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
628 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
629 }
630 if (FunctionGroups != 1)
631 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
632 Twine(FunctionGroups)));
633 if (SelectedFunctionGroup != 0)
634 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
635 Twine(SelectedFunctionGroup)));
636
637 // Leave -fprofile-dir= an unused argument unless .gcda emission is
638 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
639 // the flag used. There is no -fno-profile-dir, so the user has no
640 // targeted way to suppress the warning.
641 Arg *FProfileDir = nullptr;
642 if (Args.hasArg(options::OPT_fprofile_arcs) ||
643 Args.hasArg(options::OPT_coverage))
644 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
645
646 // Put the .gcno and .gcda files (if needed) next to the primary output file,
647 // or fall back to a file in the current directory for `clang -c --coverage
648 // d/a.c` in the absence of -o.
649 if (EmitCovNotes || EmitCovData) {
650 SmallString<128> CoverageFilename;
651 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
652 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
653 // path separator.
654 CoverageFilename = DumpDir->getValue();
655 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
656 } else if (Arg *FinalOutput =
657 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
658 CoverageFilename = FinalOutput->getValue();
659 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
660 CoverageFilename = FinalOutput->getValue();
661 } else {
662 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
663 }
664 if (llvm::sys::path::is_relative(path: CoverageFilename))
665 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
666 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
667 if (EmitCovNotes) {
668 CmdArgs.push_back(
669 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
670 }
671
672 if (EmitCovData) {
673 if (FProfileDir) {
674 SmallString<128> Gcno = std::move(CoverageFilename);
675 CoverageFilename = FProfileDir->getValue();
676 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
677 }
678 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
679 CmdArgs.push_back(
680 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
681 }
682 }
683}
684
685static void
686RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
687 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
688 unsigned DwarfVersion,
689 llvm::DebuggerKind DebuggerTuning) {
690 addDebugInfoKind(CmdArgs, DebugInfoKind);
691 if (DwarfVersion > 0)
692 CmdArgs.push_back(
693 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
694 switch (DebuggerTuning) {
695 case llvm::DebuggerKind::GDB:
696 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
697 break;
698 case llvm::DebuggerKind::LLDB:
699 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
700 break;
701 case llvm::DebuggerKind::SCE:
702 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
703 break;
704 case llvm::DebuggerKind::DBX:
705 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
706 break;
707 default:
708 break;
709 }
710}
711
712static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
713 const Driver &D, const ToolChain &TC) {
714 assert(A && "Expected non-nullptr argument.");
715 if (TC.supportsDebugInfoOption(A))
716 return true;
717 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
718 << A->getAsString(Args) << TC.getTripleString();
719 return false;
720}
721
722static void RenderDebugInfoCompressionArgs(const ArgList &Args,
723 ArgStringList &CmdArgs,
724 const Driver &D,
725 const ToolChain &TC) {
726 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
727 if (!A)
728 return;
729 if (checkDebugInfoOption(A, Args, D, TC)) {
730 StringRef Value = A->getValue();
731 if (Value == "none") {
732 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
733 } else if (Value == "zlib") {
734 if (llvm::compression::zlib::isAvailable()) {
735 CmdArgs.push_back(
736 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
737 } else {
738 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
739 }
740 } else if (Value == "zstd") {
741 if (llvm::compression::zstd::isAvailable()) {
742 CmdArgs.push_back(
743 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
744 } else {
745 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
746 }
747 } else {
748 D.Diag(diag::err_drv_unsupported_option_argument)
749 << A->getSpelling() << Value;
750 }
751 }
752}
753
754static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
755 const ArgList &Args,
756 ArgStringList &CmdArgs,
757 bool IsCC1As = false) {
758 // If no version was requested by the user, use the default value from the
759 // back end. This is consistent with the value returned from
760 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
761 // requiring the corresponding llvm to have the AMDGPU target enabled,
762 // provided the user (e.g. front end tests) can use the default.
763 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
764 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
765 CmdArgs.insert(I: CmdArgs.begin() + 1,
766 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
767 Twine(CodeObjVer)));
768 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
769 // -cc1as does not accept -mcode-object-version option.
770 if (!IsCC1As)
771 CmdArgs.insert(I: CmdArgs.begin() + 1,
772 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
773 Twine(CodeObjVer)));
774 }
775}
776
777static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
778 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
779 D.getVFS().getBufferForFile(Name: Path);
780 if (!MemBuf)
781 return false;
782 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
783 if (Magic == llvm::file_magic::unknown)
784 return false;
785 // Return true for both raw Clang AST files and object files which may
786 // contain a __clangast section.
787 if (Magic == llvm::file_magic::clang_ast)
788 return true;
789 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
790 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
791 return !Obj.takeError();
792}
793
794static bool gchProbe(const Driver &D, StringRef Path) {
795 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
796 if (!Status)
797 return false;
798
799 if (Status->isDirectory()) {
800 std::error_code EC;
801 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
802 !EC && DI != DE; DI = DI.increment(EC)) {
803 if (maybeHasClangPchSignature(D, Path: DI->path()))
804 return true;
805 }
806 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
807 return false;
808 }
809
810 if (maybeHasClangPchSignature(D, Path))
811 return true;
812 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
813 return false;
814}
815
816void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
817 const Driver &D, const ArgList &Args,
818 ArgStringList &CmdArgs,
819 const InputInfo &Output,
820 const InputInfoList &Inputs) const {
821 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
822
823 CheckPreprocessingOptions(D, Args);
824
825 Args.AddLastArg(CmdArgs, options::OPT_C);
826 Args.AddLastArg(CmdArgs, options::OPT_CC);
827
828 // Handle dependency file generation.
829 Arg *ArgM = Args.getLastArg(options::OPT_MM);
830 if (!ArgM)
831 ArgM = Args.getLastArg(options::OPT_M);
832 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
833 if (!ArgMD)
834 ArgMD = Args.getLastArg(options::OPT_MD);
835
836 // -M and -MM imply -w.
837 if (ArgM)
838 CmdArgs.push_back(Elt: "-w");
839 else
840 ArgM = ArgMD;
841
842 if (ArgM) {
843 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
844 // Determine the output location.
845 const char *DepFile;
846 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
847 DepFile = MF->getValue();
848 C.addFailureResultFile(Name: DepFile, JA: &JA);
849 } else if (Output.getType() == types::TY_Dependencies) {
850 DepFile = Output.getFilename();
851 } else if (!ArgMD) {
852 DepFile = "-";
853 } else {
854 DepFile = getDependencyFileName(Args, Inputs);
855 C.addFailureResultFile(Name: DepFile, JA: &JA);
856 }
857 CmdArgs.push_back(Elt: "-dependency-file");
858 CmdArgs.push_back(Elt: DepFile);
859 }
860 // Cmake generates dependency files using all compilation options specified
861 // by users. Claim those not used for dependency files.
862 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
863 Args.ClaimAllArgs(options::OPT_offload_compress);
864 Args.ClaimAllArgs(options::OPT_no_offload_compress);
865 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
866 }
867
868 bool HasTarget = false;
869 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
870 HasTarget = true;
871 A->claim();
872 if (A->getOption().matches(options::OPT_MT)) {
873 A->render(Args, CmdArgs);
874 } else {
875 CmdArgs.push_back("-MT");
876 SmallString<128> Quoted;
877 quoteMakeTarget(A->getValue(), Quoted);
878 CmdArgs.push_back(Args.MakeArgString(Quoted));
879 }
880 }
881
882 // Add a default target if one wasn't specified.
883 if (!HasTarget) {
884 const char *DepTarget;
885
886 // If user provided -o, that is the dependency target, except
887 // when we are only generating a dependency file.
888 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
889 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
890 DepTarget = OutputOpt->getValue();
891 } else {
892 // Otherwise derive from the base input.
893 //
894 // FIXME: This should use the computed output file location.
895 SmallString<128> P(Inputs[0].getBaseInput());
896 llvm::sys::path::replace_extension(path&: P, extension: "o");
897 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
898 }
899
900 CmdArgs.push_back(Elt: "-MT");
901 SmallString<128> Quoted;
902 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
903 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
904 }
905
906 if (ArgM->getOption().matches(options::OPT_M) ||
907 ArgM->getOption().matches(options::OPT_MD))
908 CmdArgs.push_back(Elt: "-sys-header-deps");
909 if ((isa<PrecompileJobAction>(JA) &&
910 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
911 Args.hasArg(options::OPT_fmodule_file_deps))
912 CmdArgs.push_back(Elt: "-module-file-deps");
913 }
914
915 if (Args.hasArg(options::OPT_MG)) {
916 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
917 ArgM->getOption().matches(options::OPT_MMD))
918 D.Diag(diag::err_drv_mg_requires_m_or_mm);
919 CmdArgs.push_back(Elt: "-MG");
920 }
921
922 Args.AddLastArg(CmdArgs, options::OPT_MP);
923 Args.AddLastArg(CmdArgs, options::OPT_MV);
924
925 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
926 // before we -I or -include anything else, because we must pick up the
927 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
928 // rather than from e.g. /usr/local/include.
929 if (JA.isOffloading(OKind: Action::OFK_Cuda))
930 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
931 if (JA.isOffloading(OKind: Action::OFK_HIP))
932 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
933 if (JA.isOffloading(OKind: Action::OFK_SYCL))
934 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
935
936 // If we are offloading to a target via OpenMP we need to include the
937 // openmp_wrappers folder which contains alternative system headers.
938 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
939 !Args.hasArg(options::OPT_nostdinc) &&
940 !Args.hasArg(options::OPT_nogpuinc) &&
941 getToolChain().getTriple().isGPU()) {
942 if (!Args.hasArg(options::OPT_nobuiltininc)) {
943 // Add openmp_wrappers/* to our system include path. This lets us wrap
944 // standard library headers.
945 SmallString<128> P(D.ResourceDir);
946 llvm::sys::path::append(path&: P, a: "include");
947 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
948 CmdArgs.push_back(Elt: "-internal-isystem");
949 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
950 }
951
952 CmdArgs.push_back(Elt: "-include");
953 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
954 }
955
956 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
957 // Add llvm_wrappers/* to our system include path. This lets us wrap
958 // standard library headers and other headers.
959 SmallString<128> P(D.ResourceDir);
960 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
961 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
962 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
963 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
964 else
965 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
966 }
967
968 // Add -i* options, and automatically translate to
969 // -include-pch/-include-pth for transparent PCH support. It's
970 // wonky, but we include looking for .gch so we can support seamless
971 // replacement into a build system already set up to be generating
972 // .gch files.
973
974 if (getToolChain().getDriver().IsCLMode()) {
975 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
976 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
977 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
978 JA.getKind() <= Action::AssembleJobClass) {
979 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
980 // -fpch-instantiate-templates is the default when creating
981 // precomp using /Yc
982 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
983 options::OPT_fno_pch_instantiate_templates, true))
984 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
985 }
986 if (YcArg || YuArg) {
987 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
988 if (!isa<PrecompileJobAction>(Val: JA)) {
989 CmdArgs.push_back(Elt: "-include-pch");
990 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
991 C, BaseName: !ThroughHeader.empty()
992 ? ThroughHeader
993 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
994 }
995
996 if (ThroughHeader.empty()) {
997 CmdArgs.push_back(Elt: Args.MakeArgString(
998 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
999 } else {
1000 CmdArgs.push_back(
1001 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1002 }
1003 }
1004 }
1005
1006 bool RenderedImplicitInclude = false;
1007 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1008 if (A->getOption().matches(options::OPT_include) &&
1009 D.getProbePrecompiled()) {
1010 // Handling of gcc-style gch precompiled headers.
1011 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1012 RenderedImplicitInclude = true;
1013
1014 bool FoundPCH = false;
1015 SmallString<128> P(A->getValue());
1016 // We want the files to have a name like foo.h.pch. Add a dummy extension
1017 // so that replace_extension does the right thing.
1018 P += ".dummy";
1019 llvm::sys::path::replace_extension(P, "pch");
1020 if (D.getVFS().exists(P))
1021 FoundPCH = true;
1022
1023 if (!FoundPCH) {
1024 // For GCC compat, probe for a file or directory ending in .gch instead.
1025 llvm::sys::path::replace_extension(P, "gch");
1026 FoundPCH = gchProbe(D, P.str());
1027 }
1028
1029 if (FoundPCH) {
1030 if (IsFirstImplicitInclude) {
1031 A->claim();
1032 CmdArgs.push_back("-include-pch");
1033 CmdArgs.push_back(Args.MakeArgString(P));
1034 continue;
1035 } else {
1036 // Ignore the PCH if not first on command line and emit warning.
1037 D.Diag(diag::warn_drv_pch_not_first_include) << P
1038 << A->getAsString(Args);
1039 }
1040 }
1041 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1042 // Handling of paths which must come late. These entries are handled by
1043 // the toolchain itself after the resource dir is inserted in the right
1044 // search order.
1045 // Do not claim the argument so that the use of the argument does not
1046 // silently go unnoticed on toolchains which do not honour the option.
1047 continue;
1048 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1049 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1050 continue;
1051 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1052 // This is used only by the driver. No need to pass to cc1.
1053 continue;
1054 }
1055
1056 // Not translated, render as usual.
1057 A->claim();
1058 A->render(Args, CmdArgs);
1059 }
1060
1061 Args.addAllArgs(CmdArgs,
1062 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1063 options::OPT_F, options::OPT_embed_dir_EQ});
1064
1065 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1066
1067 // FIXME: There is a very unfortunate problem here, some troubled
1068 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1069 // really support that we would have to parse and then translate
1070 // those options. :(
1071 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1072 options::OPT_Xpreprocessor);
1073
1074 // -I- is a deprecated GCC feature, reject it.
1075 if (Arg *A = Args.getLastArg(options::OPT_I_))
1076 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1077
1078 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1079 // -isysroot to the CC1 invocation.
1080 StringRef sysroot = C.getSysRoot();
1081 if (sysroot != "") {
1082 if (!Args.hasArg(options::OPT_isysroot)) {
1083 CmdArgs.push_back(Elt: "-isysroot");
1084 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1085 }
1086 }
1087
1088 // Parse additional include paths from environment variables.
1089 // FIXME: We should probably sink the logic for handling these from the
1090 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1091 // CPATH - included following the user specified includes (but prior to
1092 // builtin and standard includes).
1093 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1094 // C_INCLUDE_PATH - system includes enabled when compiling C.
1095 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1096 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1097 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1098 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1099 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1100 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1101 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1102
1103 // While adding the include arguments, we also attempt to retrieve the
1104 // arguments of related offloading toolchains or arguments that are specific
1105 // of an offloading programming model.
1106
1107 // Add C++ include arguments, if needed.
1108 if (types::isCXX(Id: Inputs[0].getType())) {
1109 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1110 forAllAssociatedToolChains(
1111 C, JA, RegularToolChain: getToolChain(),
1112 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1113 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1114 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1115 });
1116 }
1117
1118 // If we are compiling for a GPU target we want to override the system headers
1119 // with ones created by the 'libc' project if present.
1120 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1121 // OffloadKind as an argument.
1122 if (!Args.hasArg(options::OPT_nostdinc) &&
1123 !Args.hasArg(options::OPT_nogpuinc) &&
1124 !Args.hasArg(options::OPT_nobuiltininc)) {
1125 // Without an offloading language we will include these headers directly.
1126 // Offloading languages will instead only use the declarations stored in
1127 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1128 if (getToolChain().getTriple().isGPU() &&
1129 C.getActiveOffloadKinds() == Action::OFK_None) {
1130 SmallString<128> P(llvm::sys::path::parent_path(path: D.Dir));
1131 llvm::sys::path::append(path&: P, a: "include");
1132 llvm::sys::path::append(path&: P, a: getToolChain().getTripleString());
1133 CmdArgs.push_back(Elt: "-internal-isystem");
1134 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1135 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1136 // TODO: CUDA / HIP include their own headers for some common functions
1137 // implemented here. We'll need to clean those up so they do not conflict.
1138 SmallString<128> P(D.ResourceDir);
1139 llvm::sys::path::append(path&: P, a: "include");
1140 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1141 CmdArgs.push_back(Elt: "-internal-isystem");
1142 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1143 }
1144 }
1145
1146 // Add system include arguments for all targets but IAMCU.
1147 if (!IsIAMCU)
1148 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1149 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1150 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1151 });
1152 else {
1153 // For IAMCU add special include arguments.
1154 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1155 }
1156
1157 addMacroPrefixMapArg(D, Args, CmdArgs);
1158 addCoveragePrefixMapArg(D, Args, CmdArgs);
1159
1160 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1161 options::OPT_fno_file_reproducible);
1162
1163 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1164 CmdArgs.push_back(Elt: "-source-date-epoch");
1165 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1166 }
1167
1168 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1169 options::OPT_fno_define_target_os_macros);
1170}
1171
1172// FIXME: Move to target hook.
1173static bool isSignedCharDefault(const llvm::Triple &Triple) {
1174 switch (Triple.getArch()) {
1175 default:
1176 return true;
1177
1178 case llvm::Triple::aarch64:
1179 case llvm::Triple::aarch64_32:
1180 case llvm::Triple::aarch64_be:
1181 case llvm::Triple::arm:
1182 case llvm::Triple::armeb:
1183 case llvm::Triple::thumb:
1184 case llvm::Triple::thumbeb:
1185 if (Triple.isOSDarwin() || Triple.isOSWindows())
1186 return true;
1187 return false;
1188
1189 case llvm::Triple::ppc:
1190 case llvm::Triple::ppc64:
1191 if (Triple.isOSDarwin())
1192 return true;
1193 return false;
1194
1195 case llvm::Triple::csky:
1196 case llvm::Triple::hexagon:
1197 case llvm::Triple::msp430:
1198 case llvm::Triple::ppcle:
1199 case llvm::Triple::ppc64le:
1200 case llvm::Triple::riscv32:
1201 case llvm::Triple::riscv64:
1202 case llvm::Triple::systemz:
1203 case llvm::Triple::xcore:
1204 case llvm::Triple::xtensa:
1205 return false;
1206 }
1207}
1208
1209static bool hasMultipleInvocations(const llvm::Triple &Triple,
1210 const ArgList &Args) {
1211 // Supported only on Darwin where we invoke the compiler multiple times
1212 // followed by an invocation to lipo.
1213 if (!Triple.isOSDarwin())
1214 return false;
1215 // If more than one "-arch <arch>" is specified, we're targeting multiple
1216 // architectures resulting in a fat binary.
1217 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1218}
1219
1220static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1221 const llvm::Triple &Triple) {
1222 // When enabling remarks, we need to error if:
1223 // * The remark file is specified but we're targeting multiple architectures,
1224 // which means more than one remark file is being generated.
1225 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1226 bool hasExplicitOutputFile =
1227 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1228 if (hasMultipleInvocations && hasExplicitOutputFile) {
1229 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1230 << "-foptimization-record-file";
1231 return false;
1232 }
1233 return true;
1234}
1235
1236static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1237 const llvm::Triple &Triple,
1238 const InputInfo &Input,
1239 const InputInfo &Output, const JobAction &JA) {
1240 StringRef Format = "yaml";
1241 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1242 Format = A->getValue();
1243
1244 CmdArgs.push_back(Elt: "-opt-record-file");
1245
1246 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1247 if (A) {
1248 CmdArgs.push_back(Elt: A->getValue());
1249 } else {
1250 bool hasMultipleArchs =
1251 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1252 Args.getAllArgValues(options::OPT_arch).size() > 1;
1253
1254 SmallString<128> F;
1255
1256 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1257 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1258 F = FinalOutput->getValue();
1259 } else {
1260 if (Format != "yaml" && // For YAML, keep the original behavior.
1261 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1262 Output.isFilename())
1263 F = Output.getFilename();
1264 }
1265
1266 if (F.empty()) {
1267 // Use the input filename.
1268 F = llvm::sys::path::stem(path: Input.getBaseInput());
1269
1270 // If we're compiling for an offload architecture (i.e. a CUDA device),
1271 // we need to make the file name for the device compilation different
1272 // from the host compilation.
1273 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1274 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1275 llvm::sys::path::replace_extension(path&: F, extension: "");
1276 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1277 NormalizedTriple: Triple.normalize());
1278 F += "-";
1279 F += JA.getOffloadingArch();
1280 }
1281 }
1282
1283 // If we're having more than one "-arch", we should name the files
1284 // differently so that every cc1 invocation writes to a different file.
1285 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1286 // name from the triple.
1287 if (hasMultipleArchs) {
1288 // First, remember the extension.
1289 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1290 // then, remove it.
1291 llvm::sys::path::replace_extension(path&: F, extension: "");
1292 // attach -<arch> to it.
1293 F += "-";
1294 F += Triple.getArchName();
1295 // put back the extension.
1296 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1297 }
1298
1299 SmallString<32> Extension;
1300 Extension += "opt.";
1301 Extension += Format;
1302
1303 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1304 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1305 }
1306
1307 if (const Arg *A =
1308 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1309 CmdArgs.push_back(Elt: "-opt-record-passes");
1310 CmdArgs.push_back(Elt: A->getValue());
1311 }
1312
1313 if (!Format.empty()) {
1314 CmdArgs.push_back(Elt: "-opt-record-format");
1315 CmdArgs.push_back(Elt: Format.data());
1316 }
1317}
1318
1319void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1320 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1321 options::OPT_fno_aapcs_bitfield_width, true))
1322 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1323
1324 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1325 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1326}
1327
1328namespace {
1329void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1330 const ArgList &Args, ArgStringList &CmdArgs) {
1331 // Select the ABI to use.
1332 // FIXME: Support -meabi.
1333 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1334 const char *ABIName = nullptr;
1335 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1336 ABIName = A->getValue();
1337 } else {
1338 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
1339 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple, CPU).data();
1340 }
1341
1342 CmdArgs.push_back(Elt: "-target-abi");
1343 CmdArgs.push_back(Elt: ABIName);
1344}
1345
1346void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1347 auto StrictAlignIter =
1348 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1349 return Arg == "+strict-align" || Arg == "-strict-align";
1350 });
1351 if (StrictAlignIter != CmdArgs.rend() &&
1352 StringRef(*StrictAlignIter) == "+strict-align")
1353 CmdArgs.push_back(Elt: "-Wunaligned-access");
1354}
1355}
1356
1357// Each combination of options here forms a signing schema, and in most cases
1358// each signing schema is its own incompatible ABI. The default values of the
1359// options represent the default signing schema.
1360static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args) {
1361 if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
1362 options::OPT_fno_ptrauth_intrinsics))
1363 CC1Args.push_back(Elt: "-fptrauth-intrinsics");
1364
1365 if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
1366 options::OPT_fno_ptrauth_calls))
1367 CC1Args.push_back(Elt: "-fptrauth-calls");
1368
1369 if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
1370 options::OPT_fno_ptrauth_returns))
1371 CC1Args.push_back(Elt: "-fptrauth-returns");
1372
1373 if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
1374 options::OPT_fno_ptrauth_auth_traps))
1375 CC1Args.push_back(Elt: "-fptrauth-auth-traps");
1376
1377 if (!DriverArgs.hasArg(
1378 options::OPT_fptrauth_vtable_pointer_address_discrimination,
1379 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
1380 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-address-discrimination");
1381
1382 if (!DriverArgs.hasArg(
1383 options::OPT_fptrauth_vtable_pointer_type_discrimination,
1384 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
1385 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-type-discrimination");
1386
1387 if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
1388 options::OPT_fno_ptrauth_indirect_gotos))
1389 CC1Args.push_back(Elt: "-fptrauth-indirect-gotos");
1390
1391 if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
1392 options::OPT_fno_ptrauth_init_fini))
1393 CC1Args.push_back(Elt: "-fptrauth-init-fini");
1394}
1395
1396static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1397 ArgStringList &CmdArgs, bool isAArch64) {
1398 const llvm::Triple &Triple = TC.getEffectiveTriple();
1399 const Arg *A = isAArch64
1400 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1401 options::OPT_mbranch_protection_EQ)
1402 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1403 if (!A) {
1404 if (Triple.isOSOpenBSD() && isAArch64) {
1405 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1406 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1407 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1408 }
1409 return;
1410 }
1411
1412 const Driver &D = TC.getDriver();
1413 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1414 D.Diag(diag::warn_incompatible_branch_protection_option)
1415 << Triple.getArchName();
1416
1417 StringRef Scope, Key;
1418 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1419
1420 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1421 Scope = A->getValue();
1422 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1423 D.Diag(diag::err_drv_unsupported_option_argument)
1424 << A->getSpelling() << Scope;
1425 Key = "a_key";
1426 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1427 BranchProtectionPAuthLR = false;
1428 GuardedControlStack = false;
1429 } else {
1430 StringRef DiagMsg;
1431 llvm::ARM::ParsedBranchProtection PBP;
1432 bool EnablePAuthLR = false;
1433
1434 // To know if we need to enable PAuth-LR As part of the standard branch
1435 // protection option, it needs to be determined if the feature has been
1436 // activated in the `march` argument. This information is stored within the
1437 // CmdArgs variable and can be found using a search.
1438 if (isAArch64) {
1439 auto isPAuthLR = [](const char *member) {
1440 llvm::AArch64::ExtensionInfo pauthlr_extension =
1441 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1442 return pauthlr_extension.PosTargetFeature == member;
1443 };
1444
1445 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1446 EnablePAuthLR = true;
1447 }
1448 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1449 EnablePAuthLR))
1450 D.Diag(diag::err_drv_unsupported_option_argument)
1451 << A->getSpelling() << DiagMsg;
1452 if (!isAArch64 && PBP.Key == "b_key")
1453 D.Diag(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 bool HasPtrauthReturns = llvm::any_of(Range&: CmdArgs, P: [](const char *Arg) {
1463 return StringRef(Arg) == "-fptrauth-returns";
1464 });
1465 // GCS is currently untested with ptrauth-returns, but enabling this could be
1466 // allowed in future after testing with a suitable system.
1467 if (HasPtrauthReturns &&
1468 (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack)) {
1469 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1470 D.Diag(diag::err_drv_unsupported_opt_for_target)
1471 << A->getAsString(Args) << Triple.getTriple();
1472 else
1473 D.Diag(diag::err_drv_incompatible_options)
1474 << A->getAsString(Args) << "-fptrauth-returns";
1475 }
1476
1477 CmdArgs.push_back(
1478 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1479 if (Scope != "none")
1480 CmdArgs.push_back(
1481 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1482 if (BranchProtectionPAuthLR)
1483 CmdArgs.push_back(
1484 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1485 if (IndirectBranches)
1486 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1487
1488 if (GuardedControlStack)
1489 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1490}
1491
1492void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1493 ArgStringList &CmdArgs, bool KernelOrKext) const {
1494 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1495
1496 // Determine floating point ABI from the options & target defaults.
1497 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1498 if (ABI == arm::FloatABI::Soft) {
1499 // Floating point operations and argument passing are soft.
1500 // FIXME: This changes CPP defines, we need -target-soft-float.
1501 CmdArgs.push_back(Elt: "-msoft-float");
1502 CmdArgs.push_back(Elt: "-mfloat-abi");
1503 CmdArgs.push_back(Elt: "soft");
1504 } else if (ABI == arm::FloatABI::SoftFP) {
1505 // Floating point operations are hard, but argument passing is soft.
1506 CmdArgs.push_back(Elt: "-mfloat-abi");
1507 CmdArgs.push_back(Elt: "soft");
1508 } else {
1509 // Floating point operations and argument passing are hard.
1510 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1511 CmdArgs.push_back(Elt: "-mfloat-abi");
1512 CmdArgs.push_back(Elt: "hard");
1513 }
1514
1515 // Forward the -mglobal-merge option for explicit control over the pass.
1516 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1517 options::OPT_mno_global_merge)) {
1518 CmdArgs.push_back(Elt: "-mllvm");
1519 if (A->getOption().matches(options::OPT_mno_global_merge))
1520 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1521 else
1522 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1523 }
1524
1525 if (!Args.hasFlag(options::OPT_mimplicit_float,
1526 options::OPT_mno_implicit_float, true))
1527 CmdArgs.push_back(Elt: "-no-implicit-float");
1528
1529 if (Args.getLastArg(options::OPT_mcmse))
1530 CmdArgs.push_back(Elt: "-mcmse");
1531
1532 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1533
1534 // Enable/disable return address signing and indirect branch targets.
1535 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1536
1537 AddUnalignedAccessWarning(CmdArgs);
1538}
1539
1540void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1541 const ArgList &Args, bool KernelOrKext,
1542 ArgStringList &CmdArgs) const {
1543 const ToolChain &TC = getToolChain();
1544
1545 // Add the target features
1546 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1547
1548 // Add target specific flags.
1549 switch (TC.getArch()) {
1550 default:
1551 break;
1552
1553 case llvm::Triple::arm:
1554 case llvm::Triple::armeb:
1555 case llvm::Triple::thumb:
1556 case llvm::Triple::thumbeb:
1557 // Use the effective triple, which takes into account the deployment target.
1558 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1559 break;
1560
1561 case llvm::Triple::aarch64:
1562 case llvm::Triple::aarch64_32:
1563 case llvm::Triple::aarch64_be:
1564 AddAArch64TargetArgs(Args, CmdArgs);
1565 break;
1566
1567 case llvm::Triple::loongarch32:
1568 case llvm::Triple::loongarch64:
1569 AddLoongArchTargetArgs(Args, CmdArgs);
1570 break;
1571
1572 case llvm::Triple::mips:
1573 case llvm::Triple::mipsel:
1574 case llvm::Triple::mips64:
1575 case llvm::Triple::mips64el:
1576 AddMIPSTargetArgs(Args, CmdArgs);
1577 break;
1578
1579 case llvm::Triple::ppc:
1580 case llvm::Triple::ppcle:
1581 case llvm::Triple::ppc64:
1582 case llvm::Triple::ppc64le:
1583 AddPPCTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::riscv32:
1587 case llvm::Triple::riscv64:
1588 AddRISCVTargetArgs(Args, CmdArgs);
1589 break;
1590
1591 case llvm::Triple::sparc:
1592 case llvm::Triple::sparcel:
1593 case llvm::Triple::sparcv9:
1594 AddSparcTargetArgs(Args, CmdArgs);
1595 break;
1596
1597 case llvm::Triple::systemz:
1598 AddSystemZTargetArgs(Args, CmdArgs);
1599 break;
1600
1601 case llvm::Triple::x86:
1602 case llvm::Triple::x86_64:
1603 AddX86TargetArgs(Args, CmdArgs);
1604 break;
1605
1606 case llvm::Triple::lanai:
1607 AddLanaiTargetArgs(Args, CmdArgs);
1608 break;
1609
1610 case llvm::Triple::hexagon:
1611 AddHexagonTargetArgs(Args, CmdArgs);
1612 break;
1613
1614 case llvm::Triple::wasm32:
1615 case llvm::Triple::wasm64:
1616 AddWebAssemblyTargetArgs(Args, CmdArgs);
1617 break;
1618
1619 case llvm::Triple::ve:
1620 AddVETargetArgs(Args, CmdArgs);
1621 break;
1622 }
1623}
1624
1625namespace {
1626void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1627 ArgStringList &CmdArgs) {
1628 const char *ABIName = nullptr;
1629 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1630 ABIName = A->getValue();
1631 else if (Triple.isOSDarwin())
1632 ABIName = "darwinpcs";
1633 else if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1634 ABIName = "pauthtest";
1635 else
1636 ABIName = "aapcs";
1637
1638 CmdArgs.push_back(Elt: "-target-abi");
1639 CmdArgs.push_back(Elt: ABIName);
1640}
1641}
1642
1643void Clang::AddAArch64TargetArgs(const ArgList &Args,
1644 ArgStringList &CmdArgs) const {
1645 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1646
1647 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1648 Args.hasArg(options::OPT_mkernel) ||
1649 Args.hasArg(options::OPT_fapple_kext))
1650 CmdArgs.push_back(Elt: "-disable-red-zone");
1651
1652 if (!Args.hasFlag(options::OPT_mimplicit_float,
1653 options::OPT_mno_implicit_float, true))
1654 CmdArgs.push_back(Elt: "-no-implicit-float");
1655
1656 RenderAArch64ABI(Triple, Args, CmdArgs);
1657
1658 // Forward the -mglobal-merge option for explicit control over the pass.
1659 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1660 options::OPT_mno_global_merge)) {
1661 CmdArgs.push_back(Elt: "-mllvm");
1662 if (A->getOption().matches(options::OPT_mno_global_merge))
1663 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1664 else
1665 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1666 }
1667
1668 // Handle -msve_vector_bits=<bits>
1669 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1670 StringRef Val = A->getValue();
1671 const Driver &D = getToolChain().getDriver();
1672 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1673 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1674 Val == "1024+" || Val == "2048+") {
1675 unsigned Bits = 0;
1676 if (!Val.consume_back(Suffix: "+")) {
1677 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits); (void)Invalid;
1678 assert(!Invalid && "Failed to parse value");
1679 CmdArgs.push_back(
1680 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(Bits / 128)));
1681 }
1682
1683 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits); (void)Invalid;
1684 assert(!Invalid && "Failed to parse value");
1685 CmdArgs.push_back(
1686 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(Bits / 128)));
1687 // Silently drop requests for vector-length agnostic code as it's implied.
1688 } else if (Val != "scalable")
1689 // Handle the unsupported values passed to msve-vector-bits.
1690 D.Diag(diag::err_drv_unsupported_option_argument)
1691 << A->getSpelling() << Val;
1692 }
1693
1694 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1695
1696 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1697 CmdArgs.push_back(Elt: "-tune-cpu");
1698 if (strcmp(s1: A->getValue(), s2: "native") == 0)
1699 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
1700 else
1701 CmdArgs.push_back(Elt: A->getValue());
1702 }
1703
1704 AddUnalignedAccessWarning(CmdArgs);
1705
1706 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1707 options::OPT_fno_ptrauth_intrinsics);
1708 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1709 options::OPT_fno_ptrauth_calls);
1710 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1711 options::OPT_fno_ptrauth_returns);
1712 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1713 options::OPT_fno_ptrauth_auth_traps);
1714 Args.addOptInFlag(
1715 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1716 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1717 Args.addOptInFlag(
1718 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1719 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1720 Args.addOptInFlag(
1721 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1722 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1723 Args.addOptInFlag(
1724 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1725 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1726
1727 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1728 options::OPT_fno_ptrauth_indirect_gotos);
1729 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1730 options::OPT_fno_ptrauth_init_fini);
1731 Args.addOptInFlag(CmdArgs,
1732 options::OPT_fptrauth_init_fini_address_discrimination,
1733 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1734 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1735 options::OPT_fno_aarch64_jump_table_hardening);
1736
1737 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1738 handlePAuthABI(DriverArgs: Args, CC1Args&: CmdArgs);
1739
1740 // Enable/disable return address signing and indirect branch targets.
1741 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1742}
1743
1744void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1745 ArgStringList &CmdArgs) const {
1746 const llvm::Triple &Triple = getToolChain().getTriple();
1747
1748 CmdArgs.push_back(Elt: "-target-abi");
1749 CmdArgs.push_back(
1750 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1751 .data());
1752
1753 // Handle -mtune.
1754 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1755 std::string TuneCPU = A->getValue();
1756 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1757 CmdArgs.push_back(Elt: "-tune-cpu");
1758 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1759 }
1760
1761 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1762 options::OPT_mno_annotate_tablejump)) {
1763 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1764 CmdArgs.push_back(Elt: "-mllvm");
1765 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1766 }
1767 }
1768}
1769
1770void Clang::AddMIPSTargetArgs(const ArgList &Args,
1771 ArgStringList &CmdArgs) const {
1772 const Driver &D = getToolChain().getDriver();
1773 StringRef CPUName;
1774 StringRef ABIName;
1775 const llvm::Triple &Triple = getToolChain().getTriple();
1776 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1777
1778 CmdArgs.push_back(Elt: "-target-abi");
1779 CmdArgs.push_back(Elt: ABIName.data());
1780
1781 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1782 if (ABI == mips::FloatABI::Soft) {
1783 // Floating point operations and argument passing are soft.
1784 CmdArgs.push_back(Elt: "-msoft-float");
1785 CmdArgs.push_back(Elt: "-mfloat-abi");
1786 CmdArgs.push_back(Elt: "soft");
1787 } else {
1788 // Floating point operations and argument passing are hard.
1789 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1790 CmdArgs.push_back(Elt: "-mfloat-abi");
1791 CmdArgs.push_back(Elt: "hard");
1792 }
1793
1794 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1795 options::OPT_mno_ldc1_sdc1)) {
1796 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1797 CmdArgs.push_back(Elt: "-mllvm");
1798 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1799 }
1800 }
1801
1802 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1803 options::OPT_mno_check_zero_division)) {
1804 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1805 CmdArgs.push_back(Elt: "-mllvm");
1806 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1807 }
1808 }
1809
1810 if (Args.getLastArg(options::OPT_mfix4300)) {
1811 CmdArgs.push_back(Elt: "-mllvm");
1812 CmdArgs.push_back(Elt: "-mfix4300");
1813 }
1814
1815 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1816 StringRef v = A->getValue();
1817 CmdArgs.push_back(Elt: "-mllvm");
1818 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1819 A->claim();
1820 }
1821
1822 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1823 Arg *ABICalls =
1824 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1825
1826 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1827 // -mgpopt is the default for static, -fno-pic environments but these two
1828 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1829 // the only case where -mllvm -mgpopt is passed.
1830 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1831 // passed explicitly when compiling something with -mabicalls
1832 // (implictly) in affect. Currently the warning is in the backend.
1833 //
1834 // When the ABI in use is N64, we also need to determine the PIC mode that
1835 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1836 bool NoABICalls =
1837 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1838
1839 llvm::Reloc::Model RelocationModel;
1840 unsigned PICLevel;
1841 bool IsPIE;
1842 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1843 ParsePICArgs(ToolChain: getToolChain(), Args);
1844
1845 NoABICalls = NoABICalls ||
1846 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1847
1848 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1849 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1850 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1851 CmdArgs.push_back(Elt: "-mllvm");
1852 CmdArgs.push_back(Elt: "-mgpopt");
1853
1854 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1855 options::OPT_mno_local_sdata);
1856 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1857 options::OPT_mno_extern_sdata);
1858 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1859 options::OPT_mno_embedded_data);
1860 if (LocalSData) {
1861 CmdArgs.push_back(Elt: "-mllvm");
1862 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1863 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1864 } else {
1865 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1866 }
1867 LocalSData->claim();
1868 }
1869
1870 if (ExternSData) {
1871 CmdArgs.push_back(Elt: "-mllvm");
1872 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1873 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1874 } else {
1875 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1876 }
1877 ExternSData->claim();
1878 }
1879
1880 if (EmbeddedData) {
1881 CmdArgs.push_back(Elt: "-mllvm");
1882 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1883 CmdArgs.push_back(Elt: "-membedded-data=1");
1884 } else {
1885 CmdArgs.push_back(Elt: "-membedded-data=0");
1886 }
1887 EmbeddedData->claim();
1888 }
1889
1890 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1891 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1892
1893 if (GPOpt)
1894 GPOpt->claim();
1895
1896 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1897 StringRef Val = StringRef(A->getValue());
1898 if (mips::hasCompactBranches(CPU&: CPUName)) {
1899 if (Val == "never" || Val == "always" || Val == "optimal") {
1900 CmdArgs.push_back(Elt: "-mllvm");
1901 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1902 } else
1903 D.Diag(diag::err_drv_unsupported_option_argument)
1904 << A->getSpelling() << Val;
1905 } else
1906 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1907 }
1908
1909 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1910 options::OPT_mno_relax_pic_calls)) {
1911 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1912 CmdArgs.push_back(Elt: "-mllvm");
1913 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1914 }
1915 }
1916}
1917
1918void Clang::AddPPCTargetArgs(const ArgList &Args,
1919 ArgStringList &CmdArgs) const {
1920 const Driver &D = getToolChain().getDriver();
1921 const llvm::Triple &T = getToolChain().getTriple();
1922 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1923 CmdArgs.push_back(Elt: "-tune-cpu");
1924 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1925 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU.str()));
1926 }
1927
1928 // Select the ABI to use.
1929 const char *ABIName = nullptr;
1930 if (T.isOSBinFormatELF()) {
1931 switch (getToolChain().getArch()) {
1932 case llvm::Triple::ppc64: {
1933 if (T.isPPC64ELFv2ABI())
1934 ABIName = "elfv2";
1935 else
1936 ABIName = "elfv1";
1937 break;
1938 }
1939 case llvm::Triple::ppc64le:
1940 ABIName = "elfv2";
1941 break;
1942 default:
1943 break;
1944 }
1945 }
1946
1947 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1948 bool VecExtabi = false;
1949 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1950 StringRef V = A->getValue();
1951 if (V == "ieeelongdouble") {
1952 IEEELongDouble = true;
1953 A->claim();
1954 } else if (V == "ibmlongdouble") {
1955 IEEELongDouble = false;
1956 A->claim();
1957 } else if (V == "vec-default") {
1958 VecExtabi = false;
1959 A->claim();
1960 } else if (V == "vec-extabi") {
1961 VecExtabi = true;
1962 A->claim();
1963 } else if (V == "elfv1") {
1964 ABIName = "elfv1";
1965 A->claim();
1966 } else if (V == "elfv2") {
1967 ABIName = "elfv2";
1968 A->claim();
1969 } else if (V != "altivec")
1970 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1971 // the option if given as we don't have backend support for any targets
1972 // that don't use the altivec abi.
1973 ABIName = A->getValue();
1974 }
1975 if (IEEELongDouble)
1976 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
1977 if (VecExtabi) {
1978 if (!T.isOSAIX())
1979 D.Diag(diag::err_drv_unsupported_opt_for_target)
1980 << "-mabi=vec-extabi" << T.str();
1981 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
1982 }
1983
1984 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
1985 CmdArgs.push_back(Elt: "-disable-red-zone");
1986
1987 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1988 if (FloatABI == ppc::FloatABI::Soft) {
1989 // Floating point operations and argument passing are soft.
1990 CmdArgs.push_back(Elt: "-msoft-float");
1991 CmdArgs.push_back(Elt: "-mfloat-abi");
1992 CmdArgs.push_back(Elt: "soft");
1993 } else {
1994 // Floating point operations and argument passing are hard.
1995 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1996 CmdArgs.push_back(Elt: "-mfloat-abi");
1997 CmdArgs.push_back(Elt: "hard");
1998 }
1999
2000 if (ABIName) {
2001 CmdArgs.push_back(Elt: "-target-abi");
2002 CmdArgs.push_back(Elt: ABIName);
2003 }
2004}
2005
2006void Clang::AddRISCVTargetArgs(const ArgList &Args,
2007 ArgStringList &CmdArgs) const {
2008 const llvm::Triple &Triple = getToolChain().getTriple();
2009 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2010
2011 CmdArgs.push_back(Elt: "-target-abi");
2012 CmdArgs.push_back(Elt: ABIName.data());
2013
2014 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2015 CmdArgs.push_back(Elt: "-msmall-data-limit");
2016 CmdArgs.push_back(Elt: A->getValue());
2017 }
2018
2019 if (!Args.hasFlag(options::OPT_mimplicit_float,
2020 options::OPT_mno_implicit_float, true))
2021 CmdArgs.push_back(Elt: "-no-implicit-float");
2022
2023 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2024 CmdArgs.push_back(Elt: "-tune-cpu");
2025 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2026 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2027 else
2028 CmdArgs.push_back(Elt: A->getValue());
2029 }
2030
2031 // Handle -mrvv-vector-bits=<bits>
2032 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2033 StringRef Val = A->getValue();
2034 const Driver &D = getToolChain().getDriver();
2035
2036 // Get minimum VLen from march.
2037 unsigned MinVLen = 0;
2038 std::string Arch = riscv::getRISCVArch(Args, Triple);
2039 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2040 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2041 // Ignore parsing error.
2042 if (!errorToBool(Err: ISAInfo.takeError()))
2043 MinVLen = (*ISAInfo)->getMinVLen();
2044
2045 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2046 // as integer as long as we have a MinVLen.
2047 unsigned Bits = 0;
2048 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2049 Bits = MinVLen;
2050 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2051 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2052 // at least MinVLen.
2053 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2054 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2055 Bits = 0;
2056 }
2057
2058 // If we got a valid value try to use it.
2059 if (Bits != 0) {
2060 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2061 CmdArgs.push_back(
2062 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2063 CmdArgs.push_back(
2064 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2065 } else if (Val != "scalable") {
2066 // Handle the unsupported values passed to mrvv-vector-bits.
2067 D.Diag(diag::err_drv_unsupported_option_argument)
2068 << A->getSpelling() << Val;
2069 }
2070 }
2071}
2072
2073void Clang::AddSparcTargetArgs(const ArgList &Args,
2074 ArgStringList &CmdArgs) const {
2075 sparc::FloatABI FloatABI =
2076 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2077
2078 if (FloatABI == sparc::FloatABI::Soft) {
2079 // Floating point operations and argument passing are soft.
2080 CmdArgs.push_back(Elt: "-msoft-float");
2081 CmdArgs.push_back(Elt: "-mfloat-abi");
2082 CmdArgs.push_back(Elt: "soft");
2083 } else {
2084 // Floating point operations and argument passing are hard.
2085 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2086 CmdArgs.push_back(Elt: "-mfloat-abi");
2087 CmdArgs.push_back(Elt: "hard");
2088 }
2089
2090 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2091 StringRef Name = A->getValue();
2092 std::string TuneCPU;
2093 if (Name == "native")
2094 TuneCPU = std::string(llvm::sys::getHostCPUName());
2095 else
2096 TuneCPU = std::string(Name);
2097
2098 CmdArgs.push_back(Elt: "-tune-cpu");
2099 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2100 }
2101}
2102
2103void Clang::AddSystemZTargetArgs(const ArgList &Args,
2104 ArgStringList &CmdArgs) const {
2105 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2106 CmdArgs.push_back(Elt: "-tune-cpu");
2107 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2108 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2109 else
2110 CmdArgs.push_back(Elt: A->getValue());
2111 }
2112
2113 bool HasBackchain =
2114 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2115 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2116 options::OPT_mno_packed_stack, false);
2117 systemz::FloatABI FloatABI =
2118 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2119 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2120 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2121 const Driver &D = getToolChain().getDriver();
2122 D.Diag(diag::err_drv_unsupported_opt)
2123 << "-mpacked-stack -mbackchain -mhard-float";
2124 }
2125 if (HasBackchain)
2126 CmdArgs.push_back(Elt: "-mbackchain");
2127 if (HasPackedStack)
2128 CmdArgs.push_back(Elt: "-mpacked-stack");
2129 if (HasSoftFloat) {
2130 // Floating point operations and argument passing are soft.
2131 CmdArgs.push_back(Elt: "-msoft-float");
2132 CmdArgs.push_back(Elt: "-mfloat-abi");
2133 CmdArgs.push_back(Elt: "soft");
2134 }
2135}
2136
2137void Clang::AddX86TargetArgs(const ArgList &Args,
2138 ArgStringList &CmdArgs) const {
2139 const Driver &D = getToolChain().getDriver();
2140 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2141
2142 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2143 Args.hasArg(options::OPT_mkernel) ||
2144 Args.hasArg(options::OPT_fapple_kext))
2145 CmdArgs.push_back(Elt: "-disable-red-zone");
2146
2147 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2148 options::OPT_mno_tls_direct_seg_refs, true))
2149 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2150
2151 // Default to avoid implicit floating-point for kernel/kext code, but allow
2152 // that to be overridden with -mno-soft-float.
2153 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2154 Args.hasArg(options::OPT_fapple_kext));
2155 if (Arg *A = Args.getLastArg(
2156 options::OPT_msoft_float, options::OPT_mno_soft_float,
2157 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2158 const Option &O = A->getOption();
2159 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2160 O.matches(options::OPT_msoft_float));
2161 }
2162 if (NoImplicitFloat)
2163 CmdArgs.push_back(Elt: "-no-implicit-float");
2164
2165 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2166 StringRef Value = A->getValue();
2167 if (Value == "intel" || Value == "att") {
2168 CmdArgs.push_back(Elt: "-mllvm");
2169 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2170 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2171 } else {
2172 D.Diag(diag::err_drv_unsupported_option_argument)
2173 << A->getSpelling() << Value;
2174 }
2175 } else if (D.IsCLMode()) {
2176 CmdArgs.push_back(Elt: "-mllvm");
2177 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2178 }
2179
2180 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2181 options::OPT_mno_skip_rax_setup))
2182 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2183 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2184
2185 // Set flags to support MCU ABI.
2186 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2187 CmdArgs.push_back(Elt: "-mfloat-abi");
2188 CmdArgs.push_back(Elt: "soft");
2189 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2190 }
2191
2192 // Handle -mtune.
2193
2194 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2195 std::string TuneCPU;
2196 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2197 !getToolChain().getTriple().isPS())
2198 TuneCPU = "generic";
2199
2200 // Override based on -mtune.
2201 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2202 StringRef Name = A->getValue();
2203
2204 if (Name == "native") {
2205 Name = llvm::sys::getHostCPUName();
2206 if (!Name.empty())
2207 TuneCPU = std::string(Name);
2208 } else
2209 TuneCPU = std::string(Name);
2210 }
2211
2212 if (!TuneCPU.empty()) {
2213 CmdArgs.push_back(Elt: "-tune-cpu");
2214 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2215 }
2216}
2217
2218void Clang::AddHexagonTargetArgs(const ArgList &Args,
2219 ArgStringList &CmdArgs) const {
2220 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2221 CmdArgs.push_back(Elt: "-Wreturn-type");
2222
2223 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2224 CmdArgs.push_back(Elt: "-mllvm");
2225 CmdArgs.push_back(
2226 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2227 }
2228
2229 if (!Args.hasArg(options::OPT_fno_short_enums))
2230 CmdArgs.push_back(Elt: "-fshort-enums");
2231 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2232 CmdArgs.push_back(Elt: "-mllvm");
2233 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2234 }
2235 CmdArgs.push_back(Elt: "-mllvm");
2236 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2237}
2238
2239void Clang::AddLanaiTargetArgs(const ArgList &Args,
2240 ArgStringList &CmdArgs) const {
2241 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2242 StringRef CPUName = A->getValue();
2243
2244 CmdArgs.push_back(Elt: "-target-cpu");
2245 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2246 }
2247 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2248 StringRef Value = A->getValue();
2249 // Only support mregparm=4 to support old usage. Report error for all other
2250 // cases.
2251 int Mregparm;
2252 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2253 if (Mregparm != 4) {
2254 getToolChain().getDriver().Diag(
2255 diag::err_drv_unsupported_option_argument)
2256 << A->getSpelling() << Value;
2257 }
2258 }
2259 }
2260}
2261
2262void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2263 ArgStringList &CmdArgs) const {
2264 // Default to "hidden" visibility.
2265 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2266 options::OPT_fvisibility_ms_compat))
2267 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2268}
2269
2270void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2271 // Floating point operations and argument passing are hard.
2272 CmdArgs.push_back(Elt: "-mfloat-abi");
2273 CmdArgs.push_back(Elt: "hard");
2274}
2275
2276void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2277 StringRef Target, const InputInfo &Output,
2278 const InputInfo &Input, const ArgList &Args) const {
2279 // If this is a dry run, do not create the compilation database file.
2280 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2281 return;
2282
2283 using llvm::yaml::escape;
2284 const Driver &D = getToolChain().getDriver();
2285
2286 if (!CompilationDatabase) {
2287 std::error_code EC;
2288 auto File = std::make_unique<llvm::raw_fd_ostream>(
2289 args&: Filename, args&: EC,
2290 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2291 if (EC) {
2292 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2293 << EC.message();
2294 return;
2295 }
2296 CompilationDatabase = std::move(File);
2297 }
2298 auto &CDB = *CompilationDatabase;
2299 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2300 if (!CWD)
2301 CWD = ".";
2302 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2303 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2304 if (Output.isFilename())
2305 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2306 CDB << ", \"arguments\": [\"" << escape(Input: D.ClangExecutable) << "\"";
2307 SmallString<128> Buf;
2308 Buf = "-x";
2309 Buf += types::getTypeName(Id: Input.getType());
2310 CDB << ", \"" << escape(Input: Buf) << "\"";
2311 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2312 Buf = "--sysroot=";
2313 Buf += D.SysRoot;
2314 CDB << ", \"" << escape(Input: Buf) << "\"";
2315 }
2316 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2317 if (Output.isFilename())
2318 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2319 for (auto &A: Args) {
2320 auto &O = A->getOption();
2321 // Skip language selection, which is positional.
2322 if (O.getID() == options::OPT_x)
2323 continue;
2324 // Skip writing dependency output and the compilation database itself.
2325 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2326 continue;
2327 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2328 continue;
2329 // Skip inputs.
2330 if (O.getKind() == Option::InputClass)
2331 continue;
2332 // Skip output.
2333 if (O.getID() == options::OPT_o)
2334 continue;
2335 // All other arguments are quoted and appended.
2336 ArgStringList ASL;
2337 A->render(Args, Output&: ASL);
2338 for (auto &it: ASL)
2339 CDB << ", \"" << escape(Input: it) << "\"";
2340 }
2341 Buf = "--target=";
2342 Buf += Target;
2343 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2344}
2345
2346void Clang::DumpCompilationDatabaseFragmentToDir(
2347 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2348 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2349 // If this is a dry run, do not create the compilation database file.
2350 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2351 return;
2352
2353 if (CompilationDatabase)
2354 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2355
2356 SmallString<256> Path = Dir;
2357 const auto &Driver = C.getDriver();
2358 Driver.getVFS().makeAbsolute(Path);
2359 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2360 if (Err) {
2361 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2362 return;
2363 }
2364
2365 llvm::sys::path::append(
2366 path&: Path,
2367 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2368 int FD;
2369 SmallString<256> TempPath;
2370 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2371 Flags: llvm::sys::fs::OF_Text);
2372 if (Err) {
2373 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2374 return;
2375 }
2376 CompilationDatabase =
2377 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2378 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2379}
2380
2381static bool CheckARMImplicitITArg(StringRef Value) {
2382 return Value == "always" || Value == "never" || Value == "arm" ||
2383 Value == "thumb";
2384}
2385
2386static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2387 StringRef Value) {
2388 CmdArgs.push_back(Elt: "-mllvm");
2389 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2390}
2391
2392static void CollectArgsForIntegratedAssembler(Compilation &C,
2393 const ArgList &Args,
2394 ArgStringList &CmdArgs,
2395 const Driver &D) {
2396 // Default to -mno-relax-all.
2397 //
2398 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2399 // cannot be done by assembler branch relaxation as it needs a free temporary
2400 // register. Because of this, branch relaxation is handled by a MachineIR pass
2401 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2402 // MachineIR branch relaxation inaccurate and it will miss cases where an
2403 // indirect branch is necessary.
2404 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2405 options::OPT_mno_relax_all);
2406
2407 // Only default to -mincremental-linker-compatible if we think we are
2408 // targeting the MSVC linker.
2409 bool DefaultIncrementalLinkerCompatible =
2410 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2411 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2412 options::OPT_mno_incremental_linker_compatible,
2413 DefaultIncrementalLinkerCompatible))
2414 CmdArgs.push_back(Elt: "-mincremental-linker-compatible");
2415
2416 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2417
2418 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2419 options::OPT_fno_emit_compact_unwind_non_canonical);
2420
2421 // If you add more args here, also add them to the block below that
2422 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2423
2424 // When passing -I arguments to the assembler we sometimes need to
2425 // unconditionally take the next argument. For example, when parsing
2426 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2427 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2428 // arg after parsing the '-I' arg.
2429 bool TakeNextArg = false;
2430
2431 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2432 bool IsELF = Triple.isOSBinFormatELF();
2433 bool Crel = false, ExperimentalCrel = false;
2434 bool ImplicitMapSyms = false;
2435 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2436 bool UseNoExecStack = false;
2437 bool Msa = false;
2438 const char *MipsTargetFeature = nullptr;
2439 llvm::SmallVector<const char *> SparcTargetFeatures;
2440 StringRef ImplicitIt;
2441 for (const Arg *A :
2442 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2443 options::OPT_mimplicit_it_EQ)) {
2444 A->claim();
2445
2446 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2447 switch (C.getDefaultToolChain().getArch()) {
2448 case llvm::Triple::arm:
2449 case llvm::Triple::armeb:
2450 case llvm::Triple::thumb:
2451 case llvm::Triple::thumbeb:
2452 // Only store the value; the last value set takes effect.
2453 ImplicitIt = A->getValue();
2454 if (!CheckARMImplicitITArg(ImplicitIt))
2455 D.Diag(diag::err_drv_unsupported_option_argument)
2456 << A->getSpelling() << ImplicitIt;
2457 continue;
2458 default:
2459 break;
2460 }
2461 }
2462
2463 for (StringRef Value : A->getValues()) {
2464 if (TakeNextArg) {
2465 CmdArgs.push_back(Value.data());
2466 TakeNextArg = false;
2467 continue;
2468 }
2469
2470 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2471 Value == "-mbig-obj")
2472 continue; // LLVM handles bigobj automatically
2473
2474 auto Equal = Value.split('=');
2475 auto checkArg = [&](bool ValidTarget,
2476 std::initializer_list<const char *> Set) {
2477 if (!ValidTarget) {
2478 D.Diag(diag::err_drv_unsupported_opt_for_target)
2479 << (Twine("-Wa,") + Equal.first + "=").str()
2480 << Triple.getTriple();
2481 } else if (!llvm::is_contained(Set, Equal.second)) {
2482 D.Diag(diag::err_drv_unsupported_option_argument)
2483 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2484 }
2485 };
2486 switch (C.getDefaultToolChain().getArch()) {
2487 default:
2488 break;
2489 case llvm::Triple::x86:
2490 case llvm::Triple::x86_64:
2491 if (Equal.first == "-mrelax-relocations" ||
2492 Equal.first == "--mrelax-relocations") {
2493 UseRelaxRelocations = Equal.second == "yes";
2494 checkArg(IsELF, {"yes", "no"});
2495 continue;
2496 }
2497 if (Value == "-msse2avx") {
2498 CmdArgs.push_back("-msse2avx");
2499 continue;
2500 }
2501 break;
2502 case llvm::Triple::wasm32:
2503 case llvm::Triple::wasm64:
2504 if (Value == "--no-type-check") {
2505 CmdArgs.push_back("-mno-type-check");
2506 continue;
2507 }
2508 break;
2509 case llvm::Triple::thumb:
2510 case llvm::Triple::thumbeb:
2511 case llvm::Triple::arm:
2512 case llvm::Triple::armeb:
2513 if (Equal.first == "-mimplicit-it") {
2514 // Only store the value; the last value set takes effect.
2515 ImplicitIt = Equal.second;
2516 checkArg(true, {"always", "never", "arm", "thumb"});
2517 continue;
2518 }
2519 if (Value == "-mthumb")
2520 // -mthumb has already been processed in ComputeLLVMTriple()
2521 // recognize but skip over here.
2522 continue;
2523 break;
2524 case llvm::Triple::aarch64:
2525 case llvm::Triple::aarch64_be:
2526 case llvm::Triple::aarch64_32:
2527 if (Equal.first == "-mmapsyms") {
2528 ImplicitMapSyms = Equal.second == "implicit";
2529 checkArg(IsELF, {"default", "implicit"});
2530 continue;
2531 }
2532 break;
2533 case llvm::Triple::mips:
2534 case llvm::Triple::mipsel:
2535 case llvm::Triple::mips64:
2536 case llvm::Triple::mips64el:
2537 if (Value == "--trap") {
2538 CmdArgs.push_back("-target-feature");
2539 CmdArgs.push_back("+use-tcc-in-div");
2540 continue;
2541 }
2542 if (Value == "--break") {
2543 CmdArgs.push_back("-target-feature");
2544 CmdArgs.push_back("-use-tcc-in-div");
2545 continue;
2546 }
2547 if (Value.starts_with("-msoft-float")) {
2548 CmdArgs.push_back("-target-feature");
2549 CmdArgs.push_back("+soft-float");
2550 continue;
2551 }
2552 if (Value.starts_with("-mhard-float")) {
2553 CmdArgs.push_back("-target-feature");
2554 CmdArgs.push_back("-soft-float");
2555 continue;
2556 }
2557 if (Value == "-mmsa") {
2558 Msa = true;
2559 continue;
2560 }
2561 if (Value == "-mno-msa") {
2562 Msa = false;
2563 continue;
2564 }
2565 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2566 .Case("-mips1", "+mips1")
2567 .Case("-mips2", "+mips2")
2568 .Case("-mips3", "+mips3")
2569 .Case("-mips4", "+mips4")
2570 .Case("-mips5", "+mips5")
2571 .Case("-mips32", "+mips32")
2572 .Case("-mips32r2", "+mips32r2")
2573 .Case("-mips32r3", "+mips32r3")
2574 .Case("-mips32r5", "+mips32r5")
2575 .Case("-mips32r6", "+mips32r6")
2576 .Case("-mips64", "+mips64")
2577 .Case("-mips64r2", "+mips64r2")
2578 .Case("-mips64r3", "+mips64r3")
2579 .Case("-mips64r5", "+mips64r5")
2580 .Case("-mips64r6", "+mips64r6")
2581 .Default(nullptr);
2582 if (MipsTargetFeature)
2583 continue;
2584 break;
2585
2586 case llvm::Triple::sparc:
2587 case llvm::Triple::sparcel:
2588 case llvm::Triple::sparcv9:
2589 if (Value == "--undeclared-regs") {
2590 // LLVM already allows undeclared use of G registers, so this option
2591 // becomes a no-op. This solely exists for GNU compatibility.
2592 // TODO implement --no-undeclared-regs
2593 continue;
2594 }
2595 SparcTargetFeatures =
2596 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2597 .Case("-Av8", {"-v8plus"})
2598 .Case("-Av8plus", {"+v8plus", "+v9"})
2599 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2600 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2601 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2602 .Case("-Av9", {"+v9"})
2603 .Case("-Av9a", {"+v9", "+vis"})
2604 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2605 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2606 .Default({});
2607 if (!SparcTargetFeatures.empty())
2608 continue;
2609 break;
2610 }
2611
2612 if (Value == "-force_cpusubtype_ALL") {
2613 // Do nothing, this is the default and we don't support anything else.
2614 } else if (Value == "-L") {
2615 CmdArgs.push_back("-msave-temp-labels");
2616 } else if (Value == "--fatal-warnings") {
2617 CmdArgs.push_back("-massembler-fatal-warnings");
2618 } else if (Value == "--no-warn" || Value == "-W") {
2619 CmdArgs.push_back("-massembler-no-warn");
2620 } else if (Value == "--noexecstack") {
2621 UseNoExecStack = true;
2622 } else if (Value.starts_with("-compress-debug-sections") ||
2623 Value.starts_with("--compress-debug-sections") ||
2624 Value == "-nocompress-debug-sections" ||
2625 Value == "--nocompress-debug-sections") {
2626 CmdArgs.push_back(Value.data());
2627 } else if (Value == "--crel") {
2628 Crel = true;
2629 } else if (Value == "--no-crel") {
2630 Crel = false;
2631 } else if (Value == "--allow-experimental-crel") {
2632 ExperimentalCrel = true;
2633 } else if (Value.starts_with("-I")) {
2634 CmdArgs.push_back(Value.data());
2635 // We need to consume the next argument if the current arg is a plain
2636 // -I. The next arg will be the include directory.
2637 if (Value == "-I")
2638 TakeNextArg = true;
2639 } else if (Value.starts_with("-gdwarf-")) {
2640 // "-gdwarf-N" options are not cc1as options.
2641 unsigned DwarfVersion = DwarfVersionNum(Value);
2642 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2643 CmdArgs.push_back(Value.data());
2644 } else {
2645 RenderDebugEnablingArgs(Args, CmdArgs,
2646 llvm::codegenoptions::DebugInfoConstructor,
2647 DwarfVersion, llvm::DebuggerKind::Default);
2648 }
2649 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2650 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2651 // Do nothing, we'll validate it later.
2652 } else if (Value == "-defsym" || Value == "--defsym") {
2653 if (A->getNumValues() != 2) {
2654 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2655 break;
2656 }
2657 const char *S = A->getValue(1);
2658 auto Pair = StringRef(S).split('=');
2659 auto Sym = Pair.first;
2660 auto SVal = Pair.second;
2661
2662 if (Sym.empty() || SVal.empty()) {
2663 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2664 break;
2665 }
2666 int64_t IVal;
2667 if (SVal.getAsInteger(0, IVal)) {
2668 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2669 break;
2670 }
2671 CmdArgs.push_back("--defsym");
2672 TakeNextArg = true;
2673 } else if (Value == "-fdebug-compilation-dir") {
2674 CmdArgs.push_back("-fdebug-compilation-dir");
2675 TakeNextArg = true;
2676 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2677 // The flag is a -Wa / -Xassembler argument and Options doesn't
2678 // parse the argument, so this isn't automatically aliased to
2679 // -fdebug-compilation-dir (without '=') here.
2680 CmdArgs.push_back("-fdebug-compilation-dir");
2681 CmdArgs.push_back(Value.data());
2682 } else if (Value == "--version") {
2683 D.PrintVersion(C, llvm::outs());
2684 } else {
2685 D.Diag(diag::err_drv_unsupported_option_argument)
2686 << A->getSpelling() << Value;
2687 }
2688 }
2689 }
2690 if (ImplicitIt.size())
2691 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2692 if (Crel) {
2693 if (!ExperimentalCrel)
2694 D.Diag(diag::err_drv_experimental_crel);
2695 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2696 CmdArgs.push_back(Elt: "--crel");
2697 } else {
2698 D.Diag(diag::err_drv_unsupported_opt_for_target)
2699 << "-Wa,--crel" << D.getTargetTriple();
2700 }
2701 }
2702 if (ImplicitMapSyms)
2703 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2704 if (Msa)
2705 CmdArgs.push_back(Elt: "-mmsa");
2706 if (!UseRelaxRelocations)
2707 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2708 if (UseNoExecStack)
2709 CmdArgs.push_back(Elt: "-mnoexecstack");
2710 if (MipsTargetFeature != nullptr) {
2711 CmdArgs.push_back(Elt: "-target-feature");
2712 CmdArgs.push_back(Elt: MipsTargetFeature);
2713 }
2714
2715 // Those OSes default to enabling VIS on 64-bit SPARC.
2716 // See also the corresponding code for external assemblers in
2717 // sparc::getSparcAsmModeForCPU().
2718 bool IsSparcV9ATarget =
2719 (C.getDefaultToolChain().getArch() == llvm::Triple::sparcv9) &&
2720 (Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD());
2721 if (IsSparcV9ATarget && SparcTargetFeatures.empty()) {
2722 CmdArgs.push_back(Elt: "-target-feature");
2723 CmdArgs.push_back(Elt: "+vis");
2724 }
2725 for (const char *Feature : SparcTargetFeatures) {
2726 CmdArgs.push_back(Elt: "-target-feature");
2727 CmdArgs.push_back(Elt: Feature);
2728 }
2729
2730 // forward -fembed-bitcode to assmebler
2731 if (C.getDriver().embedBitcodeEnabled() ||
2732 C.getDriver().embedBitcodeMarkerOnly())
2733 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2734
2735 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2736 CmdArgs.push_back(Elt: "-as-secure-log-file");
2737 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2738 }
2739}
2740
2741static std::string ComplexRangeKindToStr(LangOptions::ComplexRangeKind Range) {
2742 switch (Range) {
2743 case LangOptions::ComplexRangeKind::CX_Full:
2744 return "full";
2745 break;
2746 case LangOptions::ComplexRangeKind::CX_Basic:
2747 return "basic";
2748 break;
2749 case LangOptions::ComplexRangeKind::CX_Improved:
2750 return "improved";
2751 break;
2752 case LangOptions::ComplexRangeKind::CX_Promoted:
2753 return "promoted";
2754 break;
2755 default:
2756 return "";
2757 }
2758}
2759
2760static std::string ComplexArithmeticStr(LangOptions::ComplexRangeKind Range) {
2761 return (Range == LangOptions::ComplexRangeKind::CX_None)
2762 ? ""
2763 : "-fcomplex-arithmetic=" + ComplexRangeKindToStr(Range);
2764}
2765
2766static void EmitComplexRangeDiag(const Driver &D, std::string str1,
2767 std::string str2) {
2768 if (str1 != str2 && !str2.empty() && !str1.empty()) {
2769 D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
2770 }
2771}
2772
2773static std::string
2774RenderComplexRangeOption(LangOptions::ComplexRangeKind Range) {
2775 std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
2776 if (!ComplexRangeStr.empty())
2777 return "-complex-range=" + ComplexRangeStr;
2778 return ComplexRangeStr;
2779}
2780
2781static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2782 bool OFastEnabled, const ArgList &Args,
2783 ArgStringList &CmdArgs,
2784 const JobAction &JA) {
2785 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2786 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2787 llvm::StringLiteral("SLEEF")};
2788 bool NoMathErrnoWasImpliedByVecLib = false;
2789 const Arg *VecLibArg = nullptr;
2790 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2791 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2792
2793 // Handle various floating point optimization flags, mapping them to the
2794 // appropriate LLVM code generation flags. This is complicated by several
2795 // "umbrella" flags, so we do this by stepping through the flags incrementally
2796 // adjusting what we think is enabled/disabled, then at the end setting the
2797 // LLVM flags based on the final state.
2798 bool HonorINFs = true;
2799 bool HonorNaNs = true;
2800 bool ApproxFunc = false;
2801 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2802 bool MathErrno = TC.IsMathErrnoDefault();
2803 bool AssociativeMath = false;
2804 bool ReciprocalMath = false;
2805 bool SignedZeros = true;
2806 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2807 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2808 // overriden by ffp-exception-behavior?
2809 bool RoundingFPMath = false;
2810 // -ffp-model values: strict, fast, precise
2811 StringRef FPModel = "";
2812 // -ffp-exception-behavior options: strict, maytrap, ignore
2813 StringRef FPExceptionBehavior = "";
2814 // -ffp-eval-method options: double, extended, source
2815 StringRef FPEvalMethod = "";
2816 llvm::DenormalMode DenormalFPMath =
2817 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2818 llvm::DenormalMode DenormalFP32Math =
2819 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2820
2821 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2822 // If one wasn't given by the user, don't pass it here.
2823 StringRef FPContract;
2824 StringRef LastSeenFfpContractOption;
2825 StringRef LastFpContractOverrideOption;
2826 bool SeenUnsafeMathModeOption = false;
2827 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2828 !JA.isOffloading(OKind: Action::OFK_HIP))
2829 FPContract = "on";
2830 bool StrictFPModel = false;
2831 StringRef Float16ExcessPrecision = "";
2832 StringRef BFloat16ExcessPrecision = "";
2833 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2834 std::string ComplexRangeStr = "";
2835 std::string GccRangeComplexOption = "";
2836
2837 auto setComplexRange = [&](LangOptions::ComplexRangeKind NewRange) {
2838 // Warn if user expects to perform full implementation of complex
2839 // multiplication or division in the presence of nnan or ninf flags.
2840 if (Range != NewRange)
2841 EmitComplexRangeDiag(D,
2842 str1: !GccRangeComplexOption.empty()
2843 ? GccRangeComplexOption
2844 : ComplexArithmeticStr(Range),
2845 str2: ComplexArithmeticStr(Range: NewRange));
2846 Range = NewRange;
2847 };
2848
2849 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2850 auto applyFastMath = [&](bool Aggressive) {
2851 if (Aggressive) {
2852 HonorINFs = false;
2853 HonorNaNs = false;
2854 setComplexRange(LangOptions::ComplexRangeKind::CX_Basic);
2855 } else {
2856 HonorINFs = true;
2857 HonorNaNs = true;
2858 setComplexRange(LangOptions::ComplexRangeKind::CX_Promoted);
2859 }
2860 MathErrno = false;
2861 AssociativeMath = true;
2862 ReciprocalMath = true;
2863 ApproxFunc = true;
2864 SignedZeros = false;
2865 TrappingMath = false;
2866 RoundingFPMath = false;
2867 FPExceptionBehavior = "";
2868 FPContract = "fast";
2869 SeenUnsafeMathModeOption = true;
2870 };
2871
2872 // Lambda to consolidate common handling for fp-contract
2873 auto restoreFPContractState = [&]() {
2874 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2875 // For other targets, if the state has been changed by one of the
2876 // unsafe-math umbrella options a subsequent -fno-fast-math or
2877 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2878 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2879 // option. If we have not seen an unsafe-math option or -ffp-contract,
2880 // we leave the FPContract state unchanged.
2881 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2882 !JA.isOffloading(OKind: Action::OFK_HIP)) {
2883 if (LastSeenFfpContractOption != "")
2884 FPContract = LastSeenFfpContractOption;
2885 else if (SeenUnsafeMathModeOption)
2886 FPContract = "on";
2887 }
2888 // In this case, we're reverting to the last explicit fp-contract option
2889 // or the platform default
2890 LastFpContractOverrideOption = "";
2891 };
2892
2893 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2894 CmdArgs.push_back(Elt: "-mlimit-float-precision");
2895 CmdArgs.push_back(Elt: A->getValue());
2896 }
2897
2898 for (const Arg *A : Args) {
2899 auto CheckMathErrnoForVecLib =
2900 llvm::make_scope_exit(F: [&, MathErrnoBeforeArg = MathErrno] {
2901 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2902 ArgThatEnabledMathErrnoAfterVecLib = A;
2903 });
2904
2905 switch (A->getOption().getID()) {
2906 // If this isn't an FP option skip the claim below
2907 default: continue;
2908
2909 case options::OPT_fcx_limited_range:
2910 if (GccRangeComplexOption.empty()) {
2911 if (Range != LangOptions::ComplexRangeKind::CX_Basic)
2912 EmitComplexRangeDiag(D, str1: RenderComplexRangeOption(Range),
2913 str2: "-fcx-limited-range");
2914 } else {
2915 if (GccRangeComplexOption != "-fno-cx-limited-range")
2916 EmitComplexRangeDiag(D, str1: GccRangeComplexOption, str2: "-fcx-limited-range");
2917 }
2918 GccRangeComplexOption = "-fcx-limited-range";
2919 Range = LangOptions::ComplexRangeKind::CX_Basic;
2920 break;
2921 case options::OPT_fno_cx_limited_range:
2922 if (GccRangeComplexOption.empty()) {
2923 EmitComplexRangeDiag(D, str1: RenderComplexRangeOption(Range),
2924 str2: "-fno-cx-limited-range");
2925 } else {
2926 if (GccRangeComplexOption != "-fcx-limited-range" &&
2927 GccRangeComplexOption != "-fno-cx-fortran-rules")
2928 EmitComplexRangeDiag(D, str1: GccRangeComplexOption,
2929 str2: "-fno-cx-limited-range");
2930 }
2931 GccRangeComplexOption = "-fno-cx-limited-range";
2932 Range = LangOptions::ComplexRangeKind::CX_Full;
2933 break;
2934 case options::OPT_fcx_fortran_rules:
2935 if (GccRangeComplexOption.empty())
2936 EmitComplexRangeDiag(D, str1: RenderComplexRangeOption(Range),
2937 str2: "-fcx-fortran-rules");
2938 else
2939 EmitComplexRangeDiag(D, str1: GccRangeComplexOption, str2: "-fcx-fortran-rules");
2940 GccRangeComplexOption = "-fcx-fortran-rules";
2941 Range = LangOptions::ComplexRangeKind::CX_Improved;
2942 break;
2943 case options::OPT_fno_cx_fortran_rules:
2944 if (GccRangeComplexOption.empty()) {
2945 EmitComplexRangeDiag(D, str1: RenderComplexRangeOption(Range),
2946 str2: "-fno-cx-fortran-rules");
2947 } else {
2948 if (GccRangeComplexOption != "-fno-cx-limited-range")
2949 EmitComplexRangeDiag(D, str1: GccRangeComplexOption,
2950 str2: "-fno-cx-fortran-rules");
2951 }
2952 GccRangeComplexOption = "-fno-cx-fortran-rules";
2953 Range = LangOptions::ComplexRangeKind::CX_Full;
2954 break;
2955 case options::OPT_fcomplex_arithmetic_EQ: {
2956 LangOptions::ComplexRangeKind RangeVal;
2957 StringRef Val = A->getValue();
2958 if (Val == "full")
2959 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2960 else if (Val == "improved")
2961 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2962 else if (Val == "promoted")
2963 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2964 else if (Val == "basic")
2965 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2966 else {
2967 D.Diag(diag::err_drv_unsupported_option_argument)
2968 << A->getSpelling() << Val;
2969 break;
2970 }
2971 if (!GccRangeComplexOption.empty()) {
2972 if (GccRangeComplexOption != "-fcx-limited-range") {
2973 if (GccRangeComplexOption != "-fcx-fortran-rules") {
2974 if (RangeVal != LangOptions::ComplexRangeKind::CX_Improved)
2975 EmitComplexRangeDiag(D, str1: GccRangeComplexOption,
2976 str2: ComplexArithmeticStr(Range: RangeVal));
2977 } else {
2978 EmitComplexRangeDiag(D, str1: GccRangeComplexOption,
2979 str2: ComplexArithmeticStr(Range: RangeVal));
2980 }
2981 } else {
2982 if (RangeVal != LangOptions::ComplexRangeKind::CX_Basic)
2983 EmitComplexRangeDiag(D, str1: GccRangeComplexOption,
2984 str2: ComplexArithmeticStr(Range: RangeVal));
2985 }
2986 }
2987 Range = RangeVal;
2988 break;
2989 }
2990 case options::OPT_ffp_model_EQ: {
2991 // If -ffp-model= is seen, reset to fno-fast-math
2992 HonorINFs = true;
2993 HonorNaNs = true;
2994 ApproxFunc = false;
2995 // Turning *off* -ffast-math restores the toolchain default.
2996 MathErrno = TC.IsMathErrnoDefault();
2997 AssociativeMath = false;
2998 ReciprocalMath = false;
2999 SignedZeros = true;
3000
3001 StringRef Val = A->getValue();
3002 if (OFastEnabled && Val != "aggressive") {
3003 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3004 D.Diag(clang::diag::warn_drv_overriding_option)
3005 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3006 break;
3007 }
3008 StrictFPModel = false;
3009 if (!FPModel.empty() && FPModel != Val)
3010 D.Diag(clang::diag::warn_drv_overriding_option)
3011 << Args.MakeArgString("-ffp-model=" + FPModel)
3012 << Args.MakeArgString("-ffp-model=" + Val);
3013 if (Val == "fast") {
3014 FPModel = Val;
3015 applyFastMath(false);
3016 // applyFastMath sets fp-contract="fast"
3017 LastFpContractOverrideOption = "-ffp-model=fast";
3018 } else if (Val == "aggressive") {
3019 FPModel = Val;
3020 applyFastMath(true);
3021 // applyFastMath sets fp-contract="fast"
3022 LastFpContractOverrideOption = "-ffp-model=aggressive";
3023 } else if (Val == "precise") {
3024 FPModel = Val;
3025 FPContract = "on";
3026 LastFpContractOverrideOption = "-ffp-model=precise";
3027 setComplexRange(LangOptions::ComplexRangeKind::CX_Full);
3028 } else if (Val == "strict") {
3029 StrictFPModel = true;
3030 FPExceptionBehavior = "strict";
3031 FPModel = Val;
3032 FPContract = "off";
3033 LastFpContractOverrideOption = "-ffp-model=strict";
3034 TrappingMath = true;
3035 RoundingFPMath = true;
3036 setComplexRange(LangOptions::ComplexRangeKind::CX_Full);
3037 } else
3038 D.Diag(diag::err_drv_unsupported_option_argument)
3039 << A->getSpelling() << Val;
3040 break;
3041 }
3042
3043 // Options controlling individual features
3044 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3045 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3046 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3047 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3048 case options::OPT_fapprox_func: ApproxFunc = true; break;
3049 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3050 case options::OPT_fmath_errno: MathErrno = true; break;
3051 case options::OPT_fno_math_errno: MathErrno = false; break;
3052 case options::OPT_fassociative_math: AssociativeMath = true; break;
3053 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3054 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3055 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3056 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3057 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3058 case options::OPT_ftrapping_math:
3059 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3060 FPExceptionBehavior != "strict")
3061 // Warn that previous value of option is overridden.
3062 D.Diag(clang::diag::warn_drv_overriding_option)
3063 << Args.MakeArgString("-ffp-exception-behavior=" +
3064 FPExceptionBehavior)
3065 << "-ftrapping-math";
3066 TrappingMath = true;
3067 TrappingMathPresent = true;
3068 FPExceptionBehavior = "strict";
3069 break;
3070 case options::OPT_fveclib:
3071 VecLibArg = A;
3072 NoMathErrnoWasImpliedByVecLib =
3073 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3074 if (NoMathErrnoWasImpliedByVecLib)
3075 MathErrno = false;
3076 break;
3077 case options::OPT_fno_trapping_math:
3078 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3079 FPExceptionBehavior != "ignore")
3080 // Warn that previous value of option is overridden.
3081 D.Diag(clang::diag::warn_drv_overriding_option)
3082 << Args.MakeArgString("-ffp-exception-behavior=" +
3083 FPExceptionBehavior)
3084 << "-fno-trapping-math";
3085 TrappingMath = false;
3086 TrappingMathPresent = true;
3087 FPExceptionBehavior = "ignore";
3088 break;
3089
3090 case options::OPT_frounding_math:
3091 RoundingFPMath = true;
3092 break;
3093
3094 case options::OPT_fno_rounding_math:
3095 RoundingFPMath = false;
3096 break;
3097
3098 case options::OPT_fdenormal_fp_math_EQ:
3099 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3100 DenormalFP32Math = DenormalFPMath;
3101 if (!DenormalFPMath.isValid()) {
3102 D.Diag(diag::err_drv_invalid_value)
3103 << A->getAsString(Args) << A->getValue();
3104 }
3105 break;
3106
3107 case options::OPT_fdenormal_fp_math_f32_EQ:
3108 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3109 if (!DenormalFP32Math.isValid()) {
3110 D.Diag(diag::err_drv_invalid_value)
3111 << A->getAsString(Args) << A->getValue();
3112 }
3113 break;
3114
3115 // Validate and pass through -ffp-contract option.
3116 case options::OPT_ffp_contract: {
3117 StringRef Val = A->getValue();
3118 if (Val == "fast" || Val == "on" || Val == "off" ||
3119 Val == "fast-honor-pragmas") {
3120 if (Val != FPContract && LastFpContractOverrideOption != "") {
3121 D.Diag(clang::diag::warn_drv_overriding_option)
3122 << LastFpContractOverrideOption
3123 << Args.MakeArgString("-ffp-contract=" + Val);
3124 }
3125
3126 FPContract = Val;
3127 LastSeenFfpContractOption = Val;
3128 LastFpContractOverrideOption = "";
3129 } else
3130 D.Diag(diag::err_drv_unsupported_option_argument)
3131 << A->getSpelling() << Val;
3132 break;
3133 }
3134
3135 // Validate and pass through -ffp-exception-behavior option.
3136 case options::OPT_ffp_exception_behavior_EQ: {
3137 StringRef Val = A->getValue();
3138 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3139 FPExceptionBehavior != Val)
3140 // Warn that previous value of option is overridden.
3141 D.Diag(clang::diag::warn_drv_overriding_option)
3142 << Args.MakeArgString("-ffp-exception-behavior=" +
3143 FPExceptionBehavior)
3144 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3145 TrappingMath = TrappingMathPresent = false;
3146 if (Val == "ignore" || Val == "maytrap")
3147 FPExceptionBehavior = Val;
3148 else if (Val == "strict") {
3149 FPExceptionBehavior = Val;
3150 TrappingMath = TrappingMathPresent = true;
3151 } else
3152 D.Diag(diag::err_drv_unsupported_option_argument)
3153 << A->getSpelling() << Val;
3154 break;
3155 }
3156
3157 // Validate and pass through -ffp-eval-method option.
3158 case options::OPT_ffp_eval_method_EQ: {
3159 StringRef Val = A->getValue();
3160 if (Val == "double" || Val == "extended" || Val == "source")
3161 FPEvalMethod = Val;
3162 else
3163 D.Diag(diag::err_drv_unsupported_option_argument)
3164 << A->getSpelling() << Val;
3165 break;
3166 }
3167
3168 case options::OPT_fexcess_precision_EQ: {
3169 StringRef Val = A->getValue();
3170 const llvm::Triple::ArchType Arch = TC.getArch();
3171 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3172 if (Val == "standard" || Val == "fast")
3173 Float16ExcessPrecision = Val;
3174 // To make it GCC compatible, allow the value of "16" which
3175 // means disable excess precision, the same meaning than clang's
3176 // equivalent value "none".
3177 else if (Val == "16")
3178 Float16ExcessPrecision = "none";
3179 else
3180 D.Diag(diag::err_drv_unsupported_option_argument)
3181 << A->getSpelling() << Val;
3182 } else {
3183 if (!(Val == "standard" || Val == "fast"))
3184 D.Diag(diag::err_drv_unsupported_option_argument)
3185 << A->getSpelling() << Val;
3186 }
3187 BFloat16ExcessPrecision = Float16ExcessPrecision;
3188 break;
3189 }
3190 case options::OPT_ffinite_math_only:
3191 HonorINFs = false;
3192 HonorNaNs = false;
3193 break;
3194 case options::OPT_fno_finite_math_only:
3195 HonorINFs = true;
3196 HonorNaNs = true;
3197 break;
3198
3199 case options::OPT_funsafe_math_optimizations:
3200 AssociativeMath = true;
3201 ReciprocalMath = true;
3202 SignedZeros = false;
3203 ApproxFunc = true;
3204 TrappingMath = false;
3205 FPExceptionBehavior = "";
3206 FPContract = "fast";
3207 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3208 SeenUnsafeMathModeOption = true;
3209 break;
3210 case options::OPT_fno_unsafe_math_optimizations:
3211 AssociativeMath = false;
3212 ReciprocalMath = false;
3213 SignedZeros = true;
3214 ApproxFunc = false;
3215 restoreFPContractState();
3216 break;
3217
3218 case options::OPT_Ofast:
3219 // If -Ofast is the optimization level, then -ffast-math should be enabled
3220 if (!OFastEnabled)
3221 continue;
3222 [[fallthrough]];
3223 case options::OPT_ffast_math:
3224 applyFastMath(true);
3225 if (A->getOption().getID() == options::OPT_Ofast)
3226 LastFpContractOverrideOption = "-Ofast";
3227 else
3228 LastFpContractOverrideOption = "-ffast-math";
3229 break;
3230 case options::OPT_fno_fast_math:
3231 HonorINFs = true;
3232 HonorNaNs = true;
3233 // Turning on -ffast-math (with either flag) removes the need for
3234 // MathErrno. However, turning *off* -ffast-math merely restores the
3235 // toolchain default (which may be false).
3236 MathErrno = TC.IsMathErrnoDefault();
3237 AssociativeMath = false;
3238 ReciprocalMath = false;
3239 ApproxFunc = false;
3240 SignedZeros = true;
3241 restoreFPContractState();
3242 LastFpContractOverrideOption = "";
3243 break;
3244 } // End switch (A->getOption().getID())
3245
3246 // The StrictFPModel local variable is needed to report warnings
3247 // in the way we intend. If -ffp-model=strict has been used, we
3248 // want to report a warning for the next option encountered that
3249 // takes us out of the settings described by fp-model=strict, but
3250 // we don't want to continue issuing warnings for other conflicting
3251 // options after that.
3252 if (StrictFPModel) {
3253 // If -ffp-model=strict has been specified on command line but
3254 // subsequent options conflict then emit warning diagnostic.
3255 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3256 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3257 FPContract == "off")
3258 // OK: Current Arg doesn't conflict with -ffp-model=strict
3259 ;
3260 else {
3261 StrictFPModel = false;
3262 FPModel = "";
3263 // The warning for -ffp-contract would have been reported by the
3264 // OPT_ffp_contract_EQ handler above. A special check here is needed
3265 // to avoid duplicating the warning.
3266 auto RHS = (A->getNumValues() == 0)
3267 ? A->getSpelling()
3268 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3269 if (A->getSpelling() != "-ffp-contract=") {
3270 if (RHS != "-ffp-model=strict")
3271 D.Diag(clang::diag::warn_drv_overriding_option)
3272 << "-ffp-model=strict" << RHS;
3273 }
3274 }
3275 }
3276
3277 // If we handled this option claim it
3278 A->claim();
3279 }
3280
3281 if (!HonorINFs)
3282 CmdArgs.push_back(Elt: "-menable-no-infs");
3283
3284 if (!HonorNaNs)
3285 CmdArgs.push_back(Elt: "-menable-no-nans");
3286
3287 if (ApproxFunc)
3288 CmdArgs.push_back(Elt: "-fapprox-func");
3289
3290 if (MathErrno) {
3291 CmdArgs.push_back(Elt: "-fmath-errno");
3292 if (NoMathErrnoWasImpliedByVecLib)
3293 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3294 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3295 << VecLibArg->getAsString(Args);
3296 }
3297
3298 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3299 !TrappingMath)
3300 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3301
3302 if (!SignedZeros)
3303 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3304
3305 if (AssociativeMath && !SignedZeros && !TrappingMath)
3306 CmdArgs.push_back(Elt: "-mreassociate");
3307
3308 if (ReciprocalMath)
3309 CmdArgs.push_back(Elt: "-freciprocal-math");
3310
3311 if (TrappingMath) {
3312 // FP Exception Behavior is also set to strict
3313 assert(FPExceptionBehavior == "strict");
3314 }
3315
3316 // The default is IEEE.
3317 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3318 llvm::SmallString<64> DenormFlag;
3319 llvm::raw_svector_ostream ArgStr(DenormFlag);
3320 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3321 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3322 }
3323
3324 // Add f32 specific denormal mode flag if it's different.
3325 if (DenormalFP32Math != DenormalFPMath) {
3326 llvm::SmallString<64> DenormFlag;
3327 llvm::raw_svector_ostream ArgStr(DenormFlag);
3328 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3329 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3330 }
3331
3332 if (!FPContract.empty())
3333 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3334
3335 if (RoundingFPMath)
3336 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3337 else
3338 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3339
3340 if (!FPExceptionBehavior.empty())
3341 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3342 FPExceptionBehavior));
3343
3344 if (!FPEvalMethod.empty())
3345 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3346
3347 if (!Float16ExcessPrecision.empty())
3348 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3349 Float16ExcessPrecision));
3350 if (!BFloat16ExcessPrecision.empty())
3351 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3352 BFloat16ExcessPrecision));
3353
3354 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3355 if (!Recip.empty())
3356 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3357
3358 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3359 // individual features enabled by -ffast-math instead of the option itself as
3360 // that's consistent with gcc's behaviour.
3361 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3362 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3363 CmdArgs.push_back(Elt: "-ffast-math");
3364
3365 // Handle __FINITE_MATH_ONLY__ similarly.
3366 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3367 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3368 // -menable-no-nans are set by the user.
3369 bool shouldAddFiniteMathOnly = false;
3370 if (!HonorINFs && !HonorNaNs) {
3371 shouldAddFiniteMathOnly = true;
3372 } else {
3373 bool InfValues = true;
3374 bool NanValues = true;
3375 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3376 StringRef ArgValue = Arg->getValue();
3377 if (ArgValue == "-menable-no-nans")
3378 NanValues = false;
3379 else if (ArgValue == "-menable-no-infs")
3380 InfValues = false;
3381 }
3382 if (!NanValues && !InfValues)
3383 shouldAddFiniteMathOnly = true;
3384 }
3385 if (shouldAddFiniteMathOnly) {
3386 CmdArgs.push_back(Elt: "-ffinite-math-only");
3387 }
3388 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3389 CmdArgs.push_back(Elt: "-mfpmath");
3390 CmdArgs.push_back(Elt: A->getValue());
3391 }
3392
3393 // Disable a codegen optimization for floating-point casts.
3394 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3395 options::OPT_fstrict_float_cast_overflow, false))
3396 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3397
3398 if (Range != LangOptions::ComplexRangeKind::CX_None)
3399 ComplexRangeStr = RenderComplexRangeOption(Range);
3400 if (!ComplexRangeStr.empty()) {
3401 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3402 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3403 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3404 ComplexRangeKindToStr(Range)));
3405 }
3406 if (Args.hasArg(options::OPT_fcx_limited_range))
3407 CmdArgs.push_back(Elt: "-fcx-limited-range");
3408 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3409 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3410 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3411 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3412 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3413 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3414}
3415
3416static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3417 const llvm::Triple &Triple,
3418 const InputInfo &Input) {
3419 // Add default argument set.
3420 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3421 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3422 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3423
3424 if (!Triple.isWindowsMSVCEnvironment()) {
3425 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3426 } else {
3427 // Enable "unix" checkers that also work on Windows.
3428 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3429 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3430 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3431 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3432 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3433 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3434 }
3435
3436 // Disable some unix checkers for PS4/PS5.
3437 if (Triple.isPS()) {
3438 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3439 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3440 }
3441
3442 if (Triple.isOSDarwin()) {
3443 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3444 CmdArgs.push_back(
3445 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3446 }
3447 else if (Triple.isOSFuchsia())
3448 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3449
3450 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3451
3452 if (types::isCXX(Id: Input.getType()))
3453 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3454
3455 if (!Triple.isPS()) {
3456 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3457 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3458 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3459 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3460 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3461 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3462 }
3463
3464 // Default nullability checks.
3465 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3466 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3467 }
3468
3469 // Set the output format. The default is plist, for (lame) historical reasons.
3470 CmdArgs.push_back(Elt: "-analyzer-output");
3471 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3472 CmdArgs.push_back(Elt: A->getValue());
3473 else
3474 CmdArgs.push_back(Elt: "plist");
3475
3476 // Disable the presentation of standard compiler warnings when using
3477 // --analyze. We only want to show static analyzer diagnostics or frontend
3478 // errors.
3479 CmdArgs.push_back(Elt: "-w");
3480
3481 // Add -Xanalyzer arguments when running as analyzer.
3482 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3483}
3484
3485static bool isValidSymbolName(StringRef S) {
3486 if (S.empty())
3487 return false;
3488
3489 if (std::isdigit(S[0]))
3490 return false;
3491
3492 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3493}
3494
3495static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3496 const ArgList &Args, ArgStringList &CmdArgs,
3497 bool KernelOrKext) {
3498 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3499
3500 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3501 // doesn't even have a stack!
3502 if (EffectiveTriple.isNVPTX())
3503 return;
3504
3505 // -stack-protector=0 is default.
3506 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3507 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3508 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3509
3510 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3511 options::OPT_fstack_protector_all,
3512 options::OPT_fstack_protector_strong,
3513 options::OPT_fstack_protector)) {
3514 if (A->getOption().matches(options::OPT_fstack_protector))
3515 StackProtectorLevel =
3516 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3517 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3518 StackProtectorLevel = LangOptions::SSPStrong;
3519 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3520 StackProtectorLevel = LangOptions::SSPReq;
3521
3522 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3523 D.Diag(diag::warn_drv_unsupported_option_for_target)
3524 << A->getSpelling() << EffectiveTriple.getTriple();
3525 StackProtectorLevel = DefaultStackProtectorLevel;
3526 }
3527 } else {
3528 StackProtectorLevel = DefaultStackProtectorLevel;
3529 }
3530
3531 if (StackProtectorLevel) {
3532 CmdArgs.push_back(Elt: "-stack-protector");
3533 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3534 }
3535
3536 // --param ssp-buffer-size=
3537 for (const Arg *A : Args.filtered(options::OPT__param)) {
3538 StringRef Str(A->getValue());
3539 if (Str.consume_front("ssp-buffer-size=")) {
3540 if (StackProtectorLevel) {
3541 CmdArgs.push_back("-stack-protector-buffer-size");
3542 // FIXME: Verify the argument is a valid integer.
3543 CmdArgs.push_back(Args.MakeArgString(Str));
3544 }
3545 A->claim();
3546 }
3547 }
3548
3549 const std::string &TripleStr = EffectiveTriple.getTriple();
3550 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3551 StringRef Value = A->getValue();
3552 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3553 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3554 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3555 D.Diag(diag::err_drv_unsupported_opt_for_target)
3556 << A->getAsString(Args) << TripleStr;
3557 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3558 EffectiveTriple.isThumb()) &&
3559 Value != "tls" && Value != "global") {
3560 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3561 << A->getOption().getName() << Value << "tls global";
3562 return;
3563 }
3564 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3565 Value == "tls") {
3566 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3567 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3568 << A->getAsString(Args);
3569 return;
3570 }
3571 // Check whether the target subarch supports the hardware TLS register
3572 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3573 D.Diag(diag::err_target_unsupported_tp_hard)
3574 << EffectiveTriple.getArchName();
3575 return;
3576 }
3577 // Check whether the user asked for something other than -mtp=cp15
3578 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3579 StringRef Value = A->getValue();
3580 if (Value != "cp15") {
3581 D.Diag(diag::err_drv_argument_not_allowed_with)
3582 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3583 return;
3584 }
3585 }
3586 CmdArgs.push_back(Elt: "-target-feature");
3587 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3588 }
3589 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3590 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3591 << A->getOption().getName() << Value << "sysreg global";
3592 return;
3593 }
3594 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3595 if (Value != "tls" && Value != "global") {
3596 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3597 << A->getOption().getName() << Value << "tls global";
3598 return;
3599 }
3600 if (Value == "tls") {
3601 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3602 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3603 << A->getAsString(Args);
3604 return;
3605 }
3606 }
3607 }
3608 A->render(Args, Output&: CmdArgs);
3609 }
3610
3611 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3612 StringRef Value = A->getValue();
3613 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3614 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3615 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3616 D.Diag(diag::err_drv_unsupported_opt_for_target)
3617 << A->getAsString(Args) << TripleStr;
3618 int Offset;
3619 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3620 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3621 return;
3622 }
3623 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3624 (Offset < 0 || Offset > 0xfffff)) {
3625 D.Diag(diag::err_drv_invalid_int_value)
3626 << A->getOption().getName() << Value;
3627 return;
3628 }
3629 A->render(Args, Output&: CmdArgs);
3630 }
3631
3632 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3633 StringRef Value = A->getValue();
3634 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3635 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3636 D.Diag(diag::err_drv_unsupported_opt_for_target)
3637 << A->getAsString(Args) << TripleStr;
3638 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3639 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3640 << A->getOption().getName() << Value << "fs gs";
3641 return;
3642 }
3643 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3644 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3645 return;
3646 }
3647 if (EffectiveTriple.isRISCV() && Value != "tp") {
3648 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3649 << A->getOption().getName() << Value << "tp";
3650 return;
3651 }
3652 if (EffectiveTriple.isPPC64() && Value != "r13") {
3653 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3654 << A->getOption().getName() << Value << "r13";
3655 return;
3656 }
3657 if (EffectiveTriple.isPPC32() && Value != "r2") {
3658 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3659 << A->getOption().getName() << Value << "r2";
3660 return;
3661 }
3662 A->render(Args, Output&: CmdArgs);
3663 }
3664
3665 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3666 StringRef Value = A->getValue();
3667 if (!isValidSymbolName(S: Value)) {
3668 D.Diag(diag::err_drv_argument_only_allowed_with)
3669 << A->getOption().getName() << "legal symbol name";
3670 return;
3671 }
3672 A->render(Args, Output&: CmdArgs);
3673 }
3674}
3675
3676static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3677 ArgStringList &CmdArgs) {
3678 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3679
3680 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3681 !EffectiveTriple.isOSFuchsia())
3682 return;
3683
3684 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3685 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3686 !EffectiveTriple.isRISCV())
3687 return;
3688
3689 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3690 options::OPT_fno_stack_clash_protection);
3691}
3692
3693static void RenderTrivialAutoVarInitOptions(const Driver &D,
3694 const ToolChain &TC,
3695 const ArgList &Args,
3696 ArgStringList &CmdArgs) {
3697 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3698 StringRef TrivialAutoVarInit = "";
3699
3700 for (const Arg *A : Args) {
3701 switch (A->getOption().getID()) {
3702 default:
3703 continue;
3704 case options::OPT_ftrivial_auto_var_init: {
3705 A->claim();
3706 StringRef Val = A->getValue();
3707 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3708 TrivialAutoVarInit = Val;
3709 else
3710 D.Diag(diag::err_drv_unsupported_option_argument)
3711 << A->getSpelling() << Val;
3712 break;
3713 }
3714 }
3715 }
3716
3717 if (TrivialAutoVarInit.empty())
3718 switch (DefaultTrivialAutoVarInit) {
3719 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3720 break;
3721 case LangOptions::TrivialAutoVarInitKind::Pattern:
3722 TrivialAutoVarInit = "pattern";
3723 break;
3724 case LangOptions::TrivialAutoVarInitKind::Zero:
3725 TrivialAutoVarInit = "zero";
3726 break;
3727 }
3728
3729 if (!TrivialAutoVarInit.empty()) {
3730 CmdArgs.push_back(
3731 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3732 }
3733
3734 if (Arg *A =
3735 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3736 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3737 StringRef(
3738 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3739 "uninitialized")
3740 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3741 A->claim();
3742 StringRef Val = A->getValue();
3743 if (std::stoi(Val.str()) <= 0)
3744 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3745 CmdArgs.push_back(
3746 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3747 }
3748
3749 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3750 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3751 StringRef(
3752 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3753 "uninitialized")
3754 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3755 A->claim();
3756 StringRef Val = A->getValue();
3757 if (std::stoi(Val.str()) <= 0)
3758 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3759 CmdArgs.push_back(
3760 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3761 }
3762}
3763
3764static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3765 types::ID InputType) {
3766 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3767 // for denormal flushing handling based on the target.
3768 const unsigned ForwardedArguments[] = {
3769 options::OPT_cl_opt_disable,
3770 options::OPT_cl_strict_aliasing,
3771 options::OPT_cl_single_precision_constant,
3772 options::OPT_cl_finite_math_only,
3773 options::OPT_cl_kernel_arg_info,
3774 options::OPT_cl_unsafe_math_optimizations,
3775 options::OPT_cl_fast_relaxed_math,
3776 options::OPT_cl_mad_enable,
3777 options::OPT_cl_no_signed_zeros,
3778 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3779 options::OPT_cl_uniform_work_group_size
3780 };
3781
3782 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3783 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3784 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3785 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3786 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3787 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3788 }
3789
3790 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3791 CmdArgs.push_back(Elt: "-menable-no-infs");
3792 CmdArgs.push_back(Elt: "-menable-no-nans");
3793 }
3794
3795 for (const auto &Arg : ForwardedArguments)
3796 if (const auto *A = Args.getLastArg(Arg))
3797 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3798
3799 // Only add the default headers if we are compiling OpenCL sources.
3800 if ((types::isOpenCL(InputType) ||
3801 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3802 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3803 CmdArgs.push_back(Elt: "-finclude-default-header");
3804 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3805 }
3806}
3807
3808static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3809 types::ID InputType) {
3810 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3811 options::OPT_res_may_alias,
3812 options::OPT_D,
3813 options::OPT_I,
3814 options::OPT_O,
3815 options::OPT_emit_llvm,
3816 options::OPT_emit_obj,
3817 options::OPT_disable_llvm_passes,
3818 options::OPT_fnative_half_type,
3819 options::OPT_hlsl_entrypoint};
3820 if (!types::isHLSL(Id: InputType))
3821 return;
3822 for (const auto &Arg : ForwardedArguments)
3823 if (const auto *A = Args.getLastArg(Arg))
3824 A->renderAsInput(Args, CmdArgs);
3825 // Add the default headers if dxc_no_stdinc is not set.
3826 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3827 !Args.hasArg(options::OPT_nostdinc))
3828 CmdArgs.push_back(Elt: "-finclude-default-header");
3829}
3830
3831static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3832 ArgStringList &CmdArgs, types::ID InputType) {
3833 if (!Args.hasArg(options::OPT_fopenacc))
3834 return;
3835
3836 CmdArgs.push_back(Elt: "-fopenacc");
3837
3838 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3839 StringRef Value = A->getValue();
3840 int Version;
3841 if (!Value.getAsInteger(Radix: 10, Result&: Version))
3842 A->renderAsInput(Args, Output&: CmdArgs);
3843 else
3844 D.Diag(diag::err_drv_clang_unsupported) << Value;
3845 }
3846}
3847
3848static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3849 const ArgList &Args, ArgStringList &CmdArgs) {
3850 // -fbuiltin is default unless -mkernel is used.
3851 bool UseBuiltins =
3852 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3853 !Args.hasArg(options::OPT_mkernel));
3854 if (!UseBuiltins)
3855 CmdArgs.push_back(Elt: "-fno-builtin");
3856
3857 // -ffreestanding implies -fno-builtin.
3858 if (Args.hasArg(options::OPT_ffreestanding))
3859 UseBuiltins = false;
3860
3861 // Process the -fno-builtin-* options.
3862 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3863 A->claim();
3864
3865 // If -fno-builtin is specified, then there's no need to pass the option to
3866 // the frontend.
3867 if (UseBuiltins)
3868 A->render(Args, CmdArgs);
3869 }
3870}
3871
3872bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3873 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
3874 Twine Path{Str};
3875 Path.toVector(Out&: Result);
3876 return Path.getSingleStringRef() != "";
3877 }
3878 if (llvm::sys::path::cache_directory(result&: Result)) {
3879 llvm::sys::path::append(path&: Result, a: "clang");
3880 llvm::sys::path::append(path&: Result, a: "ModuleCache");
3881 return true;
3882 }
3883 return false;
3884}
3885
3886llvm::SmallString<256>
3887clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3888 const char *BaseInput) {
3889 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
3890 return StringRef(ModuleOutputEQ->getValue());
3891
3892 SmallString<256> OutputPath;
3893 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3894 FinalOutput && Args.hasArg(options::OPT_c))
3895 OutputPath = FinalOutput->getValue();
3896 else
3897 OutputPath = BaseInput;
3898
3899 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
3900 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
3901 return OutputPath;
3902}
3903
3904static bool RenderModulesOptions(Compilation &C, const Driver &D,
3905 const ArgList &Args, const InputInfo &Input,
3906 const InputInfo &Output, bool HaveStd20,
3907 ArgStringList &CmdArgs) {
3908 bool IsCXX = types::isCXX(Id: Input.getType());
3909 bool HaveStdCXXModules = IsCXX && HaveStd20;
3910 bool HaveModules = HaveStdCXXModules;
3911
3912 // -fmodules enables the use of precompiled modules (off by default).
3913 // Users can pass -fno-cxx-modules to turn off modules support for
3914 // C++/Objective-C++ programs.
3915 bool HaveClangModules = false;
3916 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3917 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3918 options::OPT_fno_cxx_modules, true);
3919 if (AllowedInCXX || !IsCXX) {
3920 CmdArgs.push_back(Elt: "-fmodules");
3921 HaveClangModules = true;
3922 }
3923 }
3924
3925 HaveModules |= HaveClangModules;
3926
3927 // -fmodule-maps enables implicit reading of module map files. By default,
3928 // this is enabled if we are using Clang's flavor of precompiled modules.
3929 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3930 options::OPT_fno_implicit_module_maps, HaveClangModules))
3931 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
3932
3933 // -fmodules-decluse checks that modules used are declared so (off by default)
3934 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3935 options::OPT_fno_modules_decluse);
3936
3937 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3938 // all #included headers are part of modules.
3939 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3940 options::OPT_fno_modules_strict_decluse, false))
3941 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
3942
3943 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
3944 options::OPT_fno_modulemap_allow_subdirectory_search);
3945
3946 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3947 bool ImplicitModules = false;
3948 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3949 options::OPT_fno_implicit_modules, HaveClangModules)) {
3950 if (HaveModules)
3951 CmdArgs.push_back(Elt: "-fno-implicit-modules");
3952 } else if (HaveModules) {
3953 ImplicitModules = true;
3954 // -fmodule-cache-path specifies where our implicitly-built module files
3955 // should be written.
3956 SmallString<128> Path;
3957 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3958 Path = A->getValue();
3959
3960 bool HasPath = true;
3961 if (C.isForDiagnostics()) {
3962 // When generating crash reports, we want to emit the modules along with
3963 // the reproduction sources, so we ignore any provided module path.
3964 Path = Output.getFilename();
3965 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
3966 llvm::sys::path::append(path&: Path, a: "modules");
3967 } else if (Path.empty()) {
3968 // No module path was provided: use the default.
3969 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
3970 }
3971
3972 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3973 // That being said, that failure is unlikely and not caching is harmless.
3974 if (HasPath) {
3975 const char Arg[] = "-fmodules-cache-path=";
3976 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
3977 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
3978 }
3979 }
3980
3981 if (HaveModules) {
3982 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3983 options::OPT_fno_prebuilt_implicit_modules, false))
3984 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
3985 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3986 options::OPT_fno_modules_validate_input_files_content,
3987 false))
3988 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
3989 }
3990
3991 // -fmodule-name specifies the module that is currently being built (or
3992 // used for header checking by -fmodule-maps).
3993 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3994
3995 // -fmodule-map-file can be used to specify files containing module
3996 // definitions.
3997 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3998
3999 // -fbuiltin-module-map can be used to load the clang
4000 // builtin headers modulemap file.
4001 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4002 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4003 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
4004 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
4005 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
4006 CmdArgs.push_back(
4007 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
4008 }
4009
4010 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4011 // names to precompiled module files (the module is loaded only if used).
4012 // The -fmodule-file=<file> form can be used to unconditionally load
4013 // precompiled module files (whether used or not).
4014 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4015 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4016
4017 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4018 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4019 CmdArgs.push_back(Args.MakeArgString(
4020 std::string("-fprebuilt-module-path=") + A->getValue()));
4021 A->claim();
4022 }
4023 } else
4024 Args.ClaimAllArgs(options::OPT_fmodule_file);
4025
4026 // When building modules and generating crashdumps, we need to dump a module
4027 // dependency VFS alongside the output.
4028 if (HaveClangModules && C.isForDiagnostics()) {
4029 SmallString<128> VFSDir(Output.getFilename());
4030 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
4031 // Add the cache directory as a temp so the crash diagnostics pick it up.
4032 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
4033
4034 llvm::sys::path::append(path&: VFSDir, a: "vfs");
4035 CmdArgs.push_back(Elt: "-module-dependency-dir");
4036 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
4037 }
4038
4039 if (HaveClangModules)
4040 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4041
4042 // Pass through all -fmodules-ignore-macro arguments.
4043 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4044 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4045 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4046
4047 if (HaveClangModules) {
4048 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4049
4050 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4051 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4052 D.Diag(diag::err_drv_argument_not_allowed_with)
4053 << A->getAsString(Args) << "-fbuild-session-timestamp";
4054
4055 llvm::sys::fs::file_status Status;
4056 if (llvm::sys::fs::status(A->getValue(), Status))
4057 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4058 CmdArgs.push_back(Elt: Args.MakeArgString(
4059 Str: "-fbuild-session-timestamp=" +
4060 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4061 d: Status.getLastModificationTime().time_since_epoch())
4062 .count())));
4063 }
4064
4065 if (Args.getLastArg(
4066 options::OPT_fmodules_validate_once_per_build_session)) {
4067 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4068 options::OPT_fbuild_session_file))
4069 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4070
4071 Args.AddLastArg(CmdArgs,
4072 options::OPT_fmodules_validate_once_per_build_session);
4073 }
4074
4075 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4076 options::OPT_fno_modules_validate_system_headers,
4077 ImplicitModules))
4078 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4079
4080 Args.AddLastArg(CmdArgs,
4081 options::OPT_fmodules_disable_diagnostic_validation);
4082 } else {
4083 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4084 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4085 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4086 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4087 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4088 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4089 }
4090
4091 // FIXME: We provisionally don't check ODR violations for decls in the global
4092 // module fragment.
4093 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4094
4095 if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
4096 (Input.getType() == driver::types::TY_CXXModule ||
4097 Input.getType() == driver::types::TY_PP_CXXModule)) {
4098 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4099
4100 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4101 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4102 else {
4103 if (Args.hasArg(options::OPT__precompile) &&
4104 (!Args.hasArg(options::OPT_o) ||
4105 Args.getLastArg(options::OPT_o)->getValue() ==
4106 getCXX20NamedModuleOutputPath(Args, Input.getBaseInput()))) {
4107 D.Diag(diag::err_drv_reduced_module_output_overrided);
4108 }
4109
4110 CmdArgs.push_back(Elt: Args.MakeArgString(
4111 Str: "-fmodule-output=" +
4112 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4113 }
4114 }
4115
4116 // Noop if we see '-fmodules-reduced-bmi' with other translation
4117 // units than module units. This is more user friendly to allow end uers to
4118 // enable this feature without asking for help from build systems.
4119 Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
4120
4121 // We need to include the case the input file is a module file here.
4122 // Since the default compilation model for C++ module interface unit will
4123 // create temporary module file and compile the temporary module file
4124 // to get the object file. Then the `-fmodule-output` flag will be
4125 // brought to the second compilation process. So we have to claim it for
4126 // the case too.
4127 if (Input.getType() == driver::types::TY_CXXModule ||
4128 Input.getType() == driver::types::TY_PP_CXXModule ||
4129 Input.getType() == driver::types::TY_ModuleFile) {
4130 Args.ClaimAllArgs(options::OPT_fmodule_output);
4131 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4132 }
4133
4134 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4135 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4136
4137 return HaveModules;
4138}
4139
4140static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4141 ArgStringList &CmdArgs) {
4142 // -fsigned-char is default.
4143 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4144 options::OPT_fno_signed_char,
4145 options::OPT_funsigned_char,
4146 options::OPT_fno_unsigned_char)) {
4147 if (A->getOption().matches(options::OPT_funsigned_char) ||
4148 A->getOption().matches(options::OPT_fno_signed_char)) {
4149 CmdArgs.push_back(Elt: "-fno-signed-char");
4150 }
4151 } else if (!isSignedCharDefault(Triple: T)) {
4152 CmdArgs.push_back(Elt: "-fno-signed-char");
4153 }
4154
4155 // The default depends on the language standard.
4156 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4157
4158 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4159 options::OPT_fno_short_wchar)) {
4160 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4161 CmdArgs.push_back(Elt: "-fwchar-type=short");
4162 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4163 } else {
4164 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4165 CmdArgs.push_back(Elt: "-fwchar-type=int");
4166 if (T.isOSzOS() ||
4167 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4168 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4169 else
4170 CmdArgs.push_back(Elt: "-fsigned-wchar");
4171 }
4172 } else if (T.isOSzOS())
4173 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4174}
4175
4176static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4177 const llvm::Triple &T, const ArgList &Args,
4178 ObjCRuntime &Runtime, bool InferCovariantReturns,
4179 const InputInfo &Input, ArgStringList &CmdArgs) {
4180 const llvm::Triple::ArchType Arch = TC.getArch();
4181
4182 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4183 // is the default. Except for deployment target of 10.5, next runtime is
4184 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4185 if (Runtime.isNonFragile()) {
4186 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4187 options::OPT_fno_objc_legacy_dispatch,
4188 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4189 if (TC.UseObjCMixedDispatch())
4190 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4191 else
4192 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4193 }
4194 }
4195
4196 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4197 // to do Array/Dictionary subscripting by default.
4198 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4199 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4200 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4201
4202 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4203 // NOTE: This logic is duplicated in ToolChains.cpp.
4204 if (isObjCAutoRefCount(Args)) {
4205 TC.CheckObjCARC();
4206
4207 CmdArgs.push_back(Elt: "-fobjc-arc");
4208
4209 // FIXME: It seems like this entire block, and several around it should be
4210 // wrapped in isObjC, but for now we just use it here as this is where it
4211 // was being used previously.
4212 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4213 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4214 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4215 else
4216 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4217 }
4218
4219 // Allow the user to enable full exceptions code emission.
4220 // We default off for Objective-C, on for Objective-C++.
4221 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4222 options::OPT_fno_objc_arc_exceptions,
4223 /*Default=*/types::isCXX(Input.getType())))
4224 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4225 }
4226
4227 // Silence warning for full exception code emission options when explicitly
4228 // set to use no ARC.
4229 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4230 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4231 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4232 }
4233
4234 // Allow the user to control whether messages can be converted to runtime
4235 // functions.
4236 if (types::isObjC(Id: Input.getType())) {
4237 auto *Arg = Args.getLastArg(
4238 options::OPT_fobjc_convert_messages_to_runtime_calls,
4239 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4240 if (Arg &&
4241 Arg->getOption().matches(
4242 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4243 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4244 }
4245
4246 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4247 // rewriter.
4248 if (InferCovariantReturns)
4249 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4250
4251 // Pass down -fobjc-weak or -fno-objc-weak if present.
4252 if (types::isObjC(Id: Input.getType())) {
4253 auto WeakArg =
4254 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4255 if (!WeakArg) {
4256 // nothing to do
4257 } else if (!Runtime.allowsWeak()) {
4258 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4259 D.Diag(diag::err_objc_weak_unsupported);
4260 } else {
4261 WeakArg->render(Args, CmdArgs);
4262 }
4263 }
4264
4265 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4266 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4267}
4268
4269static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4270 ArgStringList &CmdArgs) {
4271 bool CaretDefault = true;
4272 bool ColumnDefault = true;
4273
4274 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4275 options::OPT__SLASH_diagnostics_column,
4276 options::OPT__SLASH_diagnostics_caret)) {
4277 switch (A->getOption().getID()) {
4278 case options::OPT__SLASH_diagnostics_caret:
4279 CaretDefault = true;
4280 ColumnDefault = true;
4281 break;
4282 case options::OPT__SLASH_diagnostics_column:
4283 CaretDefault = false;
4284 ColumnDefault = true;
4285 break;
4286 case options::OPT__SLASH_diagnostics_classic:
4287 CaretDefault = false;
4288 ColumnDefault = false;
4289 break;
4290 }
4291 }
4292
4293 // -fcaret-diagnostics is default.
4294 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4295 options::OPT_fno_caret_diagnostics, CaretDefault))
4296 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4297
4298 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4299 options::OPT_fno_diagnostics_fixit_info);
4300 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4301 options::OPT_fno_diagnostics_show_option);
4302
4303 if (const Arg *A =
4304 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4305 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4306 CmdArgs.push_back(Elt: A->getValue());
4307 }
4308
4309 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4310 options::OPT_fno_diagnostics_show_hotness);
4311
4312 if (const Arg *A =
4313 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4314 std::string Opt =
4315 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4316 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4317 }
4318
4319 if (const Arg *A =
4320 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4321 std::string Opt =
4322 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4323 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4324 }
4325
4326 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4327 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4328 CmdArgs.push_back(Elt: A->getValue());
4329 if (StringRef(A->getValue()) == "sarif" ||
4330 StringRef(A->getValue()) == "SARIF")
4331 D.Diag(diag::warn_drv_sarif_format_unstable);
4332 }
4333
4334 if (const Arg *A = Args.getLastArg(
4335 options::OPT_fdiagnostics_show_note_include_stack,
4336 options::OPT_fno_diagnostics_show_note_include_stack)) {
4337 const Option &O = A->getOption();
4338 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4339 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4340 else
4341 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4342 }
4343
4344 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4345
4346 if (Args.hasArg(options::OPT_fansi_escape_codes))
4347 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4348
4349 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4350 options::OPT_fno_show_source_location);
4351
4352 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4353 options::OPT_fno_diagnostics_show_line_numbers);
4354
4355 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4356 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4357
4358 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4359 ColumnDefault))
4360 CmdArgs.push_back(Elt: "-fno-show-column");
4361
4362 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4363 options::OPT_fno_spell_checking);
4364
4365 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4366}
4367
4368DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4369 const ArgList &Args, Arg *&Arg) {
4370 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4371 options::OPT_gno_split_dwarf);
4372 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4373 return DwarfFissionKind::None;
4374
4375 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4376 return DwarfFissionKind::Split;
4377
4378 StringRef Value = Arg->getValue();
4379 if (Value == "split")
4380 return DwarfFissionKind::Split;
4381 if (Value == "single")
4382 return DwarfFissionKind::Single;
4383
4384 D.Diag(diag::err_drv_unsupported_option_argument)
4385 << Arg->getSpelling() << Arg->getValue();
4386 return DwarfFissionKind::None;
4387}
4388
4389static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4390 const ArgList &Args, ArgStringList &CmdArgs,
4391 unsigned DwarfVersion) {
4392 auto *DwarfFormatArg =
4393 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4394 if (!DwarfFormatArg)
4395 return;
4396
4397 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4398 if (DwarfVersion < 3)
4399 D.Diag(diag::err_drv_argument_only_allowed_with)
4400 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4401 else if (!T.isArch64Bit())
4402 D.Diag(diag::err_drv_argument_only_allowed_with)
4403 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4404 else if (!T.isOSBinFormatELF())
4405 D.Diag(diag::err_drv_argument_only_allowed_with)
4406 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4407 }
4408
4409 DwarfFormatArg->render(Args, CmdArgs);
4410}
4411
4412static void
4413renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4414 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4415 const InputInfo &Output,
4416 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4417 DwarfFissionKind &DwarfFission) {
4418 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4419 options::OPT_fno_debug_info_for_profiling, false) &&
4420 checkDebugInfoOption(
4421 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4422 CmdArgs.push_back(Elt: "-fdebug-info-for-profiling");
4423
4424 // The 'g' groups options involve a somewhat intricate sequence of decisions
4425 // about what to pass from the driver to the frontend, but by the time they
4426 // reach cc1 they've been factored into three well-defined orthogonal choices:
4427 // * what level of debug info to generate
4428 // * what dwarf version to write
4429 // * what debugger tuning to use
4430 // This avoids having to monkey around further in cc1 other than to disable
4431 // codeview if not running in a Windows environment. Perhaps even that
4432 // decision should be made in the driver as well though.
4433 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4434
4435 bool SplitDWARFInlining =
4436 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4437 options::OPT_fno_split_dwarf_inlining, false);
4438
4439 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4440 // object file generation and no IR generation, -gN should not be needed. So
4441 // allow -gsplit-dwarf with either -gN or IR input.
4442 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4443 Arg *SplitDWARFArg;
4444 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4445 if (DwarfFission != DwarfFissionKind::None &&
4446 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4447 DwarfFission = DwarfFissionKind::None;
4448 SplitDWARFInlining = false;
4449 }
4450 }
4451 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4452 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4453
4454 // If the last option explicitly specified a debug-info level, use it.
4455 if (checkDebugInfoOption(A, Args, D, TC) &&
4456 A->getOption().matches(options::OPT_gN_Group)) {
4457 DebugInfoKind = debugLevelToInfoKind(A: *A);
4458 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4459 // complicated if you've disabled inline info in the skeleton CUs
4460 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4461 // line-tables-only, so let those compose naturally in that case.
4462 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4463 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4464 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4465 SplitDWARFInlining))
4466 DwarfFission = DwarfFissionKind::None;
4467 }
4468 }
4469
4470 // If a debugger tuning argument appeared, remember it.
4471 bool HasDebuggerTuning = false;
4472 if (const Arg *A =
4473 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4474 HasDebuggerTuning = true;
4475 if (checkDebugInfoOption(A, Args, D, TC)) {
4476 if (A->getOption().matches(options::OPT_glldb))
4477 DebuggerTuning = llvm::DebuggerKind::LLDB;
4478 else if (A->getOption().matches(options::OPT_gsce))
4479 DebuggerTuning = llvm::DebuggerKind::SCE;
4480 else if (A->getOption().matches(options::OPT_gdbx))
4481 DebuggerTuning = llvm::DebuggerKind::DBX;
4482 else
4483 DebuggerTuning = llvm::DebuggerKind::GDB;
4484 }
4485 }
4486
4487 // If a -gdwarf argument appeared, remember it.
4488 bool EmitDwarf = false;
4489 if (const Arg *A = getDwarfNArg(Args))
4490 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4491
4492 bool EmitCodeView = false;
4493 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4494 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4495
4496 // If the user asked for debug info but did not explicitly specify -gcodeview
4497 // or -gdwarf, ask the toolchain for the default format.
4498 if (!EmitCodeView && !EmitDwarf &&
4499 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4500 switch (TC.getDefaultDebugFormat()) {
4501 case llvm::codegenoptions::DIF_CodeView:
4502 EmitCodeView = true;
4503 break;
4504 case llvm::codegenoptions::DIF_DWARF:
4505 EmitDwarf = true;
4506 break;
4507 }
4508 }
4509
4510 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4511 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4512 // be lower than what the user wanted.
4513 if (EmitDwarf) {
4514 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4515 // Clamp effective DWARF version to the max supported by the toolchain.
4516 EffectiveDWARFVersion =
4517 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4518 } else {
4519 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4520 }
4521
4522 // -gline-directives-only supported only for the DWARF debug info.
4523 if (RequestedDWARFVersion == 0 &&
4524 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4525 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4526
4527 // strict DWARF is set to false by default. But for DBX, we need it to be set
4528 // as true by default.
4529 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4530 (void)checkDebugInfoOption(A, Args, D, TC);
4531 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4532 DebuggerTuning == llvm::DebuggerKind::DBX))
4533 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4534
4535 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4536 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4537
4538 // Column info is included by default for everything except SCE and
4539 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4540 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4541 // practice, however, the Microsoft debuggers don't handle missing end columns
4542 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4543 // it's better not to include any column info.
4544 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4545 (void)checkDebugInfoOption(A, Args, D, TC);
4546 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4547 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4548 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4549 DebuggerTuning != llvm::DebuggerKind::DBX)))
4550 CmdArgs.push_back(Elt: "-gno-column-info");
4551
4552 // FIXME: Move backend command line options to the module.
4553 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4554 // If -gline-tables-only or -gline-directives-only is the last option it
4555 // wins.
4556 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4557 TC)) {
4558 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4559 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4560 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4561 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4562 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4563 }
4564 }
4565 }
4566
4567 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4568 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4569
4570 // After we've dealt with all combinations of things that could
4571 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4572 // figure out if we need to "upgrade" it to standalone debug info.
4573 // We parse these two '-f' options whether or not they will be used,
4574 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4575 bool NeedFullDebug = Args.hasFlag(
4576 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4577 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4578 TC.GetDefaultStandaloneDebug());
4579 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4580 (void)checkDebugInfoOption(A, Args, D, TC);
4581
4582 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4583 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4584 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4585 options::OPT_feliminate_unused_debug_types, false))
4586 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4587 else if (NeedFullDebug)
4588 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4589 }
4590
4591 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4592 false)) {
4593 // Source embedding is a vendor extension to DWARF v5. By now we have
4594 // checked if a DWARF version was stated explicitly, and have otherwise
4595 // fallen back to the target default, so if this is still not at least 5
4596 // we emit an error.
4597 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4598 if (RequestedDWARFVersion < 5)
4599 D.Diag(diag::err_drv_argument_only_allowed_with)
4600 << A->getAsString(Args) << "-gdwarf-5";
4601 else if (EffectiveDWARFVersion < 5)
4602 // The toolchain has reduced allowed dwarf version, so we can't enable
4603 // -gembed-source.
4604 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4605 << A->getAsString(Args) << TC.getTripleString() << 5
4606 << EffectiveDWARFVersion;
4607 else if (checkDebugInfoOption(A, Args, D, TC))
4608 CmdArgs.push_back(Elt: "-gembed-source");
4609 }
4610
4611 if (Args.hasFlag(options::OPT_gkey_instructions,
4612 options::OPT_gno_key_instructions, false)) {
4613 CmdArgs.push_back(Elt: "-gkey-instructions");
4614 CmdArgs.push_back(Elt: "-mllvm");
4615 CmdArgs.push_back(Elt: "-dwarf-use-key-instructions");
4616 }
4617
4618 if (EmitCodeView) {
4619 CmdArgs.push_back(Elt: "-gcodeview");
4620
4621 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4622 options::OPT_gno_codeview_ghash);
4623
4624 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4625 options::OPT_gno_codeview_command_line);
4626 }
4627
4628 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4629 options::OPT_gno_inline_line_tables);
4630
4631 // When emitting remarks, we need at least debug lines in the output.
4632 if (willEmitRemarks(Args) &&
4633 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4634 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4635
4636 // Adjust the debug info kind for the given toolchain.
4637 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4638
4639 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4640 // set.
4641 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4642 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4643 ? llvm::DebuggerKind::Default
4644 : DebuggerTuning);
4645
4646 // -fdebug-macro turns on macro debug info generation.
4647 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4648 false))
4649 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4650 D, TC))
4651 CmdArgs.push_back(Elt: "-debug-info-macro");
4652
4653 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4654 const auto *PubnamesArg =
4655 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4656 options::OPT_gpubnames, options::OPT_gno_pubnames);
4657 if (DwarfFission != DwarfFissionKind::None ||
4658 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4659 const bool OptionSet =
4660 (PubnamesArg &&
4661 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4662 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4663 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4664 (!PubnamesArg ||
4665 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4666 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4667 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4668 options::OPT_gpubnames)
4669 ? "-gpubnames"
4670 : "-ggnu-pubnames");
4671 }
4672 const auto *SimpleTemplateNamesArg =
4673 Args.getLastArg(options::OPT_gsimple_template_names,
4674 options::OPT_gno_simple_template_names);
4675 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4676 if (SimpleTemplateNamesArg &&
4677 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4678 const auto &Opt = SimpleTemplateNamesArg->getOption();
4679 if (Opt.matches(options::OPT_gsimple_template_names)) {
4680 ForwardTemplateParams = true;
4681 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4682 }
4683 }
4684
4685 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4686 bool UseDebugTemplateAlias =
4687 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4688 if (const auto *DebugTemplateAlias = Args.getLastArg(
4689 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4690 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4691 // asks for it we should let them have it (if the target supports it).
4692 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4693 const auto &Opt = DebugTemplateAlias->getOption();
4694 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4695 }
4696 }
4697 if (UseDebugTemplateAlias)
4698 CmdArgs.push_back(Elt: "-gtemplate-alias");
4699
4700 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4701 StringRef v = A->getValue();
4702 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4703 }
4704
4705 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4706 options::OPT_fno_debug_ranges_base_address);
4707
4708 // -gdwarf-aranges turns on the emission of the aranges section in the
4709 // backend.
4710 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4711 A && checkDebugInfoOption(A, Args, D, TC)) {
4712 CmdArgs.push_back(Elt: "-mllvm");
4713 CmdArgs.push_back(Elt: "-generate-arange-section");
4714 }
4715
4716 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4717 options::OPT_fno_force_dwarf_frame);
4718
4719 bool EnableTypeUnits = false;
4720 if (Args.hasFlag(options::OPT_fdebug_types_section,
4721 options::OPT_fno_debug_types_section, false)) {
4722 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4723 D.Diag(diag::err_drv_unsupported_opt_for_target)
4724 << Args.getLastArg(options::OPT_fdebug_types_section)
4725 ->getAsString(Args)
4726 << T.getTriple();
4727 } else if (checkDebugInfoOption(
4728 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4729 TC)) {
4730 EnableTypeUnits = true;
4731 CmdArgs.push_back(Elt: "-mllvm");
4732 CmdArgs.push_back(Elt: "-generate-type-units");
4733 }
4734 }
4735
4736 if (const Arg *A =
4737 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4738 options::OPT_gno_omit_unreferenced_methods))
4739 (void)checkDebugInfoOption(A, Args, D, TC);
4740 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4741 options::OPT_gno_omit_unreferenced_methods, false) &&
4742 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4743 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4744 !EnableTypeUnits) {
4745 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
4746 }
4747
4748 // To avoid join/split of directory+filename, the integrated assembler prefers
4749 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4750 // form before DWARF v5.
4751 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4752 options::OPT_fno_dwarf_directory_asm,
4753 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4754 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
4755
4756 // Decide how to render forward declarations of template instantiations.
4757 // SCE wants full descriptions, others just get them in the name.
4758 if (ForwardTemplateParams)
4759 CmdArgs.push_back(Elt: "-debug-forward-template-params");
4760
4761 // Do we need to explicitly import anonymous namespaces into the parent
4762 // scope?
4763 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4764 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
4765
4766 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
4767 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4768
4769 // This controls whether or not we perform JustMyCode instrumentation.
4770 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4771 if (TC.getTriple().isOSBinFormatELF() ||
4772 TC.getTriple().isWindowsMSVCEnvironment()) {
4773 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4774 CmdArgs.push_back(Elt: "-fjmc");
4775 else if (D.IsCLMode())
4776 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4777 << "'/Zi', '/Z7'";
4778 else
4779 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4780 << "-g";
4781 } else {
4782 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4783 }
4784 }
4785
4786 // Add in -fdebug-compilation-dir if necessary.
4787 const char *DebugCompilationDir =
4788 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
4789
4790 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4791
4792 // Add the output path to the object file for CodeView debug infos.
4793 if (EmitCodeView && Output.isFilename())
4794 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4795 OutputFileName: Output.getFilename());
4796}
4797
4798static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4799 ArgStringList &CmdArgs) {
4800 unsigned RTOptionID = options::OPT__SLASH_MT;
4801
4802 if (Args.hasArg(options::OPT__SLASH_LDd))
4803 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4804 // but defining _DEBUG is sticky.
4805 RTOptionID = options::OPT__SLASH_MTd;
4806
4807 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4808 RTOptionID = A->getOption().getID();
4809
4810 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4811 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4812 .Case("static", options::OPT__SLASH_MT)
4813 .Case("static_dbg", options::OPT__SLASH_MTd)
4814 .Case("dll", options::OPT__SLASH_MD)
4815 .Case("dll_dbg", options::OPT__SLASH_MDd)
4816 .Default(options::OPT__SLASH_MT);
4817 }
4818
4819 StringRef FlagForCRT;
4820 switch (RTOptionID) {
4821 case options::OPT__SLASH_MD:
4822 if (Args.hasArg(options::OPT__SLASH_LDd))
4823 CmdArgs.push_back(Elt: "-D_DEBUG");
4824 CmdArgs.push_back(Elt: "-D_MT");
4825 CmdArgs.push_back(Elt: "-D_DLL");
4826 FlagForCRT = "--dependent-lib=msvcrt";
4827 break;
4828 case options::OPT__SLASH_MDd:
4829 CmdArgs.push_back(Elt: "-D_DEBUG");
4830 CmdArgs.push_back(Elt: "-D_MT");
4831 CmdArgs.push_back(Elt: "-D_DLL");
4832 FlagForCRT = "--dependent-lib=msvcrtd";
4833 break;
4834 case options::OPT__SLASH_MT:
4835 if (Args.hasArg(options::OPT__SLASH_LDd))
4836 CmdArgs.push_back(Elt: "-D_DEBUG");
4837 CmdArgs.push_back(Elt: "-D_MT");
4838 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4839 FlagForCRT = "--dependent-lib=libcmt";
4840 break;
4841 case options::OPT__SLASH_MTd:
4842 CmdArgs.push_back(Elt: "-D_DEBUG");
4843 CmdArgs.push_back(Elt: "-D_MT");
4844 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4845 FlagForCRT = "--dependent-lib=libcmtd";
4846 break;
4847 default:
4848 llvm_unreachable("Unexpected option ID.");
4849 }
4850
4851 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4852 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
4853 } else {
4854 CmdArgs.push_back(Elt: FlagForCRT.data());
4855
4856 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4857 // users want. The /Za flag to cl.exe turns this off, but it's not
4858 // implemented in clang.
4859 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
4860 }
4861
4862 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4863 // even if the file doesn't actually refer to any of the routines because
4864 // the CRT itself has incomplete dependency markings.
4865 if (TC.getTriple().isWindowsArm64EC())
4866 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
4867}
4868
4869void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4870 const InputInfo &Output, const InputInfoList &Inputs,
4871 const ArgList &Args, const char *LinkingOutput) const {
4872 const auto &TC = getToolChain();
4873 const llvm::Triple &RawTriple = TC.getTriple();
4874 const llvm::Triple &Triple = TC.getEffectiveTriple();
4875 const std::string &TripleStr = Triple.getTriple();
4876
4877 bool KernelOrKext =
4878 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4879 const Driver &D = TC.getDriver();
4880 ArgStringList CmdArgs;
4881
4882 assert(Inputs.size() >= 1 && "Must have at least one input.");
4883 // CUDA/HIP compilation may have multiple inputs (source file + results of
4884 // device-side compilations). OpenMP device jobs also take the host IR as a
4885 // second input. Module precompilation accepts a list of header files to
4886 // include as part of the module. API extraction accepts a list of header
4887 // files whose API information is emitted in the output. All other jobs are
4888 // expected to have exactly one input. SYCL compilation only expects a
4889 // single input.
4890 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
4891 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
4892 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
4893 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
4894 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
4895 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
4896 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
4897 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
4898 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
4899 JA.isDeviceOffloading(OKind: Action::OFK_Host));
4900 bool IsHostOffloadingAction =
4901 JA.isHostOffloading(Action::OFK_OpenMP) ||
4902 JA.isHostOffloading(Action::OFK_SYCL) ||
4903 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4904 Args.hasFlag(options::OPT_offload_new_driver,
4905 options::OPT_no_offload_new_driver,
4906 C.isOffloadingHostKind(Action::OFK_Cuda)));
4907
4908 bool IsRDCMode =
4909 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4910
4911 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4912 bool IsUsingLTO = LTOMode != LTOK_None;
4913
4914 // Extract API doesn't have a main input file, so invent a fake one as a
4915 // placeholder.
4916 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4917 "extract-api");
4918
4919 const InputInfo &Input =
4920 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4921
4922 InputInfoList ExtractAPIInputs;
4923 InputInfoList HostOffloadingInputs;
4924 const InputInfo *CudaDeviceInput = nullptr;
4925 const InputInfo *OpenMPDeviceInput = nullptr;
4926 for (const InputInfo &I : Inputs) {
4927 if (&I == &Input || I.getType() == types::TY_Nothing) {
4928 // This is the primary input or contains nothing.
4929 } else if (IsExtractAPI) {
4930 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4931 if (I.getType() != ExpectedInputType) {
4932 D.Diag(diag::err_drv_extract_api_wrong_kind)
4933 << I.getFilename() << types::getTypeName(I.getType())
4934 << types::getTypeName(ExpectedInputType);
4935 }
4936 ExtractAPIInputs.push_back(Elt: I);
4937 } else if (IsHostOffloadingAction) {
4938 HostOffloadingInputs.push_back(Elt: I);
4939 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4940 CudaDeviceInput = &I;
4941 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4942 OpenMPDeviceInput = &I;
4943 } else {
4944 llvm_unreachable("unexpectedly given multiple inputs");
4945 }
4946 }
4947
4948 const llvm::Triple *AuxTriple =
4949 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4950 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4951 bool IsUEFI = RawTriple.isUEFI();
4952 bool IsIAMCU = RawTriple.isOSIAMCU();
4953
4954 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
4955 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4956 // Windows), we need to pass Windows-specific flags to cc1.
4957 if (IsCuda || IsHIP || IsSYCL)
4958 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4959
4960 // C++ is not supported for IAMCU.
4961 if (IsIAMCU && types::isCXX(Input.getType()))
4962 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4963
4964 // Invoke ourselves in -cc1 mode.
4965 //
4966 // FIXME: Implement custom jobs for internal actions.
4967 CmdArgs.push_back(Elt: "-cc1");
4968
4969 // Add the "effective" target triple.
4970 CmdArgs.push_back(Elt: "-triple");
4971 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
4972
4973 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4974 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
4975 Args.ClaimAllArgs(options::OPT_MJ);
4976 } else if (const Arg *GenCDBFragment =
4977 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4978 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
4979 Target: TripleStr, Output, Input, Args);
4980 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4981 }
4982
4983 if (IsCuda || IsHIP) {
4984 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4985 // and vice-versa.
4986 std::string NormalizedTriple;
4987 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
4988 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
4989 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4990 ->getTriple()
4991 .normalize();
4992 else {
4993 // Host-side compilation.
4994 NormalizedTriple =
4995 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4996 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4997 ->getTriple()
4998 .normalize();
4999 if (IsCuda) {
5000 // We need to figure out which CUDA version we're compiling for, as that
5001 // determines how we load and launch GPU kernels.
5002 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5003 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5004 assert(CTC && "Expected valid CUDA Toolchain.");
5005 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5006 CmdArgs.push_back(Elt: Args.MakeArgString(
5007 Str: Twine("-target-sdk-version=") +
5008 CudaVersionToString(V: CTC->CudaInstallation.version())));
5009 // Unsized function arguments used for variadics were introduced in
5010 // CUDA-9.0. We still do not support generating code that actually uses
5011 // variadic arguments yet, but we do need to allow parsing them as
5012 // recent CUDA headers rely on that.
5013 // https://github.com/llvm/llvm-project/issues/58410
5014 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
5015 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
5016 }
5017 }
5018 CmdArgs.push_back(Elt: "-aux-triple");
5019 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5020
5021 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
5022 (getToolChain().getTriple().isAMDGPU() ||
5023 (getToolChain().getTriple().isSPIRV() &&
5024 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5025 // Device side compilation printf
5026 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5027 CmdArgs.push_back(Args.MakeArgString(
5028 "-mprintf-kind=" +
5029 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5030 // Force compiler error on invalid conversion specifiers
5031 CmdArgs.push_back(
5032 Elt: Args.MakeArgString(Str: "-Werror=format-invalid-specifier"));
5033 }
5034 }
5035 }
5036
5037 // Optimization level for CodeGen.
5038 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5039 if (A->getOption().matches(options::OPT_O4)) {
5040 CmdArgs.push_back(Elt: "-O3");
5041 D.Diag(diag::warn_O4_is_O3);
5042 } else {
5043 A->render(Args, Output&: CmdArgs);
5044 }
5045 }
5046
5047 // Unconditionally claim the printf option now to avoid unused diagnostic.
5048 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5049 PF->claim();
5050
5051 if (IsSYCL) {
5052 if (IsSYCLDevice) {
5053 // Host triple is needed when doing SYCL device compilations.
5054 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5055 std::string NormalizedTriple = AuxT.normalize();
5056 CmdArgs.push_back(Elt: "-aux-triple");
5057 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5058
5059 // We want to compile sycl kernels.
5060 CmdArgs.push_back(Elt: "-fsycl-is-device");
5061
5062 // Set O2 optimization level by default
5063 if (!Args.getLastArg(options::OPT_O_Group))
5064 CmdArgs.push_back(Elt: "-O2");
5065 } else {
5066 // Add any options that are needed specific to SYCL offload while
5067 // performing the host side compilation.
5068
5069 // Let the front-end host compilation flow know about SYCL offload
5070 // compilation.
5071 CmdArgs.push_back(Elt: "-fsycl-is-host");
5072 }
5073
5074 // Set options for both host and device.
5075 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5076 if (SYCLStdArg) {
5077 SYCLStdArg->render(Args, Output&: CmdArgs);
5078 } else {
5079 // Ensure the default version in SYCL mode is 2020.
5080 CmdArgs.push_back(Elt: "-sycl-std=2020");
5081 }
5082 }
5083
5084 if (Args.hasArg(options::OPT_fclangir))
5085 CmdArgs.push_back(Elt: "-fclangir");
5086
5087 if (IsOpenMPDevice) {
5088 // We have to pass the triple of the host if compiling for an OpenMP device.
5089 std::string NormalizedTriple =
5090 C.getSingleOffloadToolChain<Action::OFK_Host>()
5091 ->getTriple()
5092 .normalize();
5093 CmdArgs.push_back(Elt: "-aux-triple");
5094 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5095 }
5096
5097 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5098 Triple.getArch() == llvm::Triple::thumb)) {
5099 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5100 unsigned Version = 0;
5101 bool Failure =
5102 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5103 if (Failure || Version < 7)
5104 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5105 << TripleStr;
5106 }
5107
5108 // Push all default warning arguments that are specific to
5109 // the given target. These come before user provided warning options
5110 // are provided.
5111 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5112
5113 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5114 if (Triple.isSPIR() || Triple.isSPIRV())
5115 CmdArgs.push_back(Elt: "-Wspir-compat");
5116
5117 // Select the appropriate action.
5118 RewriteKind rewriteKind = RK_None;
5119
5120 bool UnifiedLTO = false;
5121 if (IsUsingLTO) {
5122 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5123 options::OPT_fno_unified_lto, Triple.isPS());
5124 if (UnifiedLTO)
5125 CmdArgs.push_back(Elt: "-funified-lto");
5126 }
5127
5128 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5129 // it claims when not running an assembler. Otherwise, clang would emit
5130 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5131 // flags while debugging something. That'd be somewhat inconvenient, and it's
5132 // also inconsistent with most other flags -- we don't warn on
5133 // -ffunction-sections not being used in -E mode either for example, even
5134 // though it's not really used either.
5135 if (!isa<AssembleJobAction>(Val: JA)) {
5136 // The args claimed here should match the args used in
5137 // CollectArgsForIntegratedAssembler().
5138 if (TC.useIntegratedAs()) {
5139 Args.ClaimAllArgs(options::OPT_mrelax_all);
5140 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5141 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5142 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5143 switch (C.getDefaultToolChain().getArch()) {
5144 case llvm::Triple::arm:
5145 case llvm::Triple::armeb:
5146 case llvm::Triple::thumb:
5147 case llvm::Triple::thumbeb:
5148 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5149 break;
5150 default:
5151 break;
5152 }
5153 }
5154 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5155 Args.ClaimAllArgs(options::OPT_Xassembler);
5156 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5157 }
5158
5159 if (isa<AnalyzeJobAction>(Val: JA)) {
5160 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5161 CmdArgs.push_back(Elt: "-analyze");
5162 } else if (isa<PreprocessJobAction>(Val: JA)) {
5163 if (Output.getType() == types::TY_Dependencies)
5164 CmdArgs.push_back(Elt: "-Eonly");
5165 else {
5166 CmdArgs.push_back(Elt: "-E");
5167 if (Args.hasArg(options::OPT_rewrite_objc) &&
5168 !Args.hasArg(options::OPT_g_Group))
5169 CmdArgs.push_back(Elt: "-P");
5170 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5171 CmdArgs.push_back(Elt: "-fdirectives-only");
5172 }
5173 } else if (isa<AssembleJobAction>(Val: JA)) {
5174 CmdArgs.push_back(Elt: "-emit-obj");
5175
5176 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5177
5178 // Also ignore explicit -force_cpusubtype_ALL option.
5179 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5180 } else if (isa<PrecompileJobAction>(Val: JA)) {
5181 if (JA.getType() == types::TY_Nothing)
5182 CmdArgs.push_back(Elt: "-fsyntax-only");
5183 else if (JA.getType() == types::TY_ModuleFile)
5184 CmdArgs.push_back(Elt: "-emit-module-interface");
5185 else if (JA.getType() == types::TY_HeaderUnit)
5186 CmdArgs.push_back(Elt: "-emit-header-unit");
5187 else
5188 CmdArgs.push_back(Elt: "-emit-pch");
5189 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5190 CmdArgs.push_back(Elt: "-verify-pch");
5191 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5192 assert(JA.getType() == types::TY_API_INFO &&
5193 "Extract API actions must generate a API information.");
5194 CmdArgs.push_back(Elt: "-extract-api");
5195
5196 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5197 PrettySGFArg->render(Args, Output&: CmdArgs);
5198
5199 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5200
5201 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5202 ProductNameArg->render(Args, Output&: CmdArgs);
5203 if (Arg *ExtractAPIIgnoresFileArg =
5204 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5205 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5206 if (Arg *EmitExtensionSymbolGraphs =
5207 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5208 if (!SymbolGraphDirArg)
5209 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5210
5211 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5212 }
5213 if (SymbolGraphDirArg)
5214 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5215 } else {
5216 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5217 "Invalid action for clang tool.");
5218 if (JA.getType() == types::TY_Nothing) {
5219 CmdArgs.push_back(Elt: "-fsyntax-only");
5220 } else if (JA.getType() == types::TY_LLVM_IR ||
5221 JA.getType() == types::TY_LTO_IR) {
5222 CmdArgs.push_back(Elt: "-emit-llvm");
5223 } else if (JA.getType() == types::TY_LLVM_BC ||
5224 JA.getType() == types::TY_LTO_BC) {
5225 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5226 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5227 Args.hasArg(options::OPT_emit_llvm)) {
5228 CmdArgs.push_back(Elt: "-emit-llvm");
5229 } else {
5230 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5231 }
5232 } else if (JA.getType() == types::TY_IFS ||
5233 JA.getType() == types::TY_IFS_CPP) {
5234 StringRef ArgStr =
5235 Args.hasArg(options::OPT_interface_stub_version_EQ)
5236 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5237 : "ifs-v1";
5238 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5239 CmdArgs.push_back(
5240 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr.str()));
5241 } else if (JA.getType() == types::TY_PP_Asm) {
5242 CmdArgs.push_back(Elt: "-S");
5243 } else if (JA.getType() == types::TY_AST) {
5244 CmdArgs.push_back(Elt: "-emit-pch");
5245 } else if (JA.getType() == types::TY_ModuleFile) {
5246 CmdArgs.push_back(Elt: "-module-file-info");
5247 } else if (JA.getType() == types::TY_RewrittenObjC) {
5248 CmdArgs.push_back(Elt: "-rewrite-objc");
5249 rewriteKind = RK_NonFragile;
5250 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5251 CmdArgs.push_back(Elt: "-rewrite-objc");
5252 rewriteKind = RK_Fragile;
5253 } else if (JA.getType() == types::TY_CIR) {
5254 CmdArgs.push_back(Elt: "-emit-cir");
5255 } else {
5256 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5257 }
5258
5259 // Preserve use-list order by default when emitting bitcode, so that
5260 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5261 // same result as running passes here. For LTO, we don't need to preserve
5262 // the use-list order, since serialization to bitcode is part of the flow.
5263 if (JA.getType() == types::TY_LLVM_BC)
5264 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5265
5266 if (IsUsingLTO) {
5267 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5268 !Args.hasFlag(options::OPT_offload_new_driver,
5269 options::OPT_no_offload_new_driver,
5270 C.isOffloadingHostKind(Action::OFK_Cuda)) &&
5271 !Triple.isAMDGPU()) {
5272 D.Diag(diag::err_drv_unsupported_opt_for_target)
5273 << Args.getLastArg(options::OPT_foffload_lto,
5274 options::OPT_foffload_lto_EQ)
5275 ->getAsString(Args)
5276 << Triple.getTriple();
5277 } else if (Triple.isNVPTX() && !IsRDCMode &&
5278 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5279 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5280 << Args.getLastArg(options::OPT_foffload_lto,
5281 options::OPT_foffload_lto_EQ)
5282 ->getAsString(Args)
5283 << "-fno-gpu-rdc";
5284 } else {
5285 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5286 CmdArgs.push_back(Elt: Args.MakeArgString(
5287 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5288 // PS4 uses the legacy LTO API, which does not support some of the
5289 // features enabled by -flto-unit.
5290 if (!RawTriple.isPS4() ||
5291 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5292 CmdArgs.push_back(Elt: "-flto-unit");
5293 }
5294 }
5295 }
5296
5297 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5298
5299 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5300 if (!types::isLLVMIR(Input.getType()))
5301 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5302 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5303 }
5304
5305 if (Triple.isPPC())
5306 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5307 options::OPT_mno_regnames);
5308
5309 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5310 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5311
5312 if (Args.getLastArg(options::OPT_save_temps_EQ))
5313 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5314
5315 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5316 options::OPT_fmemory_profile_EQ,
5317 options::OPT_fno_memory_profile);
5318 if (MemProfArg &&
5319 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5320 MemProfArg->render(Args, CmdArgs);
5321
5322 if (auto *MemProfUseArg =
5323 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5324 if (MemProfArg)
5325 D.Diag(diag::err_drv_argument_not_allowed_with)
5326 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5327 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5328 options::OPT_fprofile_generate_EQ))
5329 D.Diag(diag::err_drv_argument_not_allowed_with)
5330 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5331 MemProfUseArg->render(Args, CmdArgs);
5332 }
5333
5334 // Embed-bitcode option.
5335 // Only white-listed flags below are allowed to be embedded.
5336 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5337 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5338 // Add flags implied by -fembed-bitcode.
5339 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5340 // Disable all llvm IR level optimizations.
5341 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5342
5343 // Render target options.
5344 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
5345
5346 // reject options that shouldn't be supported in bitcode
5347 // also reject kernel/kext
5348 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5349 options::OPT_mkernel,
5350 options::OPT_fapple_kext,
5351 options::OPT_ffunction_sections,
5352 options::OPT_fno_function_sections,
5353 options::OPT_fdata_sections,
5354 options::OPT_fno_data_sections,
5355 options::OPT_fbasic_block_sections_EQ,
5356 options::OPT_funique_internal_linkage_names,
5357 options::OPT_fno_unique_internal_linkage_names,
5358 options::OPT_funique_section_names,
5359 options::OPT_fno_unique_section_names,
5360 options::OPT_funique_basic_block_section_names,
5361 options::OPT_fno_unique_basic_block_section_names,
5362 options::OPT_mrestrict_it,
5363 options::OPT_mno_restrict_it,
5364 options::OPT_mstackrealign,
5365 options::OPT_mno_stackrealign,
5366 options::OPT_mstack_alignment,
5367 options::OPT_mcmodel_EQ,
5368 options::OPT_mlong_calls,
5369 options::OPT_mno_long_calls,
5370 options::OPT_ggnu_pubnames,
5371 options::OPT_gdwarf_aranges,
5372 options::OPT_fdebug_types_section,
5373 options::OPT_fno_debug_types_section,
5374 options::OPT_fdwarf_directory_asm,
5375 options::OPT_fno_dwarf_directory_asm,
5376 options::OPT_mrelax_all,
5377 options::OPT_mno_relax_all,
5378 options::OPT_ftrap_function_EQ,
5379 options::OPT_ffixed_r9,
5380 options::OPT_mfix_cortex_a53_835769,
5381 options::OPT_mno_fix_cortex_a53_835769,
5382 options::OPT_ffixed_x18,
5383 options::OPT_mglobal_merge,
5384 options::OPT_mno_global_merge,
5385 options::OPT_mred_zone,
5386 options::OPT_mno_red_zone,
5387 options::OPT_Wa_COMMA,
5388 options::OPT_Xassembler,
5389 options::OPT_mllvm,
5390 options::OPT_mmlir,
5391 };
5392 for (const auto &A : Args)
5393 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5394 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5395
5396 // Render the CodeGen options that need to be passed.
5397 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5398 options::OPT_fno_optimize_sibling_calls);
5399
5400 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5401 CmdArgs, JA);
5402
5403 // Render ABI arguments
5404 switch (TC.getArch()) {
5405 default: break;
5406 case llvm::Triple::arm:
5407 case llvm::Triple::armeb:
5408 case llvm::Triple::thumbeb:
5409 RenderARMABI(D, Triple, Args, CmdArgs);
5410 break;
5411 case llvm::Triple::aarch64:
5412 case llvm::Triple::aarch64_32:
5413 case llvm::Triple::aarch64_be:
5414 RenderAArch64ABI(Triple, Args, CmdArgs);
5415 break;
5416 }
5417
5418 // Input/Output file.
5419 if (Output.getType() == types::TY_Dependencies) {
5420 // Handled with other dependency code.
5421 } else if (Output.isFilename()) {
5422 CmdArgs.push_back(Elt: "-o");
5423 CmdArgs.push_back(Elt: Output.getFilename());
5424 } else {
5425 assert(Output.isNothing() && "Input output.");
5426 }
5427
5428 for (const auto &II : Inputs) {
5429 addDashXForInput(Args, Input: II, CmdArgs);
5430 if (II.isFilename())
5431 CmdArgs.push_back(Elt: II.getFilename());
5432 else
5433 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5434 }
5435
5436 C.addCommand(C: std::make_unique<Command>(
5437 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getClangProgramPath(),
5438 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5439 return;
5440 }
5441
5442 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5443 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5444
5445 // We normally speed up the clang process a bit by skipping destructors at
5446 // exit, but when we're generating diagnostics we can rely on some of the
5447 // cleanup.
5448 if (!C.isForDiagnostics())
5449 CmdArgs.push_back(Elt: "-disable-free");
5450 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5451
5452#ifdef NDEBUG
5453 const bool IsAssertBuild = false;
5454#else
5455 const bool IsAssertBuild = true;
5456#endif
5457
5458 // Disable the verification pass in asserts builds unless otherwise specified.
5459 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5460 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5461 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5462 }
5463
5464 // Discard value names in assert builds unless otherwise specified.
5465 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5466 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5467 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5468 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5469 return types::isLLVMIR(II.getType());
5470 })) {
5471 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5472 }
5473 CmdArgs.push_back(Elt: "-discard-value-names");
5474 }
5475
5476 // Set the main file name, so that debug info works even with
5477 // -save-temps.
5478 CmdArgs.push_back(Elt: "-main-file-name");
5479 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5480
5481 // Some flags which affect the language (via preprocessor
5482 // defines).
5483 if (Args.hasArg(options::OPT_static))
5484 CmdArgs.push_back(Elt: "-static-define");
5485
5486 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5487
5488 if (Args.hasArg(options::OPT_municode))
5489 CmdArgs.push_back(Elt: "-DUNICODE");
5490
5491 if (isa<AnalyzeJobAction>(Val: JA))
5492 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5493
5494 if (isa<AnalyzeJobAction>(JA) ||
5495 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5496 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5497
5498 // Enable compatilibily mode to avoid analyzer-config related errors.
5499 // Since we can't access frontend flags through hasArg, let's manually iterate
5500 // through them.
5501 bool FoundAnalyzerConfig = false;
5502 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5503 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5504 FoundAnalyzerConfig = true;
5505 break;
5506 }
5507 if (!FoundAnalyzerConfig)
5508 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5509 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5510 FoundAnalyzerConfig = true;
5511 break;
5512 }
5513 if (FoundAnalyzerConfig)
5514 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5515
5516 CheckCodeGenerationOptions(D, Args);
5517
5518 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5519 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5520 if (FunctionAlignment) {
5521 CmdArgs.push_back(Elt: "-function-alignment");
5522 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::to_string(val: FunctionAlignment)));
5523 }
5524
5525 // We support -falign-loops=N where N is a power of 2. GCC supports more
5526 // forms.
5527 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5528 unsigned Value = 0;
5529 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5530 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5531 << A->getAsString(Args) << A->getValue();
5532 else if (Value & (Value - 1))
5533 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5534 << A->getAsString(Args) << A->getValue();
5535 // Treat =0 as unspecified (use the target preference).
5536 if (Value)
5537 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5538 Twine(std::min(a: Value, b: 65536u))));
5539 }
5540
5541 if (Triple.isOSzOS()) {
5542 // On z/OS some of the system header feature macros need to
5543 // be defined to enable most cross platform projects to build
5544 // successfully. Ths include the libc++ library. A
5545 // complicating factor is that users can define these
5546 // macros to the same or different values. We need to add
5547 // the definition for these macros to the compilation command
5548 // if the user hasn't already defined them.
5549
5550 auto findMacroDefinition = [&](const std::string &Macro) {
5551 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5552 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5553 return M == Macro || M.find(Macro + '=') != std::string::npos;
5554 });
5555 };
5556
5557 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5558 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5559 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5560 // _OPEN_DEFAULT is required for XL compat
5561 if (!findMacroDefinition("_OPEN_DEFAULT"))
5562 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5563 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5564 // _XOPEN_SOURCE=600 is required for libcxx.
5565 if (!findMacroDefinition("_XOPEN_SOURCE"))
5566 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5567 }
5568 }
5569
5570 llvm::Reloc::Model RelocationModel;
5571 unsigned PICLevel;
5572 bool IsPIE;
5573 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5574 Arg *LastPICDataRelArg =
5575 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5576 options::OPT_mpic_data_is_text_relative);
5577 bool NoPICDataIsTextRelative = false;
5578 if (LastPICDataRelArg) {
5579 if (LastPICDataRelArg->getOption().matches(
5580 options::OPT_mno_pic_data_is_text_relative)) {
5581 NoPICDataIsTextRelative = true;
5582 if (!PICLevel)
5583 D.Diag(diag::err_drv_argument_only_allowed_with)
5584 << "-mno-pic-data-is-text-relative"
5585 << "-fpic/-fpie";
5586 }
5587 if (!Triple.isSystemZ())
5588 D.Diag(diag::err_drv_unsupported_opt_for_target)
5589 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5590 : "-mpic-data-is-text-relative")
5591 << RawTriple.str();
5592 }
5593
5594 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5595 RelocationModel == llvm::Reloc::ROPI_RWPI;
5596 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5597 RelocationModel == llvm::Reloc::ROPI_RWPI;
5598
5599 if (Args.hasArg(options::OPT_mcmse) &&
5600 !Args.hasArg(options::OPT_fallow_unsupported)) {
5601 if (IsROPI)
5602 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5603 if (IsRWPI)
5604 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5605 }
5606
5607 if (IsROPI && types::isCXX(Input.getType()) &&
5608 !Args.hasArg(options::OPT_fallow_unsupported))
5609 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5610
5611 const char *RMName = RelocationModelName(Model: RelocationModel);
5612 if (RMName) {
5613 CmdArgs.push_back(Elt: "-mrelocation-model");
5614 CmdArgs.push_back(Elt: RMName);
5615 }
5616 if (PICLevel > 0) {
5617 CmdArgs.push_back(Elt: "-pic-level");
5618 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5619 if (IsPIE)
5620 CmdArgs.push_back(Elt: "-pic-is-pie");
5621 if (NoPICDataIsTextRelative)
5622 CmdArgs.push_back(Elt: "-mcmodel=medium");
5623 }
5624
5625 if (RelocationModel == llvm::Reloc::ROPI ||
5626 RelocationModel == llvm::Reloc::ROPI_RWPI)
5627 CmdArgs.push_back(Elt: "-fropi");
5628 if (RelocationModel == llvm::Reloc::RWPI ||
5629 RelocationModel == llvm::Reloc::ROPI_RWPI)
5630 CmdArgs.push_back(Elt: "-frwpi");
5631
5632 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5633 CmdArgs.push_back(Elt: "-meabi");
5634 CmdArgs.push_back(Elt: A->getValue());
5635 }
5636
5637 // -fsemantic-interposition is forwarded to CC1: set the
5638 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5639 // make default visibility external linkage definitions dso_preemptable.
5640 //
5641 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5642 // aliases (make default visibility external linkage definitions dso_local).
5643 // This is the CC1 default for ELF to match COFF/Mach-O.
5644 //
5645 // Otherwise use Clang's traditional behavior: like
5646 // -fno-semantic-interposition but local aliases are not used. So references
5647 // can be interposed if not optimized out.
5648 if (Triple.isOSBinFormatELF()) {
5649 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5650 options::OPT_fno_semantic_interposition);
5651 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5652 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5653 bool SupportsLocalAlias =
5654 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5655 if (!A)
5656 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5657 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5658 A->render(Args, Output&: CmdArgs);
5659 else if (!SupportsLocalAlias)
5660 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5661 }
5662 }
5663
5664 {
5665 std::string Model;
5666 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5667 if (!TC.isThreadModelSupported(A->getValue()))
5668 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5669 << A->getValue() << A->getAsString(Args);
5670 Model = A->getValue();
5671 } else
5672 Model = TC.getThreadModel();
5673 if (Model != "posix") {
5674 CmdArgs.push_back(Elt: "-mthread-model");
5675 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5676 }
5677 }
5678
5679 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5680 StringRef Name = A->getValue();
5681 if (Name == "SVML") {
5682 if (Triple.getArch() != llvm::Triple::x86 &&
5683 Triple.getArch() != llvm::Triple::x86_64)
5684 D.Diag(diag::err_drv_unsupported_opt_for_target)
5685 << Name << Triple.getArchName();
5686 } else if (Name == "libmvec" || Name == "AMDLIBM") {
5687 if (Triple.getArch() != llvm::Triple::x86 &&
5688 Triple.getArch() != llvm::Triple::x86_64)
5689 D.Diag(diag::err_drv_unsupported_opt_for_target)
5690 << Name << Triple.getArchName();
5691 } else if (Name == "SLEEF" || Name == "ArmPL") {
5692 if (Triple.getArch() != llvm::Triple::aarch64 &&
5693 Triple.getArch() != llvm::Triple::aarch64_be &&
5694 Triple.getArch() != llvm::Triple::riscv64)
5695 D.Diag(diag::err_drv_unsupported_opt_for_target)
5696 << Name << Triple.getArchName();
5697 }
5698 A->render(Args, Output&: CmdArgs);
5699 }
5700
5701 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5702 options::OPT_fno_merge_all_constants, false))
5703 CmdArgs.push_back(Elt: "-fmerge-all-constants");
5704
5705 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5706 options::OPT_fno_delete_null_pointer_checks);
5707
5708 // LLVM Code Generator Options.
5709
5710 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5711 if (!Triple.isOSAIX() || Triple.isPPC32())
5712 D.Diag(diag::err_drv_unsupported_opt_for_target)
5713 << A->getSpelling() << RawTriple.str();
5714 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
5715 }
5716
5717 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5718 // Emit the unsupported option error until the Clang's library integration
5719 // support for 128-bit long double is available for AIX.
5720 if (Triple.isOSAIX())
5721 D.Diag(diag::err_drv_unsupported_opt_for_target)
5722 << A->getSpelling() << RawTriple.str();
5723 }
5724
5725 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5726 StringRef V = A->getValue(), V1 = V;
5727 unsigned Size;
5728 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
5729 D.Diag(diag::err_drv_invalid_argument_to_option)
5730 << V << A->getOption().getName();
5731 else
5732 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
5733 }
5734
5735 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5736 options::OPT_fno_jump_tables);
5737 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5738 options::OPT_fno_profile_sample_accurate);
5739 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5740 options::OPT_fno_preserve_as_comments);
5741
5742 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5743 CmdArgs.push_back(Elt: "-mregparm");
5744 CmdArgs.push_back(Elt: A->getValue());
5745 }
5746
5747 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5748 options::OPT_msvr4_struct_return)) {
5749 if (!TC.getTriple().isPPC32()) {
5750 D.Diag(diag::err_drv_unsupported_opt_for_target)
5751 << A->getSpelling() << RawTriple.str();
5752 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5753 CmdArgs.push_back(Elt: "-maix-struct-return");
5754 } else {
5755 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5756 CmdArgs.push_back(Elt: "-msvr4-struct-return");
5757 }
5758 }
5759
5760 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5761 options::OPT_freg_struct_return)) {
5762 if (TC.getArch() != llvm::Triple::x86) {
5763 D.Diag(diag::err_drv_unsupported_opt_for_target)
5764 << A->getSpelling() << RawTriple.str();
5765 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5766 CmdArgs.push_back(Elt: "-fpcc-struct-return");
5767 } else {
5768 assert(A->getOption().matches(options::OPT_freg_struct_return));
5769 CmdArgs.push_back(Elt: "-freg-struct-return");
5770 }
5771 }
5772
5773 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5774 if (Triple.getArch() == llvm::Triple::m68k)
5775 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
5776 else
5777 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
5778 }
5779
5780 if (Args.hasArg(options::OPT_fenable_matrix)) {
5781 // enable-matrix is needed by both the LangOpts and by LLVM.
5782 CmdArgs.push_back(Elt: "-fenable-matrix");
5783 CmdArgs.push_back(Elt: "-mllvm");
5784 CmdArgs.push_back(Elt: "-enable-matrix");
5785 }
5786
5787 CodeGenOptions::FramePointerKind FPKeepKind =
5788 getFramePointerKind(Args, Triple: RawTriple);
5789 const char *FPKeepKindStr = nullptr;
5790 switch (FPKeepKind) {
5791 case CodeGenOptions::FramePointerKind::None:
5792 FPKeepKindStr = "-mframe-pointer=none";
5793 break;
5794 case CodeGenOptions::FramePointerKind::Reserved:
5795 FPKeepKindStr = "-mframe-pointer=reserved";
5796 break;
5797 case CodeGenOptions::FramePointerKind::NonLeaf:
5798 FPKeepKindStr = "-mframe-pointer=non-leaf";
5799 break;
5800 case CodeGenOptions::FramePointerKind::All:
5801 FPKeepKindStr = "-mframe-pointer=all";
5802 break;
5803 }
5804 assert(FPKeepKindStr && "unknown FramePointerKind");
5805 CmdArgs.push_back(Elt: FPKeepKindStr);
5806
5807 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5808 options::OPT_fno_zero_initialized_in_bss);
5809
5810 bool OFastEnabled = isOptimizationLevelFast(Args);
5811 if (OFastEnabled)
5812 D.Diag(diag::warn_drv_deprecated_arg_ofast);
5813 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5814 // enabled. This alias option is being used to simplify the hasFlag logic.
5815 OptSpecifier StrictAliasingAliasOption =
5816 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5817 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5818 // doesn't do any TBAA.
5819 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5820 options::OPT_fno_strict_aliasing,
5821 !IsWindowsMSVC && !IsUEFI))
5822 CmdArgs.push_back(Elt: "-relaxed-aliasing");
5823 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
5824 false))
5825 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
5826 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5827 options::OPT_fno_struct_path_tbaa, true))
5828 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
5829 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5830 options::OPT_fno_strict_enums);
5831 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5832 options::OPT_fno_strict_return);
5833 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5834 options::OPT_fno_allow_editor_placeholders);
5835 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5836 options::OPT_fno_strict_vtable_pointers);
5837 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5838 options::OPT_fno_force_emit_vtables);
5839 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5840 options::OPT_fno_optimize_sibling_calls);
5841 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5842 options::OPT_fno_escaping_block_tail_calls);
5843
5844 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5845 options::OPT_fno_fine_grained_bitfield_accesses);
5846
5847 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5848 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5849
5850 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5851 options::OPT_fno_experimental_omit_vtable_rtti);
5852
5853 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
5854 options::OPT_fno_disable_block_signature_string);
5855
5856 // Handle segmented stacks.
5857 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5858 options::OPT_fno_split_stack);
5859
5860 // -fprotect-parens=0 is default.
5861 if (Args.hasFlag(options::OPT_fprotect_parens,
5862 options::OPT_fno_protect_parens, false))
5863 CmdArgs.push_back(Elt: "-fprotect-parens");
5864
5865 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5866
5867 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
5868 options::OPT_fno_atomic_remote_memory);
5869 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
5870 options::OPT_fno_atomic_fine_grained_memory);
5871 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
5872 options::OPT_fno_atomic_ignore_denormal_mode);
5873
5874 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5875 const llvm::Triple::ArchType Arch = TC.getArch();
5876 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5877 StringRef V = A->getValue();
5878 if (V == "64")
5879 CmdArgs.push_back(Elt: "-fextend-arguments=64");
5880 else if (V != "32")
5881 D.Diag(diag::err_drv_invalid_argument_to_option)
5882 << A->getValue() << A->getOption().getName();
5883 } else
5884 D.Diag(diag::err_drv_unsupported_opt_for_target)
5885 << A->getOption().getName() << TripleStr;
5886 }
5887
5888 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5889 if (TC.getArch() == llvm::Triple::avr)
5890 A->render(Args, Output&: CmdArgs);
5891 else
5892 D.Diag(diag::err_drv_unsupported_opt_for_target)
5893 << A->getAsString(Args) << TripleStr;
5894 }
5895
5896 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5897 if (TC.getTriple().isX86())
5898 A->render(Args, Output&: CmdArgs);
5899 else if (TC.getTriple().isPPC() &&
5900 (A->getOption().getID() != options::OPT_mlong_double_80))
5901 A->render(Args, Output&: CmdArgs);
5902 else
5903 D.Diag(diag::err_drv_unsupported_opt_for_target)
5904 << A->getAsString(Args) << TripleStr;
5905 }
5906
5907 // Decide whether to use verbose asm. Verbose assembly is the default on
5908 // toolchains which have the integrated assembler on by default.
5909 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5910 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5911 IsIntegratedAssemblerDefault))
5912 CmdArgs.push_back(Elt: "-fno-verbose-asm");
5913
5914 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5915 // use that to indicate the MC default in the backend.
5916 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5917 StringRef V = A->getValue();
5918 unsigned Num;
5919 if (V == "none")
5920 A->render(Args, Output&: CmdArgs);
5921 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
5922 (V.empty() || (V.consume_front(Prefix: ".") &&
5923 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
5924 A->render(Args, Output&: CmdArgs);
5925 else
5926 D.Diag(diag::err_drv_invalid_argument_to_option)
5927 << A->getValue() << A->getOption().getName();
5928 }
5929
5930 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5931 // option to disable integrated-as explicitly.
5932 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5933 CmdArgs.push_back(Elt: "-no-integrated-as");
5934
5935 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5936 CmdArgs.push_back(Elt: "-mdebug-pass");
5937 CmdArgs.push_back(Elt: "Structure");
5938 }
5939 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5940 CmdArgs.push_back(Elt: "-mdebug-pass");
5941 CmdArgs.push_back(Elt: "Arguments");
5942 }
5943
5944 // Enable -mconstructor-aliases except on darwin, where we have to work around
5945 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5946 // code, where aliases aren't supported.
5947 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5948 CmdArgs.push_back(Elt: "-mconstructor-aliases");
5949
5950 // Darwin's kernel doesn't support guard variables; just die if we
5951 // try to use them.
5952 if (KernelOrKext && RawTriple.isOSDarwin())
5953 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
5954
5955 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5956 Triple.isWindowsGNUEnvironment())) {
5957 CmdArgs.push_back(Elt: "-mms-bitfields");
5958 }
5959
5960 if (Triple.isWindowsGNUEnvironment()) {
5961 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5962 options::OPT_fno_auto_import);
5963 }
5964
5965 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
5966 Triple.isX86() && IsWindowsMSVC))
5967 CmdArgs.push_back(Elt: "-fms-volatile");
5968
5969 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5970 // defaults to -fno-direct-access-external-data. Pass the option if different
5971 // from the default.
5972 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5973 options::OPT_fno_direct_access_external_data)) {
5974 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5975 (PICLevel == 0))
5976 A->render(Args, Output&: CmdArgs);
5977 } else if (PICLevel == 0 && Triple.isLoongArch()) {
5978 // Some targets default to -fno-direct-access-external-data even for
5979 // -fno-pic.
5980 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
5981 }
5982
5983 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
5984 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
5985
5986 // -fhosted is default.
5987 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5988 // use Freestanding.
5989 bool Freestanding =
5990 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5991 KernelOrKext;
5992 if (Freestanding)
5993 CmdArgs.push_back(Elt: "-ffreestanding");
5994
5995 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5996
5997 // This is a coarse approximation of what llvm-gcc actually does, both
5998 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5999 // complicated ways.
6000 auto SanitizeArgs = TC.getSanitizerArgs(JobArgs: Args);
6001
6002 bool IsAsyncUnwindTablesDefault =
6003 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6004 bool IsSyncUnwindTablesDefault =
6005 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6006
6007 bool AsyncUnwindTables = Args.hasFlag(
6008 options::OPT_fasynchronous_unwind_tables,
6009 options::OPT_fno_asynchronous_unwind_tables,
6010 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6011 !Freestanding);
6012 bool UnwindTables =
6013 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6014 IsSyncUnwindTablesDefault && !Freestanding);
6015 if (AsyncUnwindTables)
6016 CmdArgs.push_back(Elt: "-funwind-tables=2");
6017 else if (UnwindTables)
6018 CmdArgs.push_back(Elt: "-funwind-tables=1");
6019
6020 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6021 // `--gpu-use-aux-triple-only` is specified.
6022 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
6023 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6024 const ArgList &HostArgs =
6025 C.getArgsForToolChain(TC: nullptr, BoundArch: StringRef(), DeviceOffloadKind: Action::OFK_None);
6026 std::string HostCPU =
6027 getCPUName(D, Args: HostArgs, T: *TC.getAuxTriple(), /*FromAs*/ false);
6028 if (!HostCPU.empty()) {
6029 CmdArgs.push_back(Elt: "-aux-target-cpu");
6030 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6031 }
6032 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6033 /*ForAS*/ false, /*IsAux*/ true);
6034 }
6035
6036 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6037
6038 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6039
6040 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6041 StringRef Value = A->getValue();
6042 unsigned TLSSize = 0;
6043 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6044 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6045 D.Diag(diag::err_drv_unsupported_opt_for_target)
6046 << A->getOption().getName() << TripleStr;
6047 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6048 D.Diag(diag::err_drv_invalid_int_value)
6049 << A->getOption().getName() << Value;
6050 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6051 }
6052
6053 if (isTLSDESCEnabled(TC, Args))
6054 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6055
6056 // Add the target cpu
6057 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6058 if (!CPU.empty()) {
6059 CmdArgs.push_back(Elt: "-target-cpu");
6060 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6061 }
6062
6063 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6064
6065 // Add clang-cl arguments.
6066 types::ID InputType = Input.getType();
6067 if (D.IsCLMode())
6068 AddClangCLArgs(Args, InputType, CmdArgs);
6069
6070 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6071 llvm::codegenoptions::NoDebugInfo;
6072 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6073 renderDebugOptions(TC, D, T: RawTriple, Args, IRInput: types::isLLVMIR(Id: InputType),
6074 CmdArgs, Output, DebugInfoKind, DwarfFission);
6075
6076 // Add the split debug info name to the command lines here so we
6077 // can propagate it to the backend.
6078 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6079 (TC.getTriple().isOSBinFormatELF() ||
6080 TC.getTriple().isOSBinFormatWasm() ||
6081 TC.getTriple().isOSBinFormatCOFF()) &&
6082 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6083 isa<BackendJobAction>(Val: JA));
6084 if (SplitDWARF) {
6085 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6086 CmdArgs.push_back(Elt: "-split-dwarf-file");
6087 CmdArgs.push_back(Elt: SplitDWARFOut);
6088 if (DwarfFission == DwarfFissionKind::Split) {
6089 CmdArgs.push_back(Elt: "-split-dwarf-output");
6090 CmdArgs.push_back(Elt: SplitDWARFOut);
6091 }
6092 }
6093
6094 // Pass the linker version in use.
6095 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6096 CmdArgs.push_back(Elt: "-target-linker-version");
6097 CmdArgs.push_back(Elt: A->getValue());
6098 }
6099
6100 // Explicitly error on some things we know we don't support and can't just
6101 // ignore.
6102 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6103 Arg *Unsupported;
6104 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6105 TC.getArch() == llvm::Triple::x86) {
6106 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6107 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6108 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6109 << Unsupported->getOption().getName();
6110 }
6111 // The faltivec option has been superseded by the maltivec option.
6112 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6113 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6114 << Unsupported->getOption().getName()
6115 << "please use -maltivec and include altivec.h explicitly";
6116 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6117 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6118 << Unsupported->getOption().getName() << "please use -mno-altivec";
6119 }
6120
6121 Args.AddAllArgs(CmdArgs, options::OPT_v);
6122
6123 if (Args.getLastArg(options::OPT_H)) {
6124 CmdArgs.push_back(Elt: "-H");
6125 CmdArgs.push_back(Elt: "-sys-header-deps");
6126 }
6127 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6128
6129 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6130 CmdArgs.push_back(Elt: "-header-include-file");
6131 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6132 ? D.CCPrintHeadersFilename.c_str()
6133 : "-");
6134 CmdArgs.push_back(Elt: "-sys-header-deps");
6135 CmdArgs.push_back(Elt: Args.MakeArgString(
6136 Str: "-header-include-format=" +
6137 std::string(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6138 CmdArgs.push_back(
6139 Elt: Args.MakeArgString(Str: "-header-include-filtering=" +
6140 std::string(headerIncludeFilteringKindToString(
6141 K: D.CCPrintHeadersFiltering))));
6142 }
6143 Args.AddLastArg(CmdArgs, options::OPT_P);
6144 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6145
6146 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6147 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6148 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6149 ? D.CCLogDiagnosticsFilename.c_str()
6150 : "-");
6151 }
6152
6153 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6154 // crashes.
6155 if (D.CCGenDiagnostics)
6156 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6157
6158 // Allow backend to put its diagnostic files in the same place as frontend
6159 // crash diagnostics files.
6160 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6161 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6162 CmdArgs.push_back(Elt: "-mllvm");
6163 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6164 }
6165
6166 bool UseSeparateSections = isUseSeparateSections(Triple);
6167
6168 if (Args.hasFlag(options::OPT_ffunction_sections,
6169 options::OPT_fno_function_sections, UseSeparateSections)) {
6170 CmdArgs.push_back(Elt: "-ffunction-sections");
6171 }
6172
6173 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6174 options::OPT_fno_basic_block_address_map)) {
6175 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6176 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6177 A->render(Args, Output&: CmdArgs);
6178 } else {
6179 D.Diag(diag::err_drv_unsupported_opt_for_target)
6180 << A->getAsString(Args) << TripleStr;
6181 }
6182 }
6183
6184 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6185 StringRef Val = A->getValue();
6186 if (Val == "labels") {
6187 D.Diag(diag::warn_drv_deprecated_arg)
6188 << A->getAsString(Args) << /*hasReplacement=*/true
6189 << "-fbasic-block-address-map";
6190 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6191 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6192 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6193 D.Diag(diag::err_drv_invalid_value)
6194 << A->getAsString(Args) << A->getValue();
6195 else
6196 A->render(Args, Output&: CmdArgs);
6197 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6198 // "all" is not supported on AArch64 since branch relaxation creates new
6199 // basic blocks for some cross-section branches.
6200 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6201 D.Diag(diag::err_drv_invalid_value)
6202 << A->getAsString(Args) << A->getValue();
6203 else
6204 A->render(Args, Output&: CmdArgs);
6205 } else if (Triple.isNVPTX()) {
6206 // Do not pass the option to the GPU compilation. We still want it enabled
6207 // for the host-side compilation, so seeing it here is not an error.
6208 } else if (Val != "none") {
6209 // =none is allowed everywhere. It's useful for overriding the option
6210 // and is the same as not specifying the option.
6211 D.Diag(diag::err_drv_unsupported_opt_for_target)
6212 << A->getAsString(Args) << TripleStr;
6213 }
6214 }
6215
6216 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6217 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
6218 UseSeparateSections || HasDefaultDataSections)) {
6219 CmdArgs.push_back(Elt: "-fdata-sections");
6220 }
6221
6222 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6223 options::OPT_fno_unique_section_names);
6224 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6225 options::OPT_fno_separate_named_sections);
6226 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6227 options::OPT_fno_unique_internal_linkage_names);
6228 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6229 options::OPT_fno_unique_basic_block_section_names);
6230
6231 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6232 options::OPT_fno_split_machine_functions)) {
6233 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6234 // This codegen pass is only available on x86 and AArch64 ELF targets.
6235 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6236 A->render(Args, Output&: CmdArgs);
6237 else
6238 D.Diag(diag::err_drv_unsupported_opt_for_target)
6239 << A->getAsString(Args) << TripleStr;
6240 }
6241 }
6242
6243 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6244 options::OPT_finstrument_functions_after_inlining,
6245 options::OPT_finstrument_function_entry_bare);
6246 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6247 options::OPT_fno_convergent_functions);
6248
6249 // NVPTX doesn't support PGO or coverage
6250 if (!Triple.isNVPTX())
6251 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6252
6253 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6254
6255 if (getLastProfileSampleUseArg(Args) &&
6256 Args.hasArg(options::OPT_fsample_profile_use_profi)) {
6257 CmdArgs.push_back(Elt: "-mllvm");
6258 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6259 }
6260
6261 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6262 if (RawTriple.isPS() &&
6263 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6264 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6265 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6266 }
6267
6268 // Pass options for controlling the default header search paths.
6269 if (Args.hasArg(options::OPT_nostdinc)) {
6270 CmdArgs.push_back(Elt: "-nostdsysteminc");
6271 CmdArgs.push_back(Elt: "-nobuiltininc");
6272 } else {
6273 if (Args.hasArg(options::OPT_nostdlibinc))
6274 CmdArgs.push_back(Elt: "-nostdsysteminc");
6275 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6276 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6277 }
6278
6279 // Pass the path to compiler resource files.
6280 CmdArgs.push_back(Elt: "-resource-dir");
6281 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6282
6283 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6284
6285 // Add preprocessing options like -I, -D, etc. if we are using the
6286 // preprocessor.
6287 //
6288 // FIXME: Support -fpreprocessed
6289 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6290 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6291
6292 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6293 // that "The compiler can only warn and ignore the option if not recognized".
6294 // When building with ccache, it will pass -D options to clang even on
6295 // preprocessed inputs and configure concludes that -fPIC is not supported.
6296 Args.ClaimAllArgs(options::OPT_D);
6297
6298 // Warn about ignored options to clang.
6299 for (const Arg *A :
6300 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6301 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6302 A->claim();
6303 }
6304
6305 for (const Arg *A :
6306 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6307 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6308 A->claim();
6309 }
6310
6311 claimNoWarnArgs(Args);
6312
6313 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6314
6315 for (const Arg *A :
6316 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6317 A->claim();
6318 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6319 unsigned WarningNumber;
6320 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6321 D.Diag(diag::err_drv_invalid_int_value)
6322 << A->getAsString(Args) << A->getValue();
6323 continue;
6324 }
6325
6326 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6327 CmdArgs.push_back(Args.MakeArgString(
6328 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6329 }
6330 continue;
6331 }
6332 A->render(Args, CmdArgs);
6333 }
6334
6335 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6336
6337 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6338 CmdArgs.push_back(Elt: "-pedantic");
6339 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6340 Args.AddLastArg(CmdArgs, options::OPT_w);
6341
6342 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6343 options::OPT_fno_fixed_point);
6344
6345 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6346 A->render(Args, Output&: CmdArgs);
6347
6348 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6349 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6350
6351 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6352 options::OPT_fno_experimental_omit_vtable_rtti);
6353
6354 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6355 A->render(Args, Output&: CmdArgs);
6356
6357 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6358 // (-ansi is equivalent to -std=c89 or -std=c++98).
6359 //
6360 // If a std is supplied, only add -trigraphs if it follows the
6361 // option.
6362 bool ImplyVCPPCVer = false;
6363 bool ImplyVCPPCXXVer = false;
6364 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6365 if (Std) {
6366 if (Std->getOption().matches(options::OPT_ansi))
6367 if (types::isCXX(Id: InputType))
6368 CmdArgs.push_back(Elt: "-std=c++98");
6369 else
6370 CmdArgs.push_back(Elt: "-std=c89");
6371 else
6372 Std->render(Args, Output&: CmdArgs);
6373
6374 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6375 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6376 options::OPT_ftrigraphs,
6377 options::OPT_fno_trigraphs))
6378 if (A != Std)
6379 A->render(Args, Output&: CmdArgs);
6380 } else {
6381 // Honor -std-default.
6382 //
6383 // FIXME: Clang doesn't correctly handle -std= when the input language
6384 // doesn't match. For the time being just ignore this for C++ inputs;
6385 // eventually we want to do all the standard defaulting here instead of
6386 // splitting it between the driver and clang -cc1.
6387 if (!types::isCXX(Id: InputType)) {
6388 if (!Args.hasArg(options::OPT__SLASH_std)) {
6389 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6390 /*Joined=*/true);
6391 } else
6392 ImplyVCPPCVer = true;
6393 }
6394 else if (IsWindowsMSVC)
6395 ImplyVCPPCXXVer = true;
6396
6397 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6398 options::OPT_fno_trigraphs);
6399 }
6400
6401 // GCC's behavior for -Wwrite-strings is a bit strange:
6402 // * In C, this "warning flag" changes the types of string literals from
6403 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6404 // for the discarded qualifier.
6405 // * In C++, this is just a normal warning flag.
6406 //
6407 // Implementing this warning correctly in C is hard, so we follow GCC's
6408 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6409 // a non-const char* in C, rather than using this crude hack.
6410 if (!types::isCXX(Id: InputType)) {
6411 // FIXME: This should behave just like a warning flag, and thus should also
6412 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6413 Arg *WriteStrings =
6414 Args.getLastArg(options::OPT_Wwrite_strings,
6415 options::OPT_Wno_write_strings, options::OPT_w);
6416 if (WriteStrings &&
6417 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6418 CmdArgs.push_back(Elt: "-fconst-strings");
6419 }
6420
6421 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6422 // during C++ compilation, which it is by default. GCC keeps this define even
6423 // in the presence of '-w', match this behavior bug-for-bug.
6424 if (types::isCXX(InputType) &&
6425 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6426 true)) {
6427 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6428 }
6429
6430 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6431 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6432 if (Asm->getOption().matches(options::OPT_fasm))
6433 CmdArgs.push_back(Elt: "-fgnu-keywords");
6434 else
6435 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6436 }
6437
6438 if (!ShouldEnableAutolink(Args, TC, JA))
6439 CmdArgs.push_back(Elt: "-fno-autolink");
6440
6441 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6442 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6443 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6444 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6445
6446 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6447
6448 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6449 CmdArgs.push_back(Elt: "-fexperimental-new-constant-interpreter");
6450
6451 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6452 CmdArgs.push_back(Elt: "-fbracket-depth");
6453 CmdArgs.push_back(Elt: A->getValue());
6454 }
6455
6456 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6457 options::OPT_Wlarge_by_value_copy_def)) {
6458 if (A->getNumValues()) {
6459 StringRef bytes = A->getValue();
6460 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6461 } else
6462 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6463 }
6464
6465 if (Args.hasArg(options::OPT_relocatable_pch))
6466 CmdArgs.push_back(Elt: "-relocatable-pch");
6467
6468 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6469 static const char *kCFABIs[] = {
6470 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6471 };
6472
6473 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6474 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6475 else
6476 A->render(Args, Output&: CmdArgs);
6477 }
6478
6479 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6480 CmdArgs.push_back(Elt: "-fconstant-string-class");
6481 CmdArgs.push_back(Elt: A->getValue());
6482 }
6483
6484 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6485 CmdArgs.push_back(Elt: "-ftabstop");
6486 CmdArgs.push_back(Elt: A->getValue());
6487 }
6488
6489 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6490 options::OPT_fno_stack_size_section);
6491
6492 if (Args.hasArg(options::OPT_fstack_usage)) {
6493 CmdArgs.push_back(Elt: "-stack-usage-file");
6494
6495 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6496 SmallString<128> OutputFilename(OutputOpt->getValue());
6497 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6498 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6499 } else
6500 CmdArgs.push_back(
6501 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6502 }
6503
6504 CmdArgs.push_back(Elt: "-ferror-limit");
6505 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6506 CmdArgs.push_back(Elt: A->getValue());
6507 else
6508 CmdArgs.push_back(Elt: "19");
6509
6510 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6511 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6512 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6513 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6514 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6515
6516 // Pass -fmessage-length=.
6517 unsigned MessageLength = 0;
6518 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6519 StringRef V(A->getValue());
6520 if (V.getAsInteger(0, MessageLength))
6521 D.Diag(diag::err_drv_invalid_argument_to_option)
6522 << V << A->getOption().getName();
6523 } else {
6524 // If -fmessage-length=N was not specified, determine whether this is a
6525 // terminal and, if so, implicitly define -fmessage-length appropriately.
6526 MessageLength = llvm::sys::Process::StandardErrColumns();
6527 }
6528 if (MessageLength != 0)
6529 CmdArgs.push_back(
6530 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6531
6532 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6533 CmdArgs.push_back(
6534 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6535
6536 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6537 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6538 Twine(A->getValue(N: 0))));
6539
6540 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6541 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6542 options::OPT_fvisibility_ms_compat)) {
6543 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6544 A->render(Args, Output&: CmdArgs);
6545 } else {
6546 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6547 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6548 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6549 }
6550 } else if (IsOpenMPDevice) {
6551 // When compiling for the OpenMP device we want protected visibility by
6552 // default. This prevents the device from accidentally preempting code on
6553 // the host, makes the system more robust, and improves performance.
6554 CmdArgs.push_back(Elt: "-fvisibility=protected");
6555 }
6556
6557 // PS4/PS5 process these options in addClangTargetOptions.
6558 if (!RawTriple.isPS()) {
6559 if (const Arg *A =
6560 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6561 options::OPT_fno_visibility_from_dllstorageclass)) {
6562 if (A->getOption().matches(
6563 options::OPT_fvisibility_from_dllstorageclass)) {
6564 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6565 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6566 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6567 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6568 Args.AddLastArg(CmdArgs,
6569 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6570 }
6571 }
6572 }
6573
6574 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6575 options::OPT_fno_visibility_inlines_hidden, false))
6576 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
6577
6578 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6579 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6580
6581 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6582 // -fvisibility-global-new-delete=force-hidden.
6583 if (const Arg *A =
6584 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6585 D.Diag(diag::warn_drv_deprecated_arg)
6586 << A->getAsString(Args) << /*hasReplacement=*/true
6587 << "-fvisibility-global-new-delete=force-hidden";
6588 }
6589
6590 if (const Arg *A =
6591 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6592 options::OPT_fvisibility_global_new_delete_hidden)) {
6593 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6594 A->render(Args, Output&: CmdArgs);
6595 } else {
6596 assert(A->getOption().matches(
6597 options::OPT_fvisibility_global_new_delete_hidden));
6598 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
6599 }
6600 }
6601
6602 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6603
6604 if (Args.hasFlag(options::OPT_fnew_infallible,
6605 options::OPT_fno_new_infallible, false))
6606 CmdArgs.push_back(Elt: "-fnew-infallible");
6607
6608 if (Args.hasFlag(options::OPT_fno_operator_names,
6609 options::OPT_foperator_names, false))
6610 CmdArgs.push_back(Elt: "-fno-operator-names");
6611
6612 // Forward -f (flag) options which we can pass directly.
6613 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6614 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6615 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6616 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6617 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
6618 options::OPT_fno_raw_string_literals);
6619
6620 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6621 Triple.hasDefaultEmulatedTLS()))
6622 CmdArgs.push_back(Elt: "-femulated-tls");
6623
6624 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6625 options::OPT_fno_check_new);
6626
6627 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6628 // FIXME: There's no reason for this to be restricted to X86. The backend
6629 // code needs to be changed to include the appropriate function calls
6630 // automatically.
6631 if (!Triple.isX86() && !Triple.isAArch64())
6632 D.Diag(diag::err_drv_unsupported_opt_for_target)
6633 << A->getAsString(Args) << TripleStr;
6634 }
6635
6636 // AltiVec-like language extensions aren't relevant for assembling.
6637 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6638 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6639
6640 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6641 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6642
6643 // Forward flags for OpenMP. We don't do this if the current action is an
6644 // device offloading action other than OpenMP.
6645 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6646 options::OPT_fno_openmp, false) &&
6647 !Args.hasFlag(options::OPT_foffload_via_llvm,
6648 options::OPT_fno_offload_via_llvm, false) &&
6649 (JA.isDeviceOffloading(Action::OFK_None) ||
6650 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6651 switch (D.getOpenMPRuntime(Args)) {
6652 case Driver::OMPRT_OMP:
6653 case Driver::OMPRT_IOMP5:
6654 // Clang can generate useful OpenMP code for these two runtime libraries.
6655 CmdArgs.push_back(Elt: "-fopenmp");
6656
6657 // If no option regarding the use of TLS in OpenMP codegeneration is
6658 // given, decide a default based on the target. Otherwise rely on the
6659 // options and pass the right information to the frontend.
6660 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6661 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6662 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
6663 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6664 options::OPT_fno_openmp_simd);
6665 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6666 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6667 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6668 options::OPT_fno_openmp_extensions, /*Default=*/true))
6669 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
6670 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6671 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6672 Args.AddAllArgs(CmdArgs,
6673 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6674 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6675 options::OPT_fno_openmp_optimistic_collapse,
6676 /*Default=*/false))
6677 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
6678
6679 // When in OpenMP offloading mode with NVPTX target, forward
6680 // cuda-mode flag
6681 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6682 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6683 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
6684
6685 // When in OpenMP offloading mode, enable debugging on the device.
6686 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6687 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6688 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6689 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
6690
6691 // When in OpenMP offloading mode, forward assumptions information about
6692 // thread and team counts in the device.
6693 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6694 options::OPT_fno_openmp_assume_teams_oversubscription,
6695 /*Default=*/false))
6696 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
6697 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6698 options::OPT_fno_openmp_assume_threads_oversubscription,
6699 /*Default=*/false))
6700 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
6701 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6702 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
6703 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6704 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
6705 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6706 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
6707 if (Args.hasArg(options::OPT_fopenmp_force_usm))
6708 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
6709 break;
6710 default:
6711 // By default, if Clang doesn't know how to generate useful OpenMP code
6712 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6713 // down to the actual compilation.
6714 // FIXME: It would be better to have a mode which *only* omits IR
6715 // generation based on the OpenMP support so that we get consistent
6716 // semantic analysis, etc.
6717 break;
6718 }
6719 } else {
6720 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6721 options::OPT_fno_openmp_simd);
6722 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6723 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6724 options::OPT_fno_openmp_extensions);
6725 }
6726 // Forward the offload runtime change to code generation, liboffload implies
6727 // new driver. Otherwise, check if we should forward the new driver to change
6728 // offloading code generation.
6729 if (Args.hasFlag(options::OPT_foffload_via_llvm,
6730 options::OPT_fno_offload_via_llvm, false)) {
6731 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
6732 } else if (Args.hasFlag(options::OPT_offload_new_driver,
6733 options::OPT_no_offload_new_driver,
6734 C.isOffloadingHostKind(Action::OFK_Cuda))) {
6735 CmdArgs.push_back(Elt: "--offload-new-driver");
6736 }
6737
6738 const XRayArgs &XRay = TC.getXRayArgs(Args);
6739 XRay.addArgs(TC, Args, CmdArgs, InputType);
6740
6741 for (const auto &Filename :
6742 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6743 if (D.getVFS().exists(Filename))
6744 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6745 else
6746 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6747 }
6748
6749 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6750 StringRef S0 = A->getValue(), S = S0;
6751 unsigned Size, Offset = 0;
6752 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6753 !Triple.isX86() &&
6754 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6755 Triple.getArch() == llvm::Triple::ppc64)))
6756 D.Diag(diag::err_drv_unsupported_opt_for_target)
6757 << A->getAsString(Args) << TripleStr;
6758 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
6759 (!S.empty() &&
6760 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
6761 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
6762 D.Diag(diag::err_drv_invalid_argument_to_option)
6763 << S0 << A->getOption().getName();
6764 else if (Size < Offset)
6765 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6766 else {
6767 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
6768 CmdArgs.push_back(Elt: Args.MakeArgString(
6769 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
6770 if (!S.empty())
6771 CmdArgs.push_back(
6772 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
6773 }
6774 }
6775
6776 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6777
6778 if (TC.SupportsProfiling()) {
6779 Args.AddLastArg(CmdArgs, options::OPT_pg);
6780
6781 llvm::Triple::ArchType Arch = TC.getArch();
6782 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6783 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6784 A->render(Args, Output&: CmdArgs);
6785 else
6786 D.Diag(diag::err_drv_unsupported_opt_for_target)
6787 << A->getAsString(Args) << TripleStr;
6788 }
6789 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6790 if (Arch == llvm::Triple::systemz)
6791 A->render(Args, Output&: CmdArgs);
6792 else
6793 D.Diag(diag::err_drv_unsupported_opt_for_target)
6794 << A->getAsString(Args) << TripleStr;
6795 }
6796 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6797 if (Arch == llvm::Triple::systemz)
6798 A->render(Args, Output&: CmdArgs);
6799 else
6800 D.Diag(diag::err_drv_unsupported_opt_for_target)
6801 << A->getAsString(Args) << TripleStr;
6802 }
6803 }
6804
6805 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6806 if (TC.getTriple().isOSzOS()) {
6807 D.Diag(diag::err_drv_unsupported_opt_for_target)
6808 << A->getAsString(Args) << TripleStr;
6809 }
6810 }
6811 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6812 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6813 D.Diag(diag::err_drv_unsupported_opt_for_target)
6814 << A->getAsString(Args) << TripleStr;
6815 }
6816 }
6817 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6818 if (A->getOption().matches(options::OPT_p)) {
6819 A->claim();
6820 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6821 CmdArgs.push_back(Elt: "-pg");
6822 }
6823 }
6824
6825 // Reject AIX-specific link options on other targets.
6826 if (!TC.getTriple().isOSAIX()) {
6827 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6828 options::OPT_mxcoff_build_id_EQ)) {
6829 D.Diag(diag::err_drv_unsupported_opt_for_target)
6830 << A->getSpelling() << TripleStr;
6831 }
6832 }
6833
6834 if (Args.getLastArg(options::OPT_fapple_kext) ||
6835 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6836 CmdArgs.push_back(Elt: "-fapple-kext");
6837
6838 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6839 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6840 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6841 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6842 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6843 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6844 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6845 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
6846 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6847 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6848 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6849
6850 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
6851 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
6852 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6853 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
6854 }
6855
6856 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6857 CmdArgs.push_back(Elt: "-ftrapv-handler");
6858 CmdArgs.push_back(Elt: A->getValue());
6859 }
6860
6861 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6862
6863 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
6864 // clang and flang.
6865 renderCommonIntegerOverflowOptions(Args, CmdArgs);
6866
6867 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6868 options::OPT_fno_finite_loops);
6869
6870 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6871 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6872 options::OPT_fno_unroll_loops);
6873 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
6874 options::OPT_fno_loop_interchange);
6875
6876 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6877
6878 Args.AddLastArg(CmdArgs, options::OPT_pthread);
6879
6880 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6881 options::OPT_mno_speculative_load_hardening);
6882
6883 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6884 RenderSCPOptions(TC, Args, CmdArgs);
6885 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6886
6887 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6888
6889 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6890 options::OPT_mno_stackrealign);
6891
6892 if (Args.hasArg(options::OPT_mstack_alignment)) {
6893 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6894 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + alignment));
6895 }
6896
6897 if (Args.hasArg(options::OPT_mstack_probe_size)) {
6898 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6899
6900 if (!Size.empty())
6901 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
6902 else
6903 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
6904 }
6905
6906 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6907 options::OPT_mno_stack_arg_probe);
6908
6909 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6910 options::OPT_mno_restrict_it)) {
6911 if (A->getOption().matches(options::OPT_mrestrict_it)) {
6912 CmdArgs.push_back(Elt: "-mllvm");
6913 CmdArgs.push_back(Elt: "-arm-restrict-it");
6914 } else {
6915 CmdArgs.push_back(Elt: "-mllvm");
6916 CmdArgs.push_back(Elt: "-arm-default-it");
6917 }
6918 }
6919
6920 // Forward -cl options to -cc1
6921 RenderOpenCLOptions(Args, CmdArgs, InputType);
6922
6923 // Forward hlsl options to -cc1
6924 RenderHLSLOptions(Args, CmdArgs, InputType);
6925
6926 // Forward OpenACC options to -cc1
6927 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
6928
6929 if (IsHIP) {
6930 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6931 options::OPT_fno_hip_new_launch_api, true))
6932 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
6933 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
6934 options::OPT_fno_gpu_allow_device_init);
6935 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
6936 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
6937 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6938 options::OPT_fno_hip_kernel_arg_name);
6939 }
6940
6941 if (IsCuda || IsHIP) {
6942 if (IsRDCMode)
6943 CmdArgs.push_back(Elt: "-fgpu-rdc");
6944 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
6945 options::OPT_fno_gpu_defer_diag);
6946 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6947 options::OPT_fno_gpu_exclude_wrong_side_overloads,
6948 false)) {
6949 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
6950 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
6951 }
6952 }
6953
6954 // Forward --no-offloadlib to -cc1.
6955 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
6956 CmdArgs.push_back(Elt: "--no-offloadlib");
6957
6958 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6959 CmdArgs.push_back(
6960 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
6961
6962 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
6963 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
6964 SA->getValue()));
6965 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
6966 // Emit IBT endbr64 instructions by default
6967 CmdArgs.push_back(Elt: "-fcf-protection=branch");
6968 // jump-table can generate indirect jumps, which are not permitted
6969 CmdArgs.push_back(Elt: "-fno-jump-tables");
6970 }
6971
6972 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6973 CmdArgs.push_back(
6974 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
6975
6976 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6977
6978 // Forward -f options with positive and negative forms; we translate these by
6979 // hand. Do not propagate PGO options to the GPU-side compilations as the
6980 // profile info is for the host-side compilation only.
6981 if (!(IsCudaDevice || IsHIPDevice)) {
6982 if (Arg *A = getLastProfileSampleUseArg(Args)) {
6983 auto *PGOArg = Args.getLastArg(
6984 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6985 options::OPT_fcs_profile_generate,
6986 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6987 options::OPT_fprofile_use_EQ);
6988 if (PGOArg)
6989 D.Diag(diag::err_drv_argument_not_allowed_with)
6990 << "SampleUse with PGO options";
6991
6992 StringRef fname = A->getValue();
6993 if (!llvm::sys::fs::exists(Path: fname))
6994 D.Diag(diag::err_drv_no_such_file) << fname;
6995 else
6996 A->render(Args, Output&: CmdArgs);
6997 }
6998 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6999
7000 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7001 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7002 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7003 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7004 // off.
7005 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7006 options::OPT_fno_unique_internal_linkage_names, true))
7007 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7008 }
7009 }
7010 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7011
7012 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7013 options::OPT_fno_assume_sane_operator_new);
7014
7015 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7016 CmdArgs.push_back(Elt: "-fapinotes");
7017 if (Args.hasFlag(options::OPT_fapinotes_modules,
7018 options::OPT_fno_apinotes_modules, false))
7019 CmdArgs.push_back(Elt: "-fapinotes-modules");
7020 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7021
7022 // -fblocks=0 is default.
7023 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7024 TC.IsBlocksDefault()) ||
7025 (Args.hasArg(options::OPT_fgnu_runtime) &&
7026 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7027 !Args.hasArg(options::OPT_fno_blocks))) {
7028 CmdArgs.push_back(Elt: "-fblocks");
7029
7030 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7031 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7032 }
7033
7034 // -fencode-extended-block-signature=1 is default.
7035 if (TC.IsEncodeExtendedBlockSignatureDefault())
7036 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7037
7038 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7039 options::OPT_fno_coro_aligned_allocation, false) &&
7040 types::isCXX(InputType))
7041 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7042
7043 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7044 options::OPT_fno_double_square_bracket_attributes);
7045
7046 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7047 options::OPT_fno_access_control);
7048 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7049 options::OPT_fno_elide_constructors);
7050
7051 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7052
7053 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7054 (RTTIMode == ToolChain::RM_Disabled)))
7055 CmdArgs.push_back(Elt: "-fno-rtti");
7056
7057 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7058 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7059 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7060 CmdArgs.push_back(Elt: "-fshort-enums");
7061
7062 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7063
7064 // -fuse-cxa-atexit is default.
7065 if (!Args.hasFlag(
7066 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7067 !RawTriple.isOSAIX() &&
7068 (!RawTriple.isOSWindows() ||
7069 RawTriple.isWindowsCygwinEnvironment()) &&
7070 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7071 RawTriple.hasEnvironment())) ||
7072 KernelOrKext)
7073 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7074
7075 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7076 options::OPT_fno_register_global_dtors_with_atexit,
7077 RawTriple.isOSDarwin() && !KernelOrKext))
7078 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7079
7080 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7081 options::OPT_fno_use_line_directives);
7082
7083 // -fno-minimize-whitespace is default.
7084 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7085 options::OPT_fno_minimize_whitespace, false)) {
7086 types::ID InputType = Inputs[0].getType();
7087 if (!isDerivedFromC(InputType))
7088 D.Diag(diag::err_drv_opt_unsupported_input_type)
7089 << "-fminimize-whitespace" << types::getTypeName(InputType);
7090 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7091 }
7092
7093 // -fno-keep-system-includes is default.
7094 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7095 options::OPT_fno_keep_system_includes, false)) {
7096 types::ID InputType = Inputs[0].getType();
7097 if (!isDerivedFromC(InputType))
7098 D.Diag(diag::err_drv_opt_unsupported_input_type)
7099 << "-fkeep-system-includes" << types::getTypeName(InputType);
7100 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7101 }
7102
7103 // -fms-extensions=0 is default.
7104 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7105 IsWindowsMSVC || IsUEFI))
7106 CmdArgs.push_back(Elt: "-fms-extensions");
7107
7108 // -fms-compatibility=0 is default.
7109 bool IsMSVCCompat = Args.hasFlag(
7110 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7111 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7112 options::OPT_fno_ms_extensions, true)));
7113 if (IsMSVCCompat) {
7114 CmdArgs.push_back(Elt: "-fms-compatibility");
7115 if (!types::isCXX(Input.getType()) &&
7116 Args.hasArg(options::OPT_fms_define_stdc))
7117 CmdArgs.push_back(Elt: "-fms-define-stdc");
7118 }
7119
7120 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7121 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7122 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7123
7124 // Handle -fgcc-version, if present.
7125 VersionTuple GNUCVer;
7126 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7127 // Check that the version has 1 to 3 components and the minor and patch
7128 // versions fit in two decimal digits.
7129 StringRef Val = A->getValue();
7130 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7131 bool Invalid = GNUCVer.tryParse(string: Val);
7132 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7133 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7134 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7135 D.Diag(diag::err_drv_invalid_value)
7136 << A->getAsString(Args) << A->getValue();
7137 }
7138 } else if (!IsMSVCCompat) {
7139 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7140 GNUCVer = VersionTuple(4, 2, 1);
7141 }
7142 if (!GNUCVer.empty()) {
7143 CmdArgs.push_back(
7144 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7145 }
7146
7147 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7148 if (!MSVT.empty())
7149 CmdArgs.push_back(
7150 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7151
7152 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7153 if (ImplyVCPPCVer) {
7154 StringRef LanguageStandard;
7155 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7156 Std = StdArg;
7157 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7158 .Case(S: "c11", Value: "-std=c11")
7159 .Case(S: "c17", Value: "-std=c17")
7160 .Default(Value: "");
7161 if (LanguageStandard.empty())
7162 D.Diag(clang::diag::warn_drv_unused_argument)
7163 << StdArg->getAsString(Args);
7164 }
7165 CmdArgs.push_back(Elt: LanguageStandard.data());
7166 }
7167 if (ImplyVCPPCXXVer) {
7168 StringRef LanguageStandard;
7169 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7170 Std = StdArg;
7171 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7172 .Case(S: "c++14", Value: "-std=c++14")
7173 .Case(S: "c++17", Value: "-std=c++17")
7174 .Case(S: "c++20", Value: "-std=c++20")
7175 // TODO add c++23 and c++26 when MSVC supports it.
7176 .Case(S: "c++23preview", Value: "-std=c++23")
7177 .Case(S: "c++latest", Value: "-std=c++26")
7178 .Default(Value: "");
7179 if (LanguageStandard.empty())
7180 D.Diag(clang::diag::warn_drv_unused_argument)
7181 << StdArg->getAsString(Args);
7182 }
7183
7184 if (LanguageStandard.empty()) {
7185 if (IsMSVC2015Compatible)
7186 LanguageStandard = "-std=c++14";
7187 else
7188 LanguageStandard = "-std=c++11";
7189 }
7190
7191 CmdArgs.push_back(Elt: LanguageStandard.data());
7192 }
7193
7194 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7195 options::OPT_fno_borland_extensions);
7196
7197 // -fno-declspec is default, except for PS4/PS5.
7198 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7199 RawTriple.isPS()))
7200 CmdArgs.push_back(Elt: "-fdeclspec");
7201 else if (Args.hasArg(options::OPT_fno_declspec))
7202 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7203
7204 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7205 // than 19.
7206 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7207 options::OPT_fno_threadsafe_statics,
7208 !types::isOpenCL(InputType) &&
7209 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7210 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7211
7212 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7213 true))
7214 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7215
7216 // Add -fno-assumptions, if it was specified.
7217 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7218 true))
7219 CmdArgs.push_back(Elt: "-fno-assumptions");
7220
7221 // -fgnu-keywords default varies depending on language; only pass if
7222 // specified.
7223 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7224 options::OPT_fno_gnu_keywords);
7225
7226 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7227 options::OPT_fno_gnu89_inline);
7228
7229 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7230 options::OPT_finline_hint_functions,
7231 options::OPT_fno_inline_functions);
7232 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7233 if (A->getOption().matches(options::OPT_fno_inline))
7234 A->render(Args, Output&: CmdArgs);
7235 } else if (InlineArg) {
7236 InlineArg->render(Args, Output&: CmdArgs);
7237 }
7238
7239 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7240
7241 // FIXME: Find a better way to determine whether we are in C++20.
7242 bool HaveCxx20 =
7243 Std &&
7244 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7245 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7246 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7247 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7248 Std->containsValue(Value: "c++2c") || Std->containsValue(Value: "gnu++2c") ||
7249 Std->containsValue(Value: "c++26") || Std->containsValue(Value: "gnu++26") ||
7250 Std->containsValue(Value: "c++latest") || Std->containsValue(Value: "gnu++latest"));
7251 bool HaveModules =
7252 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7253
7254 // -fdelayed-template-parsing is default when targeting MSVC.
7255 // Many old Windows SDK versions require this to parse.
7256 //
7257 // According to
7258 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7259 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7260 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7261 // not enable -fdelayed-template-parsing by default after C++20.
7262 //
7263 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7264 // able to disable this by default at some point.
7265 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7266 options::OPT_fno_delayed_template_parsing,
7267 IsWindowsMSVC && !HaveCxx20)) {
7268 if (HaveCxx20)
7269 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7270
7271 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7272 }
7273
7274 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7275 options::OPT_fno_pch_validate_input_files_content, false))
7276 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7277 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7278 options::OPT_fno_pch_instantiate_templates, false))
7279 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7280 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7281 false))
7282 CmdArgs.push_back(Elt: "-fmodules-codegen");
7283 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7284 false))
7285 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7286
7287 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7288 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7289 Input, CmdArgs);
7290
7291 if (types::isObjC(Input.getType()) &&
7292 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7293 options::OPT_fno_objc_encode_cxx_class_template_spec,
7294 !Runtime.isNeXTFamily()))
7295 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7296
7297 if (Args.hasFlag(options::OPT_fapplication_extension,
7298 options::OPT_fno_application_extension, false))
7299 CmdArgs.push_back(Elt: "-fapplication-extension");
7300
7301 // Handle GCC-style exception args.
7302 bool EH = false;
7303 if (!C.getDriver().IsCLMode())
7304 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, objcRuntime: Runtime, CmdArgs);
7305
7306 // Handle exception personalities
7307 Arg *A = Args.getLastArg(
7308 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7309 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7310 if (A) {
7311 const Option &Opt = A->getOption();
7312 if (Opt.matches(options::OPT_fsjlj_exceptions))
7313 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7314 if (Opt.matches(options::OPT_fseh_exceptions))
7315 CmdArgs.push_back(Elt: "-exception-model=seh");
7316 if (Opt.matches(options::OPT_fdwarf_exceptions))
7317 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7318 if (Opt.matches(options::OPT_fwasm_exceptions))
7319 CmdArgs.push_back(Elt: "-exception-model=wasm");
7320 } else {
7321 switch (TC.GetExceptionModel(Args)) {
7322 default:
7323 break;
7324 case llvm::ExceptionHandling::DwarfCFI:
7325 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7326 break;
7327 case llvm::ExceptionHandling::SjLj:
7328 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7329 break;
7330 case llvm::ExceptionHandling::WinEH:
7331 CmdArgs.push_back(Elt: "-exception-model=seh");
7332 break;
7333 }
7334 }
7335
7336 // Unwind v2 (epilog) information for x64 Windows.
7337 Args.addOptInFlag(CmdArgs, options::OPT_fwinx64_eh_unwindv2,
7338 options::OPT_fno_winx64_eh_unwindv2);
7339
7340 // C++ "sane" operator new.
7341 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7342 options::OPT_fno_assume_sane_operator_new);
7343
7344 // -fassume-unique-vtables is on by default.
7345 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7346 options::OPT_fno_assume_unique_vtables);
7347
7348 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7349 // by default.
7350 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7351 options::OPT_fno_sized_deallocation);
7352
7353 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7354 // by default.
7355 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7356 options::OPT_fno_aligned_allocation,
7357 options::OPT_faligned_new_EQ)) {
7358 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7359 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7360 else
7361 CmdArgs.push_back(Elt: "-faligned-allocation");
7362 }
7363
7364 // The default new alignment can be specified using a dedicated option or via
7365 // a GCC-compatible option that also turns on aligned allocation.
7366 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7367 options::OPT_faligned_new_EQ))
7368 CmdArgs.push_back(
7369 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7370
7371 // -fconstant-cfstrings is default, and may be subject to argument translation
7372 // on Darwin.
7373 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7374 options::OPT_fno_constant_cfstrings, true) ||
7375 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7376 options::OPT_mno_constant_cfstrings, true))
7377 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7378
7379 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7380 options::OPT_fno_pascal_strings);
7381
7382 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7383 // -fno-pack-struct doesn't apply to -fpack-struct=.
7384 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7385 std::string PackStructStr = "-fpack-struct=";
7386 PackStructStr += A->getValue();
7387 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PackStructStr));
7388 } else if (Args.hasFlag(options::OPT_fpack_struct,
7389 options::OPT_fno_pack_struct, false)) {
7390 CmdArgs.push_back(Elt: "-fpack-struct=1");
7391 }
7392
7393 // Handle -fmax-type-align=N and -fno-type-align
7394 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7395 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7396 if (!SkipMaxTypeAlign) {
7397 std::string MaxTypeAlignStr = "-fmax-type-align=";
7398 MaxTypeAlignStr += A->getValue();
7399 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7400 }
7401 } else if (RawTriple.isOSDarwin()) {
7402 if (!SkipMaxTypeAlign) {
7403 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7404 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7405 }
7406 }
7407
7408 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7409 CmdArgs.push_back(Elt: "-Qn");
7410
7411 // -fno-common is the default, set -fcommon only when that flag is set.
7412 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7413
7414 // -fsigned-bitfields is default, and clang doesn't yet support
7415 // -funsigned-bitfields.
7416 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7417 options::OPT_funsigned_bitfields, true))
7418 D.Diag(diag::warn_drv_clang_unsupported)
7419 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7420
7421 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7422 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7423 D.Diag(diag::err_drv_clang_unsupported)
7424 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7425
7426 // -finput_charset=UTF-8 is default. Reject others
7427 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7428 StringRef value = inputCharset->getValue();
7429 if (!value.equals_insensitive("utf-8"))
7430 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7431 << value;
7432 }
7433
7434 // -fexec_charset=UTF-8 is default. Reject others
7435 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7436 StringRef value = execCharset->getValue();
7437 if (!value.equals_insensitive("utf-8"))
7438 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7439 << value;
7440 }
7441
7442 RenderDiagnosticsOptions(D, Args, CmdArgs);
7443
7444 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7445 options::OPT_fno_asm_blocks);
7446
7447 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7448 options::OPT_fno_gnu_inline_asm);
7449
7450 handleVectorizeLoopsArgs(Args, CmdArgs);
7451 handleVectorizeSLPArgs(Args, CmdArgs);
7452
7453 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
7454 if (!VecWidth.empty())
7455 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
7456
7457 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7458 Args.AddLastArg(CmdArgs,
7459 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7460
7461 // -fdollars-in-identifiers default varies depending on platform and
7462 // language; only pass if specified.
7463 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7464 options::OPT_fno_dollars_in_identifiers)) {
7465 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7466 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
7467 else
7468 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
7469 }
7470
7471 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7472 options::OPT_fno_apple_pragma_pack);
7473
7474 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7475 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7476 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7477
7478 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7479 options::OPT_fno_rewrite_imports, false);
7480 if (RewriteImports)
7481 CmdArgs.push_back(Elt: "-frewrite-imports");
7482
7483 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7484 options::OPT_fno_directives_only);
7485
7486 // Enable rewrite includes if the user's asked for it or if we're generating
7487 // diagnostics.
7488 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7489 // nice to enable this when doing a crashdump for modules as well.
7490 if (Args.hasFlag(options::OPT_frewrite_includes,
7491 options::OPT_fno_rewrite_includes, false) ||
7492 (C.isForDiagnostics() && !HaveModules))
7493 CmdArgs.push_back(Elt: "-frewrite-includes");
7494
7495 if (Args.hasFlag(options::OPT_fzos_extensions,
7496 options::OPT_fno_zos_extensions, false))
7497 CmdArgs.push_back(Elt: "-fzos-extensions");
7498 else if (Args.hasArg(options::OPT_fno_zos_extensions))
7499 CmdArgs.push_back(Elt: "-fno-zos-extensions");
7500
7501 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7502 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7503 options::OPT_traditional_cpp)) {
7504 if (isa<PreprocessJobAction>(Val: JA))
7505 CmdArgs.push_back(Elt: "-traditional-cpp");
7506 else
7507 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7508 }
7509
7510 Args.AddLastArg(CmdArgs, options::OPT_dM);
7511 Args.AddLastArg(CmdArgs, options::OPT_dD);
7512 Args.AddLastArg(CmdArgs, options::OPT_dI);
7513
7514 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7515
7516 // Handle serialized diagnostics.
7517 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7518 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
7519 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
7520 }
7521
7522 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7523 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
7524
7525 Args.AddLastArg(CmdArgs, options::OPT_fextend_variable_liveness_EQ);
7526
7527 // Forward -fcomment-block-commands to -cc1.
7528 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7529 // Forward -fparse-all-comments to -cc1.
7530 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7531
7532 // Turn -fplugin=name.so into -load name.so
7533 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7534 CmdArgs.push_back("-load");
7535 CmdArgs.push_back(A->getValue());
7536 A->claim();
7537 }
7538
7539 // Turn -fplugin-arg-pluginname-key=value into
7540 // -plugin-arg-pluginname key=value
7541 // GCC has an actual plugin_argument struct with key/value pairs that it
7542 // passes to its plugins, but we don't, so just pass it on as-is.
7543 //
7544 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7545 // argument key are allowed to contain dashes. GCC therefore only
7546 // allows dashes in the key. We do the same.
7547 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7548 auto ArgValue = StringRef(A->getValue());
7549 auto FirstDashIndex = ArgValue.find('-');
7550 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7551 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7552
7553 A->claim();
7554 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7555 if (PluginName.empty()) {
7556 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7557 } else {
7558 D.Diag(diag::warn_drv_missing_plugin_arg)
7559 << PluginName << A->getAsString(Args);
7560 }
7561 continue;
7562 }
7563
7564 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7565 CmdArgs.push_back(Args.MakeArgString(Arg));
7566 }
7567
7568 // Forward -fpass-plugin=name.so to -cc1.
7569 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7570 CmdArgs.push_back(
7571 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7572 A->claim();
7573 }
7574
7575 // Forward --vfsoverlay to -cc1.
7576 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7577 CmdArgs.push_back("--vfsoverlay");
7578 CmdArgs.push_back(A->getValue());
7579 A->claim();
7580 }
7581
7582 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7583 options::OPT_fno_safe_buffer_usage_suggestions);
7584
7585 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
7586 options::OPT_fno_experimental_late_parse_attributes);
7587
7588 if (Args.hasFlag(options::OPT_funique_source_file_names,
7589 options::OPT_fno_unique_source_file_names, false)) {
7590 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
7591 A->render(Args, Output&: CmdArgs);
7592 else
7593 CmdArgs.push_back(Elt: Args.MakeArgString(
7594 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7595 }
7596
7597 // Setup statistics file output.
7598 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7599 if (!StatsFile.empty()) {
7600 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
7601 if (D.CCPrintInternalStats)
7602 CmdArgs.push_back(Elt: "-stats-file-append");
7603 }
7604
7605 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7606 // parser.
7607 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7608 Arg->claim();
7609 // -finclude-default-header flag is for preprocessor,
7610 // do not pass it to other cc1 commands when save-temps is enabled
7611 if (C.getDriver().isSaveTempsEnabled() &&
7612 !isa<PreprocessJobAction>(JA)) {
7613 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7614 continue;
7615 }
7616 CmdArgs.push_back(Arg->getValue());
7617 }
7618 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7619 A->claim();
7620
7621 // We translate this by hand to the -cc1 argument, since nightly test uses
7622 // it and developers have been trained to spell it with -mllvm. Both
7623 // spellings are now deprecated and should be removed.
7624 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7625 CmdArgs.push_back("-disable-llvm-optzns");
7626 } else {
7627 A->render(Args, CmdArgs);
7628 }
7629 }
7630
7631 // This needs to run after -Xclang argument forwarding to pick up the target
7632 // features enabled through -Xclang -target-feature flags.
7633 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7634
7635#if CLANG_ENABLE_CIR
7636 // Forward -mmlir arguments to to the MLIR option parser.
7637 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7638 A->claim();
7639 A->render(Args, CmdArgs);
7640 }
7641#endif // CLANG_ENABLE_CIR
7642
7643 // With -save-temps, we want to save the unoptimized bitcode output from the
7644 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7645 // by the frontend.
7646 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7647 // has slightly different breakdown between stages.
7648 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7649 // pristine IR generated by the frontend. Ideally, a new compile action should
7650 // be added so both IR can be captured.
7651 if ((C.getDriver().isSaveTempsEnabled() ||
7652 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
7653 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7654 isa<CompileJobAction>(Val: JA))
7655 CmdArgs.push_back(Elt: "-disable-llvm-passes");
7656
7657 Args.AddAllArgs(CmdArgs, options::OPT_undef);
7658
7659 const char *Exec = D.getClangProgramPath();
7660
7661 // Optionally embed the -cc1 level arguments into the debug info or a
7662 // section, for build analysis.
7663 // Also record command line arguments into the debug info if
7664 // -grecord-gcc-switches options is set on.
7665 // By default, -gno-record-gcc-switches is set on and no recording.
7666 auto GRecordSwitches = false;
7667 auto FRecordSwitches = false;
7668 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches)) {
7669 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7670 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7671 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
7672 CmdArgs.push_back(Elt: FlagsArgString);
7673 }
7674 if (FRecordSwitches) {
7675 CmdArgs.push_back(Elt: "-record-command-line");
7676 CmdArgs.push_back(Elt: FlagsArgString);
7677 }
7678 }
7679
7680 // Host-side offloading compilation receives all device-side outputs. Include
7681 // them in the host compilation depending on the target. If the host inputs
7682 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7683 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7684 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7685 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
7686 } else if (!HostOffloadingInputs.empty()) {
7687 if ((IsCuda || IsHIP) && !IsRDCMode) {
7688 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7689 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7690 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
7691 } else {
7692 for (const InputInfo Input : HostOffloadingInputs)
7693 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
7694 TC.getInputFilename(Input)));
7695 }
7696 }
7697
7698 if (IsCuda) {
7699 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7700 options::OPT_fno_cuda_short_ptr, false))
7701 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
7702 }
7703
7704 if (IsCuda || IsHIP) {
7705 // Determine the original source input.
7706 const Action *SourceAction = &JA;
7707 while (SourceAction->getKind() != Action::InputClass) {
7708 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7709 SourceAction = SourceAction->getInputs()[0];
7710 }
7711 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
7712 if (!CUID.empty())
7713 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
7714
7715 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7716 // be overriden by -fno-gpu-approx-transcendentals.
7717 bool UseApproxTranscendentals = Args.hasFlag(
7718 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7719 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7720 options::OPT_fno_gpu_approx_transcendentals,
7721 UseApproxTranscendentals))
7722 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
7723 } else {
7724 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7725 options::OPT_fno_gpu_approx_transcendentals);
7726 }
7727
7728 if (IsHIP) {
7729 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
7730 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7731 }
7732
7733 Args.AddAllArgs(CmdArgs,
7734 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7735
7736 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7737 options::OPT_fno_offload_uniform_block);
7738
7739 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
7740 options::OPT_fno_offload_implicit_host_device_templates);
7741
7742 if (IsCudaDevice || IsHIPDevice) {
7743 StringRef InlineThresh =
7744 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7745 if (!InlineThresh.empty()) {
7746 std::string ArgStr =
7747 std::string("-inline-threshold=") + InlineThresh.str();
7748 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
7749 }
7750 }
7751
7752 if (IsHIPDevice)
7753 Args.addOptOutFlag(CmdArgs,
7754 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7755 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7756
7757 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7758 // to specify the result of the compile phase on the host, so the meaningful
7759 // device declarations can be identified. Also, -fopenmp-is-target-device is
7760 // passed along to tell the frontend that it is generating code for a device,
7761 // so that only the relevant declarations are emitted.
7762 if (IsOpenMPDevice) {
7763 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
7764 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7765 if (Args.hasArg(options::OPT_foffload_via_llvm))
7766 CmdArgs.push_back(Elt: "-fcuda-is-device");
7767
7768 if (OpenMPDeviceInput) {
7769 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
7770 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
7771 }
7772 }
7773
7774 if (Triple.isAMDGPU()) {
7775 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7776
7777 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7778 options::OPT_mno_unsafe_fp_atomics);
7779 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7780 options::OPT_mno_amdgpu_ieee);
7781 }
7782
7783 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
7784
7785 bool VirtualFunctionElimination =
7786 Args.hasFlag(options::OPT_fvirtual_function_elimination,
7787 options::OPT_fno_virtual_function_elimination, false);
7788 if (VirtualFunctionElimination) {
7789 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7790 // in the future).
7791 if (LTOMode != LTOK_Full)
7792 D.Diag(diag::err_drv_argument_only_allowed_with)
7793 << "-fvirtual-function-elimination"
7794 << "-flto=full";
7795
7796 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
7797 }
7798
7799 // VFE requires whole-program-vtables, and enables it by default.
7800 bool WholeProgramVTables = Args.hasFlag(
7801 options::OPT_fwhole_program_vtables,
7802 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7803 if (VirtualFunctionElimination && !WholeProgramVTables) {
7804 D.Diag(diag::err_drv_argument_not_allowed_with)
7805 << "-fno-whole-program-vtables"
7806 << "-fvirtual-function-elimination";
7807 }
7808
7809 if (WholeProgramVTables) {
7810 // PS4 uses the legacy LTO API, which does not support this feature in
7811 // ThinLTO mode.
7812 bool IsPS4 = getToolChain().getTriple().isPS4();
7813
7814 // Check if we passed LTO options but they were suppressed because this is a
7815 // device offloading action, or we passed device offload LTO options which
7816 // were suppressed because this is not the device offload action.
7817 // Check if we are using PS4 in regular LTO mode.
7818 // Otherwise, issue an error.
7819
7820 auto OtherLTOMode =
7821 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
7822 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
7823
7824 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
7825 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7826 D.Diag(diag::err_drv_argument_only_allowed_with)
7827 << "-fwhole-program-vtables"
7828 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7829
7830 // Propagate -fwhole-program-vtables if this is an LTO compile.
7831 if (IsUsingLTO)
7832 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
7833 }
7834
7835 bool DefaultsSplitLTOUnit =
7836 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7837 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7838 (!Triple.isPS4() && UnifiedLTO);
7839 bool SplitLTOUnit =
7840 Args.hasFlag(options::OPT_fsplit_lto_unit,
7841 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7842 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7843 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7844 << "-fsanitize=cfi";
7845 if (SplitLTOUnit)
7846 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
7847
7848 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
7849 options::OPT_fno_fat_lto_objects)) {
7850 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
7851 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7852 if (!Triple.isOSBinFormatELF()) {
7853 D.Diag(diag::err_drv_unsupported_opt_for_target)
7854 << A->getAsString(Args) << TC.getTripleString();
7855 }
7856 CmdArgs.push_back(Elt: Args.MakeArgString(
7857 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7858 CmdArgs.push_back(Elt: "-flto-unit");
7859 CmdArgs.push_back(Elt: "-ffat-lto-objects");
7860 A->render(Args, Output&: CmdArgs);
7861 }
7862 }
7863
7864 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7865 options::OPT_fno_global_isel)) {
7866 CmdArgs.push_back(Elt: "-mllvm");
7867 if (A->getOption().matches(options::OPT_fglobal_isel)) {
7868 CmdArgs.push_back(Elt: "-global-isel=1");
7869
7870 // GISel is on by default on AArch64 -O0, so don't bother adding
7871 // the fallback remarks for it. Other combinations will add a warning of
7872 // some kind.
7873 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7874 bool IsOptLevelSupported = false;
7875
7876 Arg *A = Args.getLastArg(options::OPT_O_Group);
7877 if (Triple.getArch() == llvm::Triple::aarch64) {
7878 if (!A || A->getOption().matches(options::OPT_O0))
7879 IsOptLevelSupported = true;
7880 }
7881 if (!IsArchSupported || !IsOptLevelSupported) {
7882 CmdArgs.push_back(Elt: "-mllvm");
7883 CmdArgs.push_back(Elt: "-global-isel-abort=2");
7884
7885 if (!IsArchSupported)
7886 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7887 else
7888 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7889 }
7890 } else {
7891 CmdArgs.push_back(Elt: "-global-isel=0");
7892 }
7893 }
7894
7895 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7896 options::OPT_fno_force_enable_int128)) {
7897 if (A->getOption().matches(options::OPT_fforce_enable_int128))
7898 CmdArgs.push_back(Elt: "-fforce-enable-int128");
7899 }
7900
7901 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7902 options::OPT_fno_keep_static_consts);
7903 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7904 options::OPT_fno_keep_persistent_storage_variables);
7905 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7906 options::OPT_fno_complete_member_pointers);
7907 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
7908 A->render(Args, Output&: CmdArgs);
7909
7910 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7911
7912 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
7913
7914 if (Triple.isAArch64() &&
7915 (Args.hasArg(options::OPT_mno_fmv) ||
7916 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7917 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7918 // Disable Function Multiversioning on AArch64 target.
7919 CmdArgs.push_back(Elt: "-target-feature");
7920 CmdArgs.push_back(Elt: "-fmv");
7921 }
7922
7923 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7924 (TC.getTriple().isOSBinFormatELF() ||
7925 TC.getTriple().isOSBinFormatCOFF()) &&
7926 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7927 !TC.getTriple().isOSNetBSD() &&
7928 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7929 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7930 CmdArgs.push_back(Elt: "-faddrsig");
7931
7932 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7933 (EH || UnwindTables || AsyncUnwindTables ||
7934 DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7935 CmdArgs.push_back(Elt: "-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7936
7937 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7938 std::string Str = A->getAsString(Args);
7939 if (!TC.getTriple().isOSBinFormatELF())
7940 D.Diag(diag::err_drv_unsupported_opt_for_target)
7941 << Str << TC.getTripleString();
7942 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
7943 }
7944
7945 // Add the "-o out -x type src.c" flags last. This is done primarily to make
7946 // the -cc1 command easier to edit when reproducing compiler crashes.
7947 if (Output.getType() == types::TY_Dependencies) {
7948 // Handled with other dependency code.
7949 } else if (Output.isFilename()) {
7950 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7951 Output.getType() == clang::driver::types::TY_IFS) {
7952 SmallString<128> OutputFilename(Output.getFilename());
7953 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
7954 CmdArgs.push_back(Elt: "-o");
7955 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
7956 } else {
7957 CmdArgs.push_back(Elt: "-o");
7958 CmdArgs.push_back(Elt: Output.getFilename());
7959 }
7960 } else {
7961 assert(Output.isNothing() && "Invalid output.");
7962 }
7963
7964 addDashXForInput(Args, Input, CmdArgs);
7965
7966 ArrayRef<InputInfo> FrontendInputs = Input;
7967 if (IsExtractAPI)
7968 FrontendInputs = ExtractAPIInputs;
7969 else if (Input.isNothing())
7970 FrontendInputs = {};
7971
7972 for (const InputInfo &Input : FrontendInputs) {
7973 if (Input.isFilename())
7974 CmdArgs.push_back(Elt: Input.getFilename());
7975 else
7976 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
7977 }
7978
7979 if (D.CC1Main && !D.CCGenDiagnostics) {
7980 // Invoke the CC1 directly in this process
7981 C.addCommand(C: std::make_unique<CC1Command>(
7982 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
7983 args: Output, args: D.getPrependArg()));
7984 } else {
7985 C.addCommand(C: std::make_unique<Command>(
7986 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
7987 args: Output, args: D.getPrependArg()));
7988 }
7989
7990 // Make the compile command echo its inputs for /showFilenames.
7991 if (Output.getType() == types::TY_Object &&
7992 Args.hasFlag(options::OPT__SLASH_showFilenames,
7993 options::OPT__SLASH_showFilenames_, false)) {
7994 C.getJobs().getJobs().back()->PrintInputFilenames = true;
7995 }
7996
7997 if (Arg *A = Args.getLastArg(options::OPT_pg))
7998 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7999 !Args.hasArg(options::OPT_mfentry))
8000 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8001 << A->getAsString(Args);
8002
8003 // Claim some arguments which clang supports automatically.
8004
8005 // -fpch-preprocess is used with gcc to add a special marker in the output to
8006 // include the PCH file.
8007 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8008
8009 // Claim some arguments which clang doesn't support, but we don't
8010 // care to warn the user about.
8011 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8012 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8013
8014 // Disable warnings for clang -E -emit-llvm foo.c
8015 Args.ClaimAllArgs(options::OPT_emit_llvm);
8016}
8017
8018Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8019 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8020 // as it is for other tools. Some operations on a Tool actually test
8021 // whether that tool is Clang based on the Tool's Name as a string.
8022 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8023
8024Clang::~Clang() {}
8025
8026/// Add options related to the Objective-C runtime/ABI.
8027///
8028/// Returns true if the runtime is non-fragile.
8029ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8030 const InputInfoList &inputs,
8031 ArgStringList &cmdArgs,
8032 RewriteKind rewriteKind) const {
8033 // Look for the controlling runtime option.
8034 Arg *runtimeArg =
8035 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8036 options::OPT_fobjc_runtime_EQ);
8037
8038 // Just forward -fobjc-runtime= to the frontend. This supercedes
8039 // options about fragility.
8040 if (runtimeArg &&
8041 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8042 ObjCRuntime runtime;
8043 StringRef value = runtimeArg->getValue();
8044 if (runtime.tryParse(input: value)) {
8045 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8046 << value;
8047 }
8048 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8049 (runtime.getVersion() >= VersionTuple(2, 0)))
8050 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8051 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8052 getToolChain().getDriver().Diag(
8053 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8054 << runtime.getVersion().getMajor();
8055 }
8056
8057 runtimeArg->render(Args: args, Output&: cmdArgs);
8058 return runtime;
8059 }
8060
8061 // Otherwise, we'll need the ABI "version". Version numbers are
8062 // slightly confusing for historical reasons:
8063 // 1 - Traditional "fragile" ABI
8064 // 2 - Non-fragile ABI, version 1
8065 // 3 - Non-fragile ABI, version 2
8066 unsigned objcABIVersion = 1;
8067 // If -fobjc-abi-version= is present, use that to set the version.
8068 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8069 StringRef value = abiArg->getValue();
8070 if (value == "1")
8071 objcABIVersion = 1;
8072 else if (value == "2")
8073 objcABIVersion = 2;
8074 else if (value == "3")
8075 objcABIVersion = 3;
8076 else
8077 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8078 } else {
8079 // Otherwise, determine if we are using the non-fragile ABI.
8080 bool nonFragileABIIsDefault =
8081 (rewriteKind == RK_NonFragile ||
8082 (rewriteKind == RK_None &&
8083 getToolChain().IsObjCNonFragileABIDefault()));
8084 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8085 options::OPT_fno_objc_nonfragile_abi,
8086 nonFragileABIIsDefault)) {
8087// Determine the non-fragile ABI version to use.
8088#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8089 unsigned nonFragileABIVersion = 1;
8090#else
8091 unsigned nonFragileABIVersion = 2;
8092#endif
8093
8094 if (Arg *abiArg =
8095 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8096 StringRef value = abiArg->getValue();
8097 if (value == "1")
8098 nonFragileABIVersion = 1;
8099 else if (value == "2")
8100 nonFragileABIVersion = 2;
8101 else
8102 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8103 << value;
8104 }
8105
8106 objcABIVersion = 1 + nonFragileABIVersion;
8107 } else {
8108 objcABIVersion = 1;
8109 }
8110 }
8111
8112 // We don't actually care about the ABI version other than whether
8113 // it's non-fragile.
8114 bool isNonFragile = objcABIVersion != 1;
8115
8116 // If we have no runtime argument, ask the toolchain for its default runtime.
8117 // However, the rewriter only really supports the Mac runtime, so assume that.
8118 ObjCRuntime runtime;
8119 if (!runtimeArg) {
8120 switch (rewriteKind) {
8121 case RK_None:
8122 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8123 break;
8124 case RK_Fragile:
8125 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8126 break;
8127 case RK_NonFragile:
8128 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8129 break;
8130 }
8131
8132 // -fnext-runtime
8133 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8134 // On Darwin, make this use the default behavior for the toolchain.
8135 if (getToolChain().getTriple().isOSDarwin()) {
8136 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8137
8138 // Otherwise, build for a generic macosx port.
8139 } else {
8140 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8141 }
8142
8143 // -fgnu-runtime
8144 } else {
8145 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8146 // Legacy behaviour is to target the gnustep runtime if we are in
8147 // non-fragile mode or the GCC runtime in fragile mode.
8148 if (isNonFragile)
8149 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8150 else
8151 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8152 }
8153
8154 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8155 return types::isObjC(Id: input.getType());
8156 }))
8157 cmdArgs.push_back(
8158 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8159 return runtime;
8160}
8161
8162static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8163 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8164 I += HaveDash;
8165 return !HaveDash;
8166}
8167
8168namespace {
8169struct EHFlags {
8170 bool Synch = false;
8171 bool Asynch = false;
8172 bool NoUnwindC = false;
8173};
8174} // end anonymous namespace
8175
8176/// /EH controls whether to run destructor cleanups when exceptions are
8177/// thrown. There are three modifiers:
8178/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8179/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8180/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8181/// - c: Assume that extern "C" functions are implicitly nounwind.
8182/// The default is /EHs-c-, meaning cleanups are disabled.
8183static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8184 bool isWindowsMSVC) {
8185 EHFlags EH;
8186
8187 std::vector<std::string> EHArgs =
8188 Args.getAllArgValues(options::OPT__SLASH_EH);
8189 for (const auto &EHVal : EHArgs) {
8190 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8191 switch (EHVal[I]) {
8192 case 'a':
8193 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8194 if (EH.Asynch) {
8195 // Async exceptions are Windows MSVC only.
8196 if (!isWindowsMSVC) {
8197 EH.Asynch = false;
8198 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8199 continue;
8200 }
8201 EH.Synch = false;
8202 }
8203 continue;
8204 case 'c':
8205 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8206 continue;
8207 case 's':
8208 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8209 if (EH.Synch)
8210 EH.Asynch = false;
8211 continue;
8212 default:
8213 break;
8214 }
8215 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8216 break;
8217 }
8218 }
8219 // The /GX, /GX- flags are only processed if there are not /EH flags.
8220 // The default is that /GX is not specified.
8221 if (EHArgs.empty() &&
8222 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8223 /*Default=*/false)) {
8224 EH.Synch = true;
8225 EH.NoUnwindC = true;
8226 }
8227
8228 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8229 EH.Synch = false;
8230 EH.NoUnwindC = false;
8231 EH.Asynch = false;
8232 }
8233
8234 return EH;
8235}
8236
8237void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8238 ArgStringList &CmdArgs) const {
8239 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8240
8241 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8242
8243 if (Arg *ShowIncludes =
8244 Args.getLastArg(options::OPT__SLASH_showIncludes,
8245 options::OPT__SLASH_showIncludes_user)) {
8246 CmdArgs.push_back(Elt: "--show-includes");
8247 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8248 CmdArgs.push_back(Elt: "-sys-header-deps");
8249 }
8250
8251 // This controls whether or not we emit RTTI data for polymorphic types.
8252 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8253 /*Default=*/false))
8254 CmdArgs.push_back(Elt: "-fno-rtti-data");
8255
8256 // This controls whether or not we emit stack-protector instrumentation.
8257 // In MSVC, Buffer Security Check (/GS) is on by default.
8258 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8259 /*Default=*/true)) {
8260 CmdArgs.push_back(Elt: "-stack-protector");
8261 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8262 }
8263
8264 const Driver &D = getToolChain().getDriver();
8265
8266 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8267 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8268 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8269 if (types::isCXX(Id: InputType))
8270 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8271 CmdArgs.push_back(Elt: "-fexceptions");
8272 if (EH.Asynch)
8273 CmdArgs.push_back(Elt: "-fasync-exceptions");
8274 }
8275 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8276 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8277
8278 // /EP should expand to -E -P.
8279 if (Args.hasArg(options::OPT__SLASH_EP)) {
8280 CmdArgs.push_back(Elt: "-E");
8281 CmdArgs.push_back(Elt: "-P");
8282 }
8283
8284 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8285 options::OPT__SLASH_Zc_dllexportInlines,
8286 false)) {
8287 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8288 }
8289
8290 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8291 options::OPT__SLASH_Zc_wchar_t, false)) {
8292 CmdArgs.push_back(Elt: "-fno-wchar");
8293 }
8294
8295 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8296 llvm::Triple::ArchType Arch = getToolChain().getArch();
8297 std::vector<std::string> Values =
8298 Args.getAllArgValues(options::OPT__SLASH_arch);
8299 if (!Values.empty()) {
8300 llvm::SmallSet<std::string, 4> SupportedArches;
8301 if (Arch == llvm::Triple::x86)
8302 SupportedArches.insert(V: "IA32");
8303
8304 for (auto &V : Values)
8305 if (!SupportedArches.contains(V))
8306 D.Diag(diag::err_drv_argument_not_allowed_with)
8307 << std::string("/arch:").append(V) << "/kernel";
8308 }
8309
8310 CmdArgs.push_back(Elt: "-fno-rtti");
8311 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8312 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8313 << "/kernel";
8314 }
8315
8316 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8317 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8318 if (MostGeneralArg && BestCaseArg)
8319 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8320 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8321
8322 if (MostGeneralArg) {
8323 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8324 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8325 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8326
8327 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8328 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8329 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8330 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8331 << FirstConflict->getAsString(Args)
8332 << SecondConflict->getAsString(Args);
8333
8334 if (SingleArg)
8335 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8336 else if (MultipleArg)
8337 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8338 else
8339 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8340 }
8341
8342 if (Args.hasArg(options::OPT_regcall4))
8343 CmdArgs.push_back(Elt: "-regcall4");
8344
8345 // Parse the default calling convention options.
8346 if (Arg *CCArg =
8347 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8348 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8349 options::OPT__SLASH_Gregcall)) {
8350 unsigned DCCOptId = CCArg->getOption().getID();
8351 const char *DCCFlag = nullptr;
8352 bool ArchSupported = !isNVPTX;
8353 llvm::Triple::ArchType Arch = getToolChain().getArch();
8354 switch (DCCOptId) {
8355 case options::OPT__SLASH_Gd:
8356 DCCFlag = "-fdefault-calling-conv=cdecl";
8357 break;
8358 case options::OPT__SLASH_Gr:
8359 ArchSupported = Arch == llvm::Triple::x86;
8360 DCCFlag = "-fdefault-calling-conv=fastcall";
8361 break;
8362 case options::OPT__SLASH_Gz:
8363 ArchSupported = Arch == llvm::Triple::x86;
8364 DCCFlag = "-fdefault-calling-conv=stdcall";
8365 break;
8366 case options::OPT__SLASH_Gv:
8367 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8368 DCCFlag = "-fdefault-calling-conv=vectorcall";
8369 break;
8370 case options::OPT__SLASH_Gregcall:
8371 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8372 DCCFlag = "-fdefault-calling-conv=regcall";
8373 break;
8374 }
8375
8376 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8377 if (ArchSupported && DCCFlag)
8378 CmdArgs.push_back(Elt: DCCFlag);
8379 }
8380
8381 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8382 CmdArgs.push_back(Elt: "-regcall4");
8383
8384 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8385
8386 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8387 CmdArgs.push_back(Elt: "-fdiagnostics-format");
8388 CmdArgs.push_back(Elt: "msvc");
8389 }
8390
8391 if (Args.hasArg(options::OPT__SLASH_kernel))
8392 CmdArgs.push_back(Elt: "-fms-kernel");
8393
8394 // Unwind v2 (epilog) information for x64 Windows.
8395 if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
8396 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2");
8397
8398 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8399 StringRef GuardArgs = A->getValue();
8400 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8401 // "ehcont-".
8402 if (GuardArgs.equals_insensitive("cf")) {
8403 // Emit CFG instrumentation and the table of address-taken functions.
8404 CmdArgs.push_back("-cfguard");
8405 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8406 // Emit only the table of address-taken functions.
8407 CmdArgs.push_back("-cfguard-no-checks");
8408 } else if (GuardArgs.equals_insensitive("ehcont")) {
8409 // Emit EH continuation table.
8410 CmdArgs.push_back("-ehcontguard");
8411 } else if (GuardArgs.equals_insensitive("cf-") ||
8412 GuardArgs.equals_insensitive("ehcont-")) {
8413 // Do nothing, but we might want to emit a security warning in future.
8414 } else {
8415 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8416 }
8417 A->claim();
8418 }
8419
8420 for (const auto &FuncOverride :
8421 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
8422 CmdArgs.push_back(Args.MakeArgString(
8423 Twine("-loader-replaceable-function=") + FuncOverride));
8424 }
8425}
8426
8427const char *Clang::getBaseInputName(const ArgList &Args,
8428 const InputInfo &Input) {
8429 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
8430}
8431
8432const char *Clang::getBaseInputStem(const ArgList &Args,
8433 const InputInfoList &Inputs) {
8434 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
8435
8436 if (const char *End = strrchr(s: Str, c: '.'))
8437 return Args.MakeArgString(Str: std::string(Str, End));
8438
8439 return Str;
8440}
8441
8442const char *Clang::getDependencyFileName(const ArgList &Args,
8443 const InputInfoList &Inputs) {
8444 // FIXME: Think about this more.
8445
8446 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8447 SmallString<128> OutputFilename(OutputOpt->getValue());
8448 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
8449 return Args.MakeArgString(Str: OutputFilename);
8450 }
8451
8452 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
8453}
8454
8455// Begin ClangAs
8456
8457void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8458 ArgStringList &CmdArgs) const {
8459 StringRef CPUName;
8460 StringRef ABIName;
8461 const llvm::Triple &Triple = getToolChain().getTriple();
8462 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8463
8464 CmdArgs.push_back(Elt: "-target-abi");
8465 CmdArgs.push_back(Elt: ABIName.data());
8466}
8467
8468void ClangAs::AddX86TargetArgs(const ArgList &Args,
8469 ArgStringList &CmdArgs) const {
8470 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
8471 /*IsLTO=*/false);
8472
8473 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8474 StringRef Value = A->getValue();
8475 if (Value == "intel" || Value == "att") {
8476 CmdArgs.push_back(Elt: "-mllvm");
8477 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
8478 } else {
8479 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8480 << A->getSpelling() << Value;
8481 }
8482 }
8483}
8484
8485void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8486 ArgStringList &CmdArgs) const {
8487 CmdArgs.push_back(Elt: "-target-abi");
8488 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
8489 Triple: getToolChain().getTriple())
8490 .data());
8491}
8492
8493void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8494 ArgStringList &CmdArgs) const {
8495 const llvm::Triple &Triple = getToolChain().getTriple();
8496 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8497
8498 CmdArgs.push_back(Elt: "-target-abi");
8499 CmdArgs.push_back(Elt: ABIName.data());
8500
8501 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8502 options::OPT_mno_default_build_attributes, true)) {
8503 CmdArgs.push_back(Elt: "-mllvm");
8504 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
8505 }
8506}
8507
8508void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8509 const InputInfo &Output, const InputInfoList &Inputs,
8510 const ArgList &Args,
8511 const char *LinkingOutput) const {
8512 ArgStringList CmdArgs;
8513
8514 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8515 const InputInfo &Input = Inputs[0];
8516
8517 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8518 const std::string &TripleStr = Triple.getTriple();
8519 const auto &D = getToolChain().getDriver();
8520
8521 // Don't warn about "clang -w -c foo.s"
8522 Args.ClaimAllArgs(options::OPT_w);
8523 // and "clang -emit-llvm -c foo.s"
8524 Args.ClaimAllArgs(options::OPT_emit_llvm);
8525
8526 claimNoWarnArgs(Args);
8527
8528 // Invoke ourselves in -cc1as mode.
8529 //
8530 // FIXME: Implement custom jobs for internal actions.
8531 CmdArgs.push_back(Elt: "-cc1as");
8532
8533 // Add the "effective" target triple.
8534 CmdArgs.push_back(Elt: "-triple");
8535 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
8536
8537 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
8538
8539 // Set the output mode, we currently only expect to be used as a real
8540 // assembler.
8541 CmdArgs.push_back(Elt: "-filetype");
8542 CmdArgs.push_back(Elt: "obj");
8543
8544 // Set the main file name, so that debug info works even with
8545 // -save-temps or preprocessed assembly.
8546 CmdArgs.push_back(Elt: "-main-file-name");
8547 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
8548
8549 // Add the target cpu
8550 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
8551 if (!CPU.empty()) {
8552 CmdArgs.push_back(Elt: "-target-cpu");
8553 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
8554 }
8555
8556 // Add the target features
8557 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
8558
8559 // Ignore explicit -force_cpusubtype_ALL option.
8560 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8561
8562 // Pass along any -I options so we get proper .include search paths.
8563 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8564
8565 // Pass along any --embed-dir or similar options so we get proper embed paths.
8566 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
8567
8568 // Determine the original source input.
8569 auto FindSource = [](const Action *S) -> const Action * {
8570 while (S->getKind() != Action::InputClass) {
8571 assert(!S->getInputs().empty() && "unexpected root action!");
8572 S = S->getInputs()[0];
8573 }
8574 return S;
8575 };
8576 const Action *SourceAction = FindSource(&JA);
8577
8578 // Forward -g and handle debug info related flags, assuming we are dealing
8579 // with an actual assembly file.
8580 bool WantDebug = false;
8581 Args.ClaimAllArgs(options::OPT_g_Group);
8582 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8583 WantDebug = !A->getOption().matches(options::OPT_g0) &&
8584 !A->getOption().matches(options::OPT_ggdb0);
8585
8586 // If a -gdwarf argument appeared, remember it.
8587 bool EmitDwarf = false;
8588 if (const Arg *A = getDwarfNArg(Args))
8589 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8590
8591 bool EmitCodeView = false;
8592 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
8593 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8594
8595 // If the user asked for debug info but did not explicitly specify -gcodeview
8596 // or -gdwarf, ask the toolchain for the default format.
8597 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8598 switch (getToolChain().getDefaultDebugFormat()) {
8599 case llvm::codegenoptions::DIF_CodeView:
8600 EmitCodeView = true;
8601 break;
8602 case llvm::codegenoptions::DIF_DWARF:
8603 EmitDwarf = true;
8604 break;
8605 }
8606 }
8607
8608 // If the arguments don't imply DWARF, don't emit any debug info here.
8609 if (!EmitDwarf)
8610 WantDebug = false;
8611
8612 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8613 llvm::codegenoptions::NoDebugInfo;
8614
8615 // Add the -fdebug-compilation-dir flag if needed.
8616 const char *DebugCompilationDir =
8617 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
8618
8619 if (SourceAction->getType() == types::TY_Asm ||
8620 SourceAction->getType() == types::TY_PP_Asm) {
8621 // You might think that it would be ok to set DebugInfoKind outside of
8622 // the guard for source type, however there is a test which asserts
8623 // that some assembler invocation receives no -debug-info-kind,
8624 // and it's not clear whether that test is just overly restrictive.
8625 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8626 : llvm::codegenoptions::NoDebugInfo);
8627
8628 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
8629 CmdArgs);
8630
8631 // Set the AT_producer to the clang version when using the integrated
8632 // assembler on assembly source files.
8633 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
8634 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
8635
8636 // And pass along -I options
8637 Args.AddAllArgs(CmdArgs, options::OPT_I);
8638 }
8639 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
8640 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8641 DebuggerTuning: llvm::DebuggerKind::Default);
8642 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
8643 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
8644
8645 // Handle -fPIC et al -- the relocation-model affects the assembler
8646 // for some targets.
8647 llvm::Reloc::Model RelocationModel;
8648 unsigned PICLevel;
8649 bool IsPIE;
8650 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
8651 ParsePICArgs(ToolChain: getToolChain(), Args);
8652
8653 const char *RMName = RelocationModelName(Model: RelocationModel);
8654 if (RMName) {
8655 CmdArgs.push_back(Elt: "-mrelocation-model");
8656 CmdArgs.push_back(Elt: RMName);
8657 }
8658
8659 // Optionally embed the -cc1as level arguments into the debug info, for build
8660 // analysis.
8661 if (getToolChain().UseDwarfDebugFlags()) {
8662 ArgStringList OriginalArgs;
8663 for (const auto &Arg : Args)
8664 Arg->render(Args, Output&: OriginalArgs);
8665
8666 SmallString<256> Flags;
8667 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8668 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
8669 for (const char *OriginalArg : OriginalArgs) {
8670 SmallString<128> EscapedArg;
8671 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
8672 Flags += " ";
8673 Flags += EscapedArg;
8674 }
8675 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8676 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
8677 }
8678
8679 // FIXME: Add -static support, once we have it.
8680
8681 // Add target specific flags.
8682 switch (getToolChain().getArch()) {
8683 default:
8684 break;
8685
8686 case llvm::Triple::mips:
8687 case llvm::Triple::mipsel:
8688 case llvm::Triple::mips64:
8689 case llvm::Triple::mips64el:
8690 AddMIPSTargetArgs(Args, CmdArgs);
8691 break;
8692
8693 case llvm::Triple::x86:
8694 case llvm::Triple::x86_64:
8695 AddX86TargetArgs(Args, CmdArgs);
8696 break;
8697
8698 case llvm::Triple::arm:
8699 case llvm::Triple::armeb:
8700 case llvm::Triple::thumb:
8701 case llvm::Triple::thumbeb:
8702 // This isn't in AddARMTargetArgs because we want to do this for assembly
8703 // only, not C/C++.
8704 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8705 options::OPT_mno_default_build_attributes, true)) {
8706 CmdArgs.push_back(Elt: "-mllvm");
8707 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
8708 }
8709 break;
8710
8711 case llvm::Triple::aarch64:
8712 case llvm::Triple::aarch64_32:
8713 case llvm::Triple::aarch64_be:
8714 if (Args.hasArg(options::OPT_mmark_bti_property)) {
8715 CmdArgs.push_back(Elt: "-mllvm");
8716 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
8717 }
8718 break;
8719
8720 case llvm::Triple::loongarch32:
8721 case llvm::Triple::loongarch64:
8722 AddLoongArchTargetArgs(Args, CmdArgs);
8723 break;
8724
8725 case llvm::Triple::riscv32:
8726 case llvm::Triple::riscv64:
8727 AddRISCVTargetArgs(Args, CmdArgs);
8728 break;
8729
8730 case llvm::Triple::hexagon:
8731 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8732 options::OPT_mno_default_build_attributes, true)) {
8733 CmdArgs.push_back(Elt: "-mllvm");
8734 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
8735 }
8736 break;
8737 }
8738
8739 // Consume all the warning flags. Usually this would be handled more
8740 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8741 // doesn't handle that so rather than warning about unused flags that are
8742 // actually used, we'll lie by omission instead.
8743 // FIXME: Stop lying and consume only the appropriate driver flags
8744 Args.ClaimAllArgs(options::OPT_W_Group);
8745
8746 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8747 D: getToolChain().getDriver());
8748
8749 // Forward -Xclangas arguments to -cc1as
8750 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
8751 Arg->claim();
8752 CmdArgs.push_back(Arg->getValue());
8753 }
8754
8755 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8756
8757 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8758 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8759 OutputFileName: Output.getFilename());
8760
8761 // Fixup any previous commands that use -object-file-name because when we
8762 // generated them, the final .obj name wasn't yet known.
8763 for (Command &J : C.getJobs()) {
8764 if (SourceAction != FindSource(&J.getSource()))
8765 continue;
8766 auto &JArgs = J.getArguments();
8767 for (unsigned I = 0; I < JArgs.size(); ++I) {
8768 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
8769 Output.isFilename()) {
8770 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8771 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
8772 OutputFileName: Output.getFilename());
8773 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
8774 J.replaceArguments(List: NewArgs);
8775 break;
8776 }
8777 }
8778 }
8779
8780 assert(Output.isFilename() && "Unexpected lipo output.");
8781 CmdArgs.push_back(Elt: "-o");
8782 CmdArgs.push_back(Elt: Output.getFilename());
8783
8784 const llvm::Triple &T = getToolChain().getTriple();
8785 Arg *A;
8786 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
8787 T.isOSBinFormatELF()) {
8788 CmdArgs.push_back(Elt: "-split-dwarf-output");
8789 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
8790 }
8791
8792 if (Triple.isAMDGPU())
8793 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8794
8795 assert(Input.isFilename() && "Invalid input.");
8796 CmdArgs.push_back(Elt: Input.getFilename());
8797
8798 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8799 if (D.CC1Main && !D.CCGenDiagnostics) {
8800 // Invoke cc1as directly in this process.
8801 C.addCommand(C: std::make_unique<CC1Command>(
8802 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8803 args: Output, args: D.getPrependArg()));
8804 } else {
8805 C.addCommand(C: std::make_unique<Command>(
8806 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8807 args: Output, args: D.getPrependArg()));
8808 }
8809}
8810
8811// Begin OffloadBundler
8812void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8813 const InputInfo &Output,
8814 const InputInfoList &Inputs,
8815 const llvm::opt::ArgList &TCArgs,
8816 const char *LinkingOutput) const {
8817 // The version with only one output is expected to refer to a bundling job.
8818 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8819
8820 // The bundling command looks like this:
8821 // clang-offload-bundler -type=bc
8822 // -targets=host-triple,openmp-triple1,openmp-triple2
8823 // -output=output_file
8824 // -input=unbundle_file_host
8825 // -input=unbundle_file_tgt1
8826 // -input=unbundle_file_tgt2
8827
8828 ArgStringList CmdArgs;
8829
8830 // Get the type.
8831 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
8832 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
8833
8834 assert(JA.getInputs().size() == Inputs.size() &&
8835 "Not have inputs for all dependence actions??");
8836
8837 // Get the targets.
8838 SmallString<128> Triples;
8839 Triples += "-targets=";
8840 for (unsigned I = 0; I < Inputs.size(); ++I) {
8841 if (I)
8842 Triples += ',';
8843
8844 // Find ToolChain for this input.
8845 Action::OffloadKind CurKind = Action::OFK_Host;
8846 const ToolChain *CurTC = &getToolChain();
8847 const Action *CurDep = JA.getInputs()[I];
8848
8849 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
8850 CurTC = nullptr;
8851 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, const char *) {
8852 assert(CurTC == nullptr && "Expected one dependence!");
8853 CurKind = A->getOffloadingDeviceKind();
8854 CurTC = TC;
8855 });
8856 }
8857 Triples += Action::GetOffloadKindName(Kind: CurKind);
8858 Triples += '-';
8859 Triples +=
8860 CurTC->getTriple().normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
8861 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8862 !StringRef(CurDep->getOffloadingArch()).empty()) {
8863 Triples += '-';
8864 Triples += CurDep->getOffloadingArch();
8865 }
8866
8867 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8868 // with each toolchain.
8869 StringRef GPUArchName;
8870 if (CurKind == Action::OFK_OpenMP) {
8871 // Extract GPUArch from -march argument in TC argument list.
8872 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8873 auto ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
8874 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
8875 if (Arch) {
8876 GPUArchName = ArchStr.substr(Start: 7);
8877 Triples += "-";
8878 break;
8879 }
8880 }
8881 Triples += GPUArchName.str();
8882 }
8883 }
8884 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
8885
8886 // Get bundled file command.
8887 CmdArgs.push_back(
8888 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
8889
8890 // Get unbundled files command.
8891 for (unsigned I = 0; I < Inputs.size(); ++I) {
8892 SmallString<128> UB;
8893 UB += "-input=";
8894
8895 // Find ToolChain for this input.
8896 const ToolChain *CurTC = &getToolChain();
8897 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
8898 CurTC = nullptr;
8899 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, const char *) {
8900 assert(CurTC == nullptr && "Expected one dependence!");
8901 CurTC = TC;
8902 });
8903 UB += C.addTempFile(
8904 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
8905 } else {
8906 UB += CurTC->getInputFilename(Input: Inputs[I]);
8907 }
8908 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
8909 }
8910 addOffloadCompressArgs(TCArgs, CmdArgs);
8911 // All the inputs are encoded as commands.
8912 C.addCommand(C: std::make_unique<Command>(
8913 args: JA, args: *this, args: ResponseFileSupport::None(),
8914 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
8915 args&: CmdArgs, args: std::nullopt, args: Output));
8916}
8917
8918void OffloadBundler::ConstructJobMultipleOutputs(
8919 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8920 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8921 const char *LinkingOutput) const {
8922 // The version with multiple outputs is expected to refer to a unbundling job.
8923 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
8924
8925 // The unbundling command looks like this:
8926 // clang-offload-bundler -type=bc
8927 // -targets=host-triple,openmp-triple1,openmp-triple2
8928 // -input=input_file
8929 // -output=unbundle_file_host
8930 // -output=unbundle_file_tgt1
8931 // -output=unbundle_file_tgt2
8932 // -unbundle
8933
8934 ArgStringList CmdArgs;
8935
8936 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8937 InputInfo Input = Inputs.front();
8938
8939 // Get the type.
8940 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
8941 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
8942
8943 // Get the targets.
8944 SmallString<128> Triples;
8945 Triples += "-targets=";
8946 auto DepInfo = UA.getDependentActionsInfo();
8947 for (unsigned I = 0; I < DepInfo.size(); ++I) {
8948 if (I)
8949 Triples += ',';
8950
8951 auto &Dep = DepInfo[I];
8952 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
8953 Triples += '-';
8954 Triples += Dep.DependentToolChain->getTriple().normalize(
8955 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
8956 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8957 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8958 !Dep.DependentBoundArch.empty()) {
8959 Triples += '-';
8960 Triples += Dep.DependentBoundArch;
8961 }
8962 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8963 // with each toolchain.
8964 StringRef GPUArchName;
8965 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8966 // Extract GPUArch from -march argument in TC argument list.
8967 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8968 StringRef ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
8969 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
8970 if (Arch) {
8971 GPUArchName = ArchStr.substr(Start: 7);
8972 Triples += "-";
8973 break;
8974 }
8975 }
8976 Triples += GPUArchName.str();
8977 }
8978 }
8979
8980 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
8981
8982 // Get bundled file command.
8983 CmdArgs.push_back(
8984 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
8985
8986 // Get unbundled files command.
8987 for (unsigned I = 0; I < Outputs.size(); ++I) {
8988 SmallString<128> UB;
8989 UB += "-output=";
8990 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
8991 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
8992 }
8993 CmdArgs.push_back(Elt: "-unbundle");
8994 CmdArgs.push_back(Elt: "-allow-missing-bundles");
8995 if (TCArgs.hasArg(options::OPT_v))
8996 CmdArgs.push_back(Elt: "-verbose");
8997
8998 // All the inputs are encoded as commands.
8999 C.addCommand(C: std::make_unique<Command>(
9000 args: JA, args: *this, args: ResponseFileSupport::None(),
9001 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9002 args&: CmdArgs, args: std::nullopt, args: Outputs));
9003}
9004
9005void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9006 const InputInfo &Output,
9007 const InputInfoList &Inputs,
9008 const llvm::opt::ArgList &Args,
9009 const char *LinkingOutput) const {
9010 ArgStringList CmdArgs;
9011
9012 // Add the output file name.
9013 assert(Output.isFilename() && "Invalid output.");
9014 CmdArgs.push_back(Elt: "-o");
9015 CmdArgs.push_back(Elt: Output.getFilename());
9016
9017 // Create the inputs to bundle the needed metadata.
9018 for (const InputInfo &Input : Inputs) {
9019 const Action *OffloadAction = Input.getAction();
9020 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9021 const ArgList &TCArgs =
9022 C.getArgsForToolChain(TC, BoundArch: OffloadAction->getOffloadingArch(),
9023 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9024 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9025 StringRef Arch = OffloadAction->getOffloadingArch()
9026 ? OffloadAction->getOffloadingArch()
9027 : TCArgs.getLastArgValue(options::OPT_march_EQ);
9028 StringRef Kind =
9029 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9030
9031 ArgStringList Features;
9032 SmallVector<StringRef> FeatureArgs;
9033 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9034 ForAS: false);
9035 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9036 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9037
9038 // TODO: We need to pass in the full target-id and handle it properly in the
9039 // linker wrapper.
9040 SmallVector<std::string> Parts{
9041 "file=" + File.str(),
9042 "triple=" + TC->getTripleString(),
9043 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9044 "kind=" + Kind.str(),
9045 };
9046
9047 if (TC->getDriver().isUsingOffloadLTO())
9048 for (StringRef Feature : FeatureArgs)
9049 Parts.emplace_back(Args: "feature=" + Feature.str());
9050
9051 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9052 }
9053
9054 C.addCommand(C: std::make_unique<Command>(
9055 args: JA, args: *this, args: ResponseFileSupport::None(),
9056 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9057 args&: CmdArgs, args: Inputs, args: Output));
9058}
9059
9060void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9061 const InputInfo &Output,
9062 const InputInfoList &Inputs,
9063 const ArgList &Args,
9064 const char *LinkingOutput) const {
9065 using namespace options;
9066
9067 // A list of permitted options that will be forwarded to the embedded device
9068 // compilation job.
9069 const llvm::DenseSet<unsigned> CompilerOptions{
9070 OPT_v,
9071 OPT_cuda_path_EQ,
9072 OPT_rocm_path_EQ,
9073 OPT_O_Group,
9074 OPT_g_Group,
9075 OPT_g_flags_Group,
9076 OPT_R_value_Group,
9077 OPT_R_Group,
9078 OPT_Xcuda_ptxas,
9079 OPT_ftime_report,
9080 OPT_ftime_trace,
9081 OPT_ftime_trace_EQ,
9082 OPT_ftime_trace_granularity_EQ,
9083 OPT_ftime_trace_verbose,
9084 OPT_opt_record_file,
9085 OPT_opt_record_format,
9086 OPT_opt_record_passes,
9087 OPT_fsave_optimization_record,
9088 OPT_fsave_optimization_record_EQ,
9089 OPT_fno_save_optimization_record,
9090 OPT_foptimization_record_file_EQ,
9091 OPT_foptimization_record_passes_EQ,
9092 OPT_save_temps,
9093 OPT_save_temps_EQ,
9094 OPT_mcode_object_version_EQ,
9095 OPT_load,
9096 OPT_fno_lto,
9097 OPT_flto,
9098 OPT_flto_partitions_EQ,
9099 OPT_flto_EQ};
9100 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9101 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A) {
9102 return Set.contains(V: A->getOption().getID()) ||
9103 (A->getOption().getGroup().isValid() &&
9104 Set.contains(V: A->getOption().getGroup().getID()));
9105 };
9106
9107 ArgStringList CmdArgs;
9108 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9109 Action::OFK_HIP, Action::OFK_SYCL}) {
9110 auto TCRange = C.getOffloadToolChains(Kind);
9111 for (auto &I : llvm::make_range(p: TCRange)) {
9112 const ToolChain *TC = I.second;
9113
9114 // We do not use a bound architecture here so options passed only to a
9115 // specific architecture via -Xarch_<cpu> will not be forwarded.
9116 ArgStringList CompilerArgs;
9117 ArgStringList LinkerArgs;
9118 for (Arg *A : C.getArgsForToolChain(TC, /*BoundArch=*/"", DeviceOffloadKind: Kind)) {
9119 if (A->getOption().matches(OPT_Zlinker_input))
9120 LinkerArgs.emplace_back(Args: A->getValue());
9121 else if (ShouldForward(CompilerOptions, A))
9122 A->render(Args, Output&: CompilerArgs);
9123 else if (ShouldForward(LinkerOptions, A))
9124 A->render(Args, Output&: LinkerArgs);
9125 }
9126
9127 // If this is OpenMP the device linker will need `-lompdevice`.
9128 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9129 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9130 LinkerArgs.emplace_back(Args: "-lompdevice");
9131
9132 // Forward all of these to the appropriate toolchain.
9133 for (StringRef Arg : CompilerArgs)
9134 CmdArgs.push_back(Elt: Args.MakeArgString(
9135 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9136 for (StringRef Arg : LinkerArgs)
9137 CmdArgs.push_back(Elt: Args.MakeArgString(
9138 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9139
9140 // Forward the LTO mode relying on the Driver's parsing.
9141 if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9142 CmdArgs.push_back(Elt: Args.MakeArgString(
9143 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9144 else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9145 CmdArgs.push_back(Elt: Args.MakeArgString(
9146 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9147 if (TC->getTriple().isAMDGPU()) {
9148 CmdArgs.push_back(
9149 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9150 "=-plugin-opt=-force-import-all"));
9151 CmdArgs.push_back(
9152 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9153 "=-plugin-opt=-avail-extern-to-local"));
9154 if (Kind == Action::OFK_OpenMP) {
9155 CmdArgs.push_back(
9156 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9157 "=-plugin-opt=-amdgpu-internalize-symbols"));
9158 }
9159 }
9160 }
9161 }
9162 }
9163
9164 CmdArgs.push_back(
9165 Elt: Args.MakeArgString(Str: "--host-triple=" + getToolChain().getTripleString()));
9166 if (Args.hasArg(options::OPT_v))
9167 CmdArgs.push_back(Elt: "--wrapper-verbose");
9168 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ))
9169 CmdArgs.push_back(
9170 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9171
9172 // Construct the link job so we can wrap around it.
9173 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9174 const auto &LinkCommand = C.getJobs().getJobs().back();
9175
9176 // Forward -Xoffload-linker<-triple> arguments to the device link job.
9177 for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
9178 StringRef Val = A->getValue(0);
9179 if (Val.empty())
9180 CmdArgs.push_back(
9181 Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
9182 else
9183 CmdArgs.push_back(Args.MakeArgString(
9184 "--device-linker=" +
9185 ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
9186 A->getValue(1)));
9187 }
9188 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9189
9190 // Embed bitcode instead of an object in JIT mode.
9191 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9192 options::OPT_fno_openmp_target_jit, false))
9193 CmdArgs.push_back(Elt: "--embed-bitcode");
9194
9195 // Save temporary files created by the linker wrapper.
9196 if (Args.hasArg(options::OPT_save_temps_EQ) ||
9197 Args.hasArg(options::OPT_save_temps))
9198 CmdArgs.push_back(Elt: "--save-temps");
9199
9200 // Pass in the C library for GPUs if present and not disabled.
9201 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
9202 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
9203 options::OPT_nodefaultlibs, options::OPT_nolibc,
9204 options::OPT_nogpulibc)) {
9205 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9206 // The device C library is only available for NVPTX and AMDGPU targets
9207 // currently.
9208 if (!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU())
9209 return;
9210 bool HasLibC = TC.getStdlibIncludePath().has_value();
9211 if (HasLibC) {
9212 CmdArgs.push_back(Elt: Args.MakeArgString(
9213 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9214 CmdArgs.push_back(Elt: Args.MakeArgString(
9215 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9216 }
9217 auto HasCompilerRT = getToolChain().getVFS().exists(
9218 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static));
9219 if (HasCompilerRT)
9220 CmdArgs.push_back(
9221 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9222 "-lclang_rt.builtins"));
9223 bool HasFlangRT = HasCompilerRT && C.getDriver().IsFlangMode();
9224 if (HasFlangRT)
9225 CmdArgs.push_back(
9226 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9227 "-lflang_rt.runtime"));
9228 });
9229 }
9230
9231 // Add the linker arguments to be forwarded by the wrapper.
9232 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
9233 LinkCommand->getExecutable()));
9234 for (const char *LinkArg : LinkCommand->getArguments())
9235 CmdArgs.push_back(Elt: LinkArg);
9236
9237 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
9238
9239 if (Arg *A = Args.getLastArg(options::OPT_offload_jobs_EQ)) {
9240 int NumThreads;
9241 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: NumThreads) ||
9242 NumThreads <= 0)
9243 C.getDriver().Diag(diag::err_drv_invalid_int_value)
9244 << A->getAsString(Args) << A->getValue();
9245 else
9246 CmdArgs.push_back(
9247 Elt: Args.MakeArgString(Str: "--wrapper-jobs=" + Twine(NumThreads)));
9248 }
9249
9250 const char *Exec =
9251 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
9252
9253 // Replace the executable and arguments of the link job with the
9254 // wrapper.
9255 LinkCommand->replaceExecutable(Exe: Exec);
9256 LinkCommand->replaceArguments(List: CmdArgs);
9257}
9258

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang/lib/Driver/ToolChains/Clang.cpp