clang 24.0.0git
Clang.cpp
Go to the documentation of this file.
1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
28#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
30#include "clang/Driver/Action.h"
32#include "clang/Driver/Distro.h"
35#include "clang/Driver/Types.h"
39#include "llvm/ADT/ScopeExit.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/BinaryFormat/Magic.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/Frontend/Debug/Options.h"
45#include "llvm/Object/ObjectFile.h"
46#include "llvm/Option/ArgList.h"
47#include "llvm/ProfileData/InstrProfReader.h"
48#include "llvm/Support/CodeGen.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64#include <iterator>
65#include <optional>
66
67using namespace clang::driver;
68using namespace clang::driver::tools;
69using namespace clang;
70using namespace llvm::opt;
71
72static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
73 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,
74 options::OPT_fminimize_whitespace,
75 options::OPT_fno_minimize_whitespace,
76 options::OPT_fkeep_system_includes,
77 options::OPT_fno_keep_system_includes)) {
78 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
79 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
80 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
81 << A->getBaseArg().getAsString(Args)
82 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
83 }
84 }
85}
86
87static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
88 // In gcc, only ARM checks this, but it seems reasonable to check universally.
89 if (Args.hasArg(options::OPT_static))
90 if (const Arg *A =
91 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
92 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
93 << "-static";
94}
95
96/// Apply \a Work on the current tool chain \a RegularToolChain and any other
97/// offloading tool chain that is associated with the current action \a JA.
98static void
100 const ToolChain &RegularToolChain,
101 llvm::function_ref<void(const ToolChain &)> Work) {
102 // Apply Work on the current/regular tool chain.
103 Work(RegularToolChain);
104
105 // Apply Work on all the offloading tool chains associated with the current
106 // action.
109 if (JA.isHostOffloading(Kind)) {
110 auto TCs = C.getOffloadToolChains(Kind);
111 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
112 Work(*II->second);
113 } else if (JA.isDeviceOffloading(Kind))
114 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
115 }
116}
117
118static bool
120 const llvm::Triple &Triple) {
121 // We use the zero-cost exception tables for Objective-C if the non-fragile
122 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
123 // later.
124 if (runtime.isNonFragile())
125 return true;
126
127 if (!Triple.isMacOSX())
128 return false;
129
130 return (!Triple.isMacOSXVersionLT(10, 5) &&
131 (Triple.getArch() == llvm::Triple::x86_64 ||
132 Triple.getArch() == llvm::Triple::arm));
133}
134
135/// Adds exception related arguments to the driver command arguments. There's a
136/// main flag, -fexceptions and also language specific flags to enable/disable
137/// C++ and Objective-C exceptions. This makes it possible to for example
138/// disable C++ exceptions but enable Objective-C exceptions.
139static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
140 const ToolChain &TC, bool KernelOrKext,
141 bool IsDeviceOffloadAction,
142 const ObjCRuntime &objcRuntime,
143 ArgStringList &CmdArgs) {
144 const llvm::Triple &Triple = TC.getTriple();
145
146 if (KernelOrKext) {
147 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
148 // arguments now to avoid warnings about unused arguments.
149 Args.ClaimAllArgs(options::OPT_fexceptions);
150 Args.ClaimAllArgs(options::OPT_fno_exceptions);
151 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
152 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
153 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
154 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
155 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
156 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
157 return false;
158 }
159
160 // See if the user explicitly enabled exceptions.
161 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
162 false);
163
164 // Async exceptions are Windows MSVC only.
165 if (Triple.isWindowsMSVCEnvironment()) {
166 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
167 options::OPT_fno_async_exceptions, false);
168 if (EHa) {
169 CmdArgs.push_back("-fasync-exceptions");
170 EH = true;
171 }
172 }
173
174 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
175 // is not necessarily sensible, but follows GCC.
176 if (types::isObjC(InputType) &&
177 Args.hasFlag(options::OPT_fobjc_exceptions,
178 options::OPT_fno_objc_exceptions, true)) {
179 CmdArgs.push_back("-fobjc-exceptions");
180
181 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
182 }
183
184 if (types::isCXX(InputType)) {
185 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
186 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
187 !Triple.isPS() && !Triple.isDriverKit() &&
188 !(Triple.isGPU() && !IsDeviceOffloadAction);
189 Arg *ExceptionArg = Args.getLastArg(
190 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
191 options::OPT_fexceptions, options::OPT_fno_exceptions);
192 if (ExceptionArg)
193 CXXExceptionsEnabled =
194 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
195 ExceptionArg->getOption().matches(options::OPT_fexceptions);
196
197 if (CXXExceptionsEnabled) {
198 CmdArgs.push_back("-fcxx-exceptions");
199
200 EH = true;
201 }
202 }
203
204 // OPT_fignore_exceptions means exception could still be thrown,
205 // but no clean up or catch would happen in current module.
206 // So we do not set EH to false.
207 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
208
209 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
210 options::OPT_fno_assume_nothrow_exception_dtor);
211
212 if (EH)
213 CmdArgs.push_back("-fexceptions");
214 return EH;
215}
216
217static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
218 const JobAction &JA) {
219 bool Default = true;
220 if (TC.getTriple().isOSDarwin()) {
221 // The native darwin assembler doesn't support the linker_option directives,
222 // so we disable them if we think the .s file will be passed to it.
224 }
225 // The linker_option directives are intended for host compilation.
228 Default = false;
229 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
230 Default);
231}
232
233/// Add a CC1 option to specify the debug compilation directory.
234static const char *addDebugCompDirArg(const ArgList &Args,
235 ArgStringList &CmdArgs,
236 const llvm::vfs::FileSystem &VFS) {
237 std::string DebugCompDir;
238 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
239 options::OPT_fdebug_compilation_dir_EQ))
240 DebugCompDir = A->getValue();
241
242 if (DebugCompDir.empty()) {
243 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
244 DebugCompDir = std::move(*CWD);
245 else
246 return nullptr;
247 }
248 CmdArgs.push_back(
249 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
250 StringRef Path(CmdArgs.back());
251 return Path.substr(Path.find('=') + 1).data();
252}
253
254static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
255 const char *DebugCompilationDir,
256 const char *OutputFileName) {
257 // No need to generate a value for -object-file-name if it was provided.
258 for (auto *Arg : Args.filtered(options::OPT_Xclang))
259 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
260 return;
261
262 if (Args.hasArg(options::OPT_object_file_name_EQ))
263 return;
264
265 SmallString<128> ObjFileNameForDebug(OutputFileName);
266 if (ObjFileNameForDebug != "-" &&
267 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
268 (!DebugCompilationDir ||
269 llvm::sys::path::is_absolute(DebugCompilationDir))) {
270 // Make the path absolute in the debug infos like MSVC does.
271 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
272 }
273 // If the object file name is a relative path, then always use Windows
274 // backslash style as -object-file-name is used for embedding object file path
275 // in codeview and it can only be generated when targeting on Windows.
276 // Otherwise, just use native absolute path.
277 llvm::sys::path::Style Style =
278 llvm::sys::path::is_absolute(ObjFileNameForDebug)
279 ? llvm::sys::path::Style::native
280 : llvm::sys::path::Style::windows_backslash;
281 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
282 Style);
283 CmdArgs.push_back(
284 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
285}
286
287/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
288static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
289 const ArgList &Args, ArgStringList &CmdArgs) {
290 auto AddOneArg = [&](StringRef Map, StringRef Name) {
291 if (!Map.contains('='))
292 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
293 else
294 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
295 };
296
297 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
298 options::OPT_fdebug_prefix_map_EQ)) {
299 AddOneArg(A->getValue(), A->getOption().getName());
300 A->claim();
301 }
302 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
303 if (GlobalRemapEntry.empty())
304 return;
305 AddOneArg(GlobalRemapEntry, "environment");
306}
307
308/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
309static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
310 ArgStringList &CmdArgs) {
311 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
312 options::OPT_fmacro_prefix_map_EQ)) {
313 StringRef Map = A->getValue();
314 if (!Map.contains('='))
315 D.Diag(diag::err_drv_invalid_argument_to_option)
316 << Map << A->getOption().getName();
317 else
318 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
319 A->claim();
320 }
321}
322
323/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
324static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
325 ArgStringList &CmdArgs) {
326 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
327 options::OPT_fcoverage_prefix_map_EQ)) {
328 StringRef Map = A->getValue();
329 if (!Map.contains('='))
330 D.Diag(diag::err_drv_invalid_argument_to_option)
331 << Map << A->getOption().getName();
332 else
333 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
334 A->claim();
335 }
336}
337
338/// Add -x lang to \p CmdArgs for \p Input.
339static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
340 ArgStringList &CmdArgs) {
341 // When using -verify-pch, we don't want to provide the type
342 // 'precompiled-header' if it was inferred from the file extension
343 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
344 return;
345
346 CmdArgs.push_back("-x");
347 if (Args.hasArg(options::OPT_rewrite_objc))
348 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
349 else {
350 // Map the driver type to the frontend type. This is mostly an identity
351 // mapping, except that the distinction between module interface units
352 // and other source files does not exist at the frontend layer.
353 const char *ClangType;
354 switch (Input.getType()) {
355 case types::TY_CXXModule:
356 case types::TY_CXXStdModule:
357 ClangType = "c++";
358 break;
359 case types::TY_PP_CXXModule:
360 ClangType = "c++-cpp-output";
361 break;
362 case types::TY_CIRBC:
363 ClangType = "cir";
364 break;
365 default:
366 ClangType = types::getTypeName(Input.getType());
367 break;
368 }
369 CmdArgs.push_back(ClangType);
370 }
371}
372
374 const JobAction &JA, const InputInfo &Output,
375 const ArgList &Args, SanitizerArgs &SanArgs,
376 ArgStringList &CmdArgs) {
377 const Driver &D = TC.getDriver();
378 const llvm::Triple &T = TC.getTriple();
379 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
380 options::OPT_fprofile_generate_EQ,
381 options::OPT_fno_profile_generate);
382 if (PGOGenerateArg &&
383 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
384 PGOGenerateArg = nullptr;
385
386 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
387
388 auto *ProfileGenerateArg = Args.getLastArg(
389 options::OPT_fprofile_instr_generate,
390 options::OPT_fprofile_instr_generate_EQ,
391 options::OPT_fno_profile_instr_generate);
392 if (ProfileGenerateArg &&
393 ProfileGenerateArg->getOption().matches(
394 options::OPT_fno_profile_instr_generate))
395 ProfileGenerateArg = nullptr;
396
397 if (PGOGenerateArg && ProfileGenerateArg)
398 D.Diag(diag::err_drv_argument_not_allowed_with)
399 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
400
401 auto *ProfileUseArg = getLastProfileUseArg(Args);
402
403 if (PGOGenerateArg && ProfileUseArg)
404 D.Diag(diag::err_drv_argument_not_allowed_with)
405 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
406
407 if (ProfileGenerateArg && ProfileUseArg)
408 D.Diag(diag::err_drv_argument_not_allowed_with)
409 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
410
411 if (CSPGOGenerateArg && PGOGenerateArg) {
412 D.Diag(diag::err_drv_argument_not_allowed_with)
413 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
414 PGOGenerateArg = nullptr;
415 }
416
417 if (TC.getTriple().isOSAIX()) {
418 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
419 D.Diag(diag::err_drv_unsupported_opt_for_target)
420 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
421 }
422
423 if (ProfileGenerateArg) {
424 if (ProfileGenerateArg->getOption().matches(
425 options::OPT_fprofile_instr_generate_EQ))
426 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
427 ProfileGenerateArg->getValue()));
428 // The default is to use Clang Instrumentation.
429 CmdArgs.push_back("-fprofile-instrument=clang");
430 if (TC.getTriple().isWindowsMSVCEnvironment() &&
431 Args.hasFlag(options::OPT_frtlib_defaultlib,
432 options::OPT_fno_rtlib_defaultlib, true)) {
433 // Add dependent lib for clang_rt.profile
434 CmdArgs.push_back(Args.MakeArgString(
435 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
436 }
437 }
438
439 if (auto *ColdFuncCoverageArg = Args.getLastArg(
440 options::OPT_fprofile_generate_cold_function_coverage,
441 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
442 SmallString<128> Path(
443 ColdFuncCoverageArg->getOption().matches(
444 options::OPT_fprofile_generate_cold_function_coverage_EQ)
445 ? ColdFuncCoverageArg->getValue()
446 : "");
447 llvm::sys::path::append(Path, "default_%m.profraw");
448 // FIXME: Idealy the file path should be passed through
449 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
450 // shared with other profile use path(see PGOOptions), we need to refactor
451 // PGOOptions to make it work.
452 CmdArgs.push_back("-mllvm");
453 CmdArgs.push_back(Args.MakeArgString(
454 Twine("--instrument-cold-function-only-path=") + Path));
455 CmdArgs.push_back("-mllvm");
456 CmdArgs.push_back("--pgo-instrument-cold-function-only");
457 CmdArgs.push_back("-mllvm");
458 CmdArgs.push_back("--pgo-function-entry-coverage");
459 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
460 }
461
462 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
463 if (!PGOGenerateArg && !CSPGOGenerateArg)
464 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
465 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
466 CmdArgs.push_back("-mllvm");
467 CmdArgs.push_back("--pgo-temporal-instrumentation");
468 }
469
470 Arg *PGOGenArg = nullptr;
471 if (PGOGenerateArg) {
472 assert(!CSPGOGenerateArg);
473 PGOGenArg = PGOGenerateArg;
474 CmdArgs.push_back("-fprofile-instrument=llvm");
475 }
476 if (CSPGOGenerateArg) {
477 assert(!PGOGenerateArg);
478 PGOGenArg = CSPGOGenerateArg;
479 CmdArgs.push_back("-fprofile-instrument=csllvm");
480 }
481 if (PGOGenArg) {
482 if (TC.getTriple().isWindowsMSVCEnvironment() &&
483 Args.hasFlag(options::OPT_frtlib_defaultlib,
484 options::OPT_fno_rtlib_defaultlib, true)) {
485 // Add dependent lib for clang_rt.profile
486 CmdArgs.push_back(Args.MakeArgString(
487 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
488 }
489 if (PGOGenArg->getOption().matches(
490 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
491 : options::OPT_fcs_profile_generate_EQ)) {
492 SmallString<128> Path(PGOGenArg->getValue());
493 llvm::sys::path::append(Path, "default_%m.profraw");
494 CmdArgs.push_back(
495 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
496 }
497 }
498
499 if (ProfileUseArg) {
500 SmallString<128> UsePathBuf;
501 StringRef UsePath;
502 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
503 UsePath = ProfileUseArg->getValue();
504 else if ((ProfileUseArg->getOption().matches(
505 options::OPT_fprofile_use_EQ) ||
506 ProfileUseArg->getOption().matches(
507 options::OPT_fprofile_instr_use))) {
508 UsePathBuf =
509 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
510 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
511 llvm::sys::path::append(UsePathBuf, "default.profdata");
512 UsePath = UsePathBuf;
513 }
514 auto ReaderOrErr =
515 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
516 if (auto E = ReaderOrErr.takeError()) {
517 auto DiagID = D.getDiags().getCustomDiagID(
518 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
519 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
520 D.Diag(DiagID) << UsePath.str() << EI.message();
521 });
522 } else {
523 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
524 std::move(ReaderOrErr.get());
525 StringRef UseKind;
526 // Currently memprof profiles are only added at the IR level. Mark the
527 // profile type as IR in that case as well and the subsequent matching
528 // needs to detect which is available (might be one or both).
529 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
530 if (PGOReader->hasCSIRLevelProfile())
531 UseKind = "csllvm";
532 else
533 UseKind = "llvm";
534 } else
535 UseKind = "clang";
536
537 CmdArgs.push_back(
538 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
539 CmdArgs.push_back(
540 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
541 }
542 }
543
544 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
545 options::OPT_fno_test_coverage, false) ||
546 Args.hasArg(options::OPT_coverage);
547 bool EmitCovData = TC.needsGCovInstrumentation(Args);
548
549 if (Args.hasFlag(options::OPT_fcoverage_mapping,
550 options::OPT_fno_coverage_mapping, false)) {
551 if (!ProfileGenerateArg)
552 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
553 << "-fcoverage-mapping"
554 << "-fprofile-instr-generate";
555
556 CmdArgs.push_back("-fcoverage-mapping");
557 }
558
559 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
560 false)) {
561 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
562 options::OPT_fno_coverage_mapping, false))
563 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
564 << "-fcoverage-mcdc"
565 << "-fcoverage-mapping";
566
567 CmdArgs.push_back("-fcoverage-mcdc");
568 }
569
570 StringRef CoverageCompDir;
571 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
572 options::OPT_fcoverage_compilation_dir_EQ))
573 CoverageCompDir = A->getValue();
574 if (CoverageCompDir.empty()) {
575 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
576 CmdArgs.push_back(
577 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
578 } else
579 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
580 CoverageCompDir));
581
582 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
583 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
584 if (!Args.hasArg(options::OPT_coverage))
585 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
586 << "-fprofile-exclude-files="
587 << "--coverage";
588
589 StringRef v = Arg->getValue();
590 CmdArgs.push_back(
591 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
592 }
593
594 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
595 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
596 if (!Args.hasArg(options::OPT_coverage))
597 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
598 << "-fprofile-filter-files="
599 << "--coverage";
600
601 StringRef v = Arg->getValue();
602 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
603 }
604
605 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
606 StringRef Val = A->getValue();
607 if (Val == "atomic" || Val == "prefer-atomic")
608 CmdArgs.push_back("-fprofile-update=atomic");
609 else if (Val == "single") {
610 if (SanArgs.needsTsanRt() &&
611 (PGOGenerateArg || CSPGOGenerateArg || ProfileGenerateArg)) {
612 // Under TSan, instrprof defaults to atomic counter updates to avoid
613 // data race reports on profile counters; override that default and
614 // warn.
615 D.Diag(diag::warn_drv_tsan_profile_update_single)
616 << A->getAsString(Args);
617 CmdArgs.push_back("-mllvm");
618 CmdArgs.push_back("-instrprof-atomic-counter-update-all=false");
619 }
620 } else
621 D.Diag(diag::err_drv_unsupported_option_argument)
622 << A->getSpelling() << Val;
623 }
624 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
625 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
626 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
627 << A->getSpelling()
628 << "-fprofile-generate, -fprofile-instr-generate, or "
629 "-fcs-profile-generate";
630 else {
631 CmdArgs.push_back("-fprofile-continuous");
632 // Platforms that require a bias variable:
633 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
634 CmdArgs.push_back("-mllvm");
635 CmdArgs.push_back("-runtime-counter-relocation");
636 }
637 // -fprofile-instr-generate does not decide the profile file name in the
638 // FE, and so it does not define the filename symbol
639 // (__llvm_profile_filename). Instead, the runtime uses the name
640 // "default.profraw" for the profile file. When continuous mode is ON, we
641 // will create the filename symbol so that we can insert the "%c"
642 // modifier.
643 if (ProfileGenerateArg &&
644 (ProfileGenerateArg->getOption().matches(
645 options::OPT_fprofile_instr_generate) ||
646 (ProfileGenerateArg->getOption().matches(
647 options::OPT_fprofile_instr_generate_EQ) &&
648 strlen(ProfileGenerateArg->getValue()) == 0)))
649 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
650 }
651 }
652
653 int FunctionGroups = 1;
654 int SelectedFunctionGroup = 0;
655 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
656 StringRef Val = A->getValue();
657 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
658 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
659 }
660 if (const auto *A =
661 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
662 StringRef Val = A->getValue();
663 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
664 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
665 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
666 }
667 if (FunctionGroups != 1)
668 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
669 Twine(FunctionGroups)));
670 if (SelectedFunctionGroup != 0)
671 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
672 Twine(SelectedFunctionGroup)));
673
674 // Leave -fprofile-dir= an unused argument unless .gcda emission is
675 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
676 // the flag used. There is no -fno-profile-dir, so the user has no
677 // targeted way to suppress the warning.
678 Arg *FProfileDir = nullptr;
679 if (Args.hasArg(options::OPT_fprofile_arcs) ||
680 Args.hasArg(options::OPT_coverage))
681 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
682
683 // Put the .gcno and .gcda files (if needed) next to the primary output file,
684 // or fall back to a file in the current directory for `clang -c --coverage
685 // d/a.c` in the absence of -o.
686 if (EmitCovNotes || EmitCovData) {
687 SmallString<128> CoverageFilename;
688 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
689 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
690 // path separator.
691 CoverageFilename = DumpDir->getValue();
692 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
693 } else if (Arg *FinalOutput =
694 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
695 CoverageFilename = FinalOutput->getValue();
696 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
697 CoverageFilename = FinalOutput->getValue();
698 } else {
699 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
700 }
701 if (llvm::sys::path::is_relative(CoverageFilename))
702 (void)D.getVFS().makeAbsolute(CoverageFilename);
703 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
704 if (EmitCovNotes) {
705 CmdArgs.push_back(
706 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
707
708 bool UseAbsolutePathsInNotes =
709 Args.hasFlag(options::OPT_fprofile_abs_path,
710 options::OPT_fno_profile_abs_path, false);
711 if (UseAbsolutePathsInNotes)
712 CmdArgs.push_back(Args.MakeArgString("-coverage-notes-abs-paths"));
713 }
714
715 if (EmitCovData) {
716 if (FProfileDir) {
717 SmallString<128> Gcno = std::move(CoverageFilename);
718 CoverageFilename = FProfileDir->getValue();
719 llvm::sys::path::append(CoverageFilename, Gcno);
720 }
721 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
722 CmdArgs.push_back(
723 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
724 }
725 }
726}
727
728static void
729RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
730 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
731 unsigned DwarfVersion,
732 llvm::DebuggerKind DebuggerTuning) {
733 addDebugInfoKind(CmdArgs, DebugInfoKind);
734 if (DwarfVersion > 0)
735 CmdArgs.push_back(
736 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
737 switch (DebuggerTuning) {
738 case llvm::DebuggerKind::GDB:
739 CmdArgs.push_back("-debugger-tuning=gdb");
740 break;
741 case llvm::DebuggerKind::LLDB:
742 CmdArgs.push_back("-debugger-tuning=lldb");
743 break;
744 case llvm::DebuggerKind::SCE:
745 CmdArgs.push_back("-debugger-tuning=sce");
746 break;
747 case llvm::DebuggerKind::DBX:
748 CmdArgs.push_back("-debugger-tuning=dbx");
749 break;
750 default:
751 break;
752 }
753}
754
756 const ArgList &Args,
757 ArgStringList &CmdArgs,
758 bool IsCC1As = false) {
759 // If no version was requested by the user, use the default value from the
760 // back end. This is consistent with the value returned from
761 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
762 // requiring the corresponding llvm to have the AMDGPU target enabled,
763 // provided the user (e.g. front end tests) can use the default.
765 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
766 CmdArgs.insert(CmdArgs.begin() + 1,
767 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
768 Twine(CodeObjVer)));
769 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
770 // -cc1as does not accept -mcode-object-version option.
771 if (!IsCC1As)
772 CmdArgs.insert(CmdArgs.begin() + 1,
773 Args.MakeArgString(Twine("-mcode-object-version=") +
774 Twine(CodeObjVer)));
775 }
776}
777
778static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
779 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
780 D.getVFS().getBufferForFile(Path);
781 if (!MemBuf)
782 return false;
783 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
784 if (Magic == llvm::file_magic::unknown)
785 return false;
786 // Return true for both raw Clang AST files and object files which may
787 // contain a __clangast section.
788 if (Magic == llvm::file_magic::clang_ast)
789 return true;
791 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
792 return !Obj.takeError();
793}
794
795static bool gchProbe(const Driver &D, StringRef Path) {
796 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
797 if (!Status)
798 return false;
799
800 if (Status->isDirectory()) {
801 std::error_code EC;
802 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
803 !EC && DI != DE; DI = DI.increment(EC)) {
804 if (maybeHasClangPchSignature(D, DI->path()))
805 return true;
806 }
807 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
808 return false;
809 }
810
811 if (maybeHasClangPchSignature(D, Path))
812 return true;
813 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
814 return false;
815}
816
817void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
818 const Driver &D, const ArgList &Args,
819 ArgStringList &CmdArgs,
820 const InputInfo &Output,
821 const InputInfoList &Inputs) const {
822 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
823
825
826 Args.AddLastArg(CmdArgs, options::OPT_C);
827 Args.AddLastArg(CmdArgs, options::OPT_CC);
828
829 // Handle dependency file generation.
830 Arg *ArgM = Args.getLastArg(options::OPT_MM);
831 if (!ArgM)
832 ArgM = Args.getLastArg(options::OPT_M);
833 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
834 if (!ArgMD)
835 ArgMD = Args.getLastArg(options::OPT_MD);
836
837 // -M and -MM imply -w.
838 if (ArgM)
839 CmdArgs.push_back("-w");
840 else
841 ArgM = ArgMD;
842
843 if (ArgM) {
845 // Determine the output location.
846 const char *DepFile;
847 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
848 DepFile = MF->getValue();
849 C.addFailureResultFile(DepFile, &JA);
850 } else if (Output.getType() == types::TY_Dependencies) {
851 DepFile = Output.getFilename();
852 } else if (!ArgMD) {
853 DepFile = "-";
854 } else {
855 DepFile = getDependencyFileName(Args, Inputs);
856 C.addFailureResultFile(DepFile, &JA);
857 }
858 CmdArgs.push_back("-dependency-file");
859 CmdArgs.push_back(DepFile);
860 }
861 // Cmake generates dependency files using all compilation options specified
862 // by users. Claim those not used for dependency files.
864 Args.ClaimAllArgs(options::OPT_offload_compress);
865 Args.ClaimAllArgs(options::OPT_no_offload_compress);
866 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
867 }
868
869 bool HasTarget = false;
870 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
871 HasTarget = true;
872 A->claim();
873 if (A->getOption().matches(options::OPT_MT)) {
874 A->render(Args, CmdArgs);
875 } else {
876 CmdArgs.push_back("-MT");
877 SmallString<128> Quoted;
878 quoteMakeTarget(A->getValue(), Quoted);
879 CmdArgs.push_back(Args.MakeArgString(Quoted));
880 }
881 }
882
883 // Add a default target if one wasn't specified.
884 if (!HasTarget) {
885 const char *DepTarget;
886
887 // If user provided -o, that is the dependency target, except
888 // when we are only generating a dependency file.
889 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
890 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
891 DepTarget = OutputOpt->getValue();
892 } else {
893 // Otherwise derive from the base input.
894 //
895 // FIXME: This should use the computed output file location.
896 SmallString<128> P(Inputs[0].getBaseInput());
897 llvm::sys::path::replace_extension(P, "o");
898 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
899 }
900
901 CmdArgs.push_back("-MT");
902 SmallString<128> Quoted;
903 quoteMakeTarget(DepTarget, Quoted);
904 CmdArgs.push_back(Args.MakeArgString(Quoted));
905 }
906
907 if (ArgM->getOption().matches(options::OPT_M) ||
908 ArgM->getOption().matches(options::OPT_MD))
909 CmdArgs.push_back("-sys-header-deps");
910
911 // Determine module file deps mode.
912 StringRef ModuleFileDepsVal;
913 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
914 options::OPT_fmodule_file_deps,
915 options::OPT_fno_module_file_deps)) {
916 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
917 ModuleFileDepsVal = A->getValue();
918 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
919 ModuleFileDepsVal = "all";
920 else
921 ModuleFileDepsVal = "none";
922 } else if (isa<PrecompileJobAction>(JA)) {
923 ModuleFileDepsVal = "all";
924 }
925 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
926 CmdArgs.push_back(
927 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
928 }
929
930 if (Args.hasArg(options::OPT_MG)) {
931 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
932 ArgM->getOption().matches(options::OPT_MMD))
933 D.Diag(diag::err_drv_mg_requires_m_or_mm);
934 CmdArgs.push_back("-MG");
935 }
936
937 Args.AddLastArg(CmdArgs, options::OPT_MP);
938 Args.AddLastArg(CmdArgs, options::OPT_MV);
939
940 bool UsesLLVMOffloading = Args.hasFlag(
941 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
942 bool UsesOffloadInclude =
943 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc, true);
944 bool NoBuiltinInc = Args.hasArg(options::OPT_nobuiltininc);
945
946 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
947 // want to pull in our wrappers instead of the vendor headers.
948 if (UsesLLVMOffloading) {
949 if (UsesOffloadInclude && !NoBuiltinInc) {
950 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
951 StringRef RuntimeHeader) {
952 SmallString<128> OffloadInclude(D.Dir);
953 llvm::sys::path::append(OffloadInclude, "..", "include", "offload");
954 if (!IncludeSubdir.empty())
955 llvm::sys::path::append(OffloadInclude, IncludeSubdir);
956 CmdArgs.append({"-internal-isystem", Args.MakeArgString(OffloadInclude),
957 "-include", Args.MakeArgString(RuntimeHeader)});
958 };
959 auto AddForcedInclude = [&](StringRef Header) {
960 CmdArgs.push_back("-include");
961 CmdArgs.push_back(Args.MakeArgString(Header));
962 };
963 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
964 AddForcedInclude("__clang_gpu_builtin_vars.h");
965 AddForcedInclude("__clang_gpu_device_functions.h");
966 AddForcedInclude("__clang_gpu_intrinsics.h");
968 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
970 !Args.hasArg(options::OPT_nohipwrapperinc)) {
971 // HIP code commonly includes this as "hip/hip_runtime.h".
972 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
973 }
974 }
975 } else {
976 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
977 // happen before we -I or -include anything else, because we must pick up
978 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
979 // installation, rather than from e.g. /usr/local/include.
981 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
983 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
985 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
986
987 // If we are offloading to a target via OpenMP we need to include the
988 // openmp_wrappers folder which contains alternative system headers.
990 !Args.hasArg(options::OPT_nostdinc) && UsesOffloadInclude &&
991 getToolChain().getTriple().isGPU()) {
992 if (!NoBuiltinInc) {
993 // Add openmp_wrappers/* to our system include path. This lets us
994 // wrap standard library headers.
995 SmallString<128> P(D.ResourceDir);
996 llvm::sys::path::append(P, "include");
997 llvm::sys::path::append(P, "openmp_wrappers");
998 CmdArgs.push_back("-internal-isystem");
999 CmdArgs.push_back(Args.MakeArgString(P));
1000 }
1001
1002 CmdArgs.push_back("-include");
1003 CmdArgs.push_back("__clang_openmp_device_functions.h");
1004 }
1005 }
1006
1007 // Add -i* options, and automatically translate to
1008 // -include-pch/-include-pth for transparent PCH support. It's
1009 // wonky, but we include looking for .gch so we can support seamless
1010 // replacement into a build system already set up to be generating
1011 // .gch files.
1012
1013 if (getToolChain().getDriver().IsCLMode()) {
1014 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1015 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1016 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1018 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1019 // -fpch-instantiate-templates is the default when creating
1020 // precomp using /Yc
1021 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1022 options::OPT_fno_pch_instantiate_templates, true))
1023 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1024 }
1025 if (YcArg || YuArg) {
1026 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1027 if (!isa<PrecompileJobAction>(JA)) {
1028 CmdArgs.push_back("-include-pch");
1029 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1030 C, !ThroughHeader.empty()
1031 ? ThroughHeader
1032 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1033 }
1034
1035 if (ThroughHeader.empty()) {
1036 CmdArgs.push_back(Args.MakeArgString(
1037 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1038 } else {
1039 CmdArgs.push_back(
1040 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1041 }
1042 }
1043 }
1044
1045 bool RenderedImplicitInclude = false;
1046 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1047 if (A->getOption().matches(options::OPT_include) &&
1048 D.getProbePrecompiled()) {
1049 // Handling of gcc-style gch precompiled headers.
1050 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1051 RenderedImplicitInclude = true;
1052
1053 bool FoundPCH = false;
1054 SmallString<128> P(A->getValue());
1055 // We want the files to have a name like foo.h.pch. Add a dummy extension
1056 // so that replace_extension does the right thing.
1057 P += ".dummy";
1058 llvm::sys::path::replace_extension(P, "pch");
1059 if (D.getVFS().exists(P))
1060 FoundPCH = true;
1061
1062 if (!FoundPCH) {
1063 // For GCC compat, probe for a file or directory ending in .gch instead.
1064 llvm::sys::path::replace_extension(P, "gch");
1065 FoundPCH = gchProbe(D, P.str());
1066 }
1067
1068 if (FoundPCH) {
1069 if (IsFirstImplicitInclude) {
1070 A->claim();
1071 CmdArgs.push_back("-include-pch");
1072 CmdArgs.push_back(Args.MakeArgString(P));
1073 continue;
1074 } else {
1075 // Ignore the PCH if not first on command line and emit warning.
1076 D.Diag(diag::warn_drv_pch_not_first_include) << P
1077 << A->getAsString(Args);
1078 }
1079 }
1080 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1081 // Handling of paths which must come late. These entries are handled by
1082 // the toolchain itself after the resource dir is inserted in the right
1083 // search order.
1084 // Do not claim the argument so that the use of the argument does not
1085 // silently go unnoticed on toolchains which do not honour the option.
1086 continue;
1087 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1088 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1089 continue;
1090 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1091 // This is used only by the driver. No need to pass to cc1.
1092 continue;
1093 }
1094
1095 // Not translated, render as usual.
1096 A->claim();
1097 A->render(Args, CmdArgs);
1098 }
1099
1100 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1102 // Collect all enabled NVPTX architectures.
1103 std::set<unsigned> ArchIDs;
1104 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1105 const ToolChain *TC = I.second;
1106 for (BoundArch Arch :
1107 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1108 if (Arch.Arch.isNVPTX())
1109 ArchIDs.insert(CudaArchToID(Arch.Arch));
1110 }
1111 }
1112
1113 if (!ArchIDs.empty()) {
1114 SmallString<128> List;
1115 llvm::raw_svector_ostream OS(List);
1116 llvm::interleave(ArchIDs, OS, ",");
1117 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1118 }
1119 }
1120
1121 Args.addAllArgs(CmdArgs,
1122 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1123 options::OPT_F, options::OPT_embed_dir_EQ});
1124
1125 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1126
1127 // FIXME: There is a very unfortunate problem here, some troubled
1128 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1129 // really support that we would have to parse and then translate
1130 // those options. :(
1131 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1132 options::OPT_Xpreprocessor);
1133
1134 // -I- is a deprecated GCC feature, reject it.
1135 if (Arg *A = Args.getLastArg(options::OPT_I_))
1136 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1137
1138 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1139 // -isysroot to the CC1 invocation.
1140 StringRef sysroot = C.getSysRoot();
1141 if (sysroot != "") {
1142 if (!Args.hasArg(options::OPT_isysroot)) {
1143 CmdArgs.push_back("-isysroot");
1144 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1145 }
1146 }
1147
1148 // Parse additional include paths from environment variables.
1149 // FIXME: We should probably sink the logic for handling these from the
1150 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1151 // CPATH - included following the user specified includes (but prior to
1152 // builtin and standard includes).
1153 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1154 // C_INCLUDE_PATH - system includes enabled when compiling C.
1155 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1156 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1157 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1158 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1159 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1160 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1161 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1162
1163 // While adding the include arguments, we also attempt to retrieve the
1164 // arguments of related offloading toolchains or arguments that are specific
1165 // of an offloading programming model.
1166
1167 // Add C++ include arguments, if needed.
1168 if (types::isCXX(Inputs[0].getType())) {
1169 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1171 C, JA, getToolChain(),
1172 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1173 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1174 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1175 });
1176 }
1177
1178 // If we are compiling for a GPU target with the LLVM environment we want to
1179 // override the system headers with ones created by the 'libc' project if
1180 // present.
1181 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1182 // OffloadKind as an argument.
1183 bool OffloadUsesLLVMLibc =
1184 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1185 (C.getActiveOffloadKinds() != Action::OFK_None &&
1186 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1187 if (!Args.hasArg(options::OPT_nostdinc) &&
1188 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1189 true) &&
1190 !Args.hasArg(options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1191 SmallString<128> P(D.ResourceDir);
1192 llvm::sys::path::append(P, "include");
1193 llvm::sys::path::append(P, "llvm_libc_wrappers");
1194 CmdArgs.push_back("-internal-isystem");
1195 CmdArgs.push_back(Args.MakeArgString(P));
1196 }
1197
1198 // Add system include arguments for all targets but IAMCU.
1199 if (!IsIAMCU)
1201 [&Args, &CmdArgs](const ToolChain &TC) {
1202 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1203 });
1204 else {
1205 // For IAMCU add special include arguments.
1206 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1207 }
1208
1209 addMacroPrefixMapArg(D, Args, CmdArgs);
1210 addCoveragePrefixMapArg(D, Args, CmdArgs);
1211
1212 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1213 options::OPT_fno_file_reproducible);
1214
1215 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1216 CmdArgs.push_back("-source-date-epoch");
1217 CmdArgs.push_back(Args.MakeArgString(Epoch));
1218 }
1219
1220 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1221 options::OPT_fno_define_target_os_macros);
1222}
1223
1224// FIXME: Move to target hook.
1225static bool isSignedCharDefault(const llvm::Triple &Triple) {
1226 switch (Triple.getArch()) {
1227 default:
1228 return true;
1229
1230 case llvm::Triple::aarch64:
1231 case llvm::Triple::aarch64_32:
1232 case llvm::Triple::aarch64_be:
1233 case llvm::Triple::arm:
1234 case llvm::Triple::armeb:
1235 case llvm::Triple::thumb:
1236 case llvm::Triple::thumbeb:
1237 if (Triple.isOSDarwin() || Triple.isOSWindowsOrUEFI())
1238 return true;
1239 return false;
1240
1241 case llvm::Triple::ppc:
1242 case llvm::Triple::ppc64:
1243 if (Triple.isOSDarwin())
1244 return true;
1245 return false;
1246
1247 case llvm::Triple::csky:
1248 case llvm::Triple::hexagon:
1249 case llvm::Triple::msp430:
1250 case llvm::Triple::ppcle:
1251 case llvm::Triple::ppc64le:
1252 case llvm::Triple::riscv32:
1253 case llvm::Triple::riscv64:
1254 case llvm::Triple::riscv32be:
1255 case llvm::Triple::riscv64be:
1256 case llvm::Triple::systemz:
1257 case llvm::Triple::xcore:
1258 case llvm::Triple::xtensa:
1259 return false;
1260 }
1261}
1262
1263static bool hasMultipleInvocations(const llvm::Triple &Triple,
1264 const ArgList &Args) {
1265 // Supported only on Darwin where we invoke the compiler multiple times
1266 // followed by an invocation to lipo.
1267 if (!Triple.isOSDarwin())
1268 return false;
1269 // If more than one "-arch <arch>" is specified, we're targeting multiple
1270 // architectures resulting in a fat binary.
1271 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1272}
1273
1274static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1275 const llvm::Triple &Triple) {
1276 // When enabling remarks, we need to error if:
1277 // * The remark file is specified but we're targeting multiple architectures,
1278 // which means more than one remark file is being generated.
1280 bool hasExplicitOutputFile =
1281 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1282 if (hasMultipleInvocations && hasExplicitOutputFile) {
1283 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1284 << "-foptimization-record-file";
1285 return false;
1286 }
1287 return true;
1288}
1289
1290static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1291 const llvm::Triple &Triple,
1292 const InputInfo &Input,
1293 const InputInfo &Output, const JobAction &JA) {
1294 StringRef Format = "yaml";
1295 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1296 Format = A->getValue();
1297
1298 CmdArgs.push_back("-opt-record-file");
1299
1300 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1301 if (A) {
1302 CmdArgs.push_back(A->getValue());
1303 } else {
1304 bool hasMultipleArchs =
1305 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1306 Args.getAllArgValues(options::OPT_arch).size() > 1;
1307
1309
1310 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1311 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1312 F = FinalOutput->getValue();
1313 } else {
1314 if (Format != "yaml" && // For YAML, keep the original behavior.
1315 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1316 Output.isFilename())
1317 F = Output.getFilename();
1318 }
1319
1320 if (F.empty()) {
1321 // Use the input filename.
1322 F = llvm::sys::path::stem(Input.getBaseInput());
1323
1324 // If we're compiling for an offload architecture (i.e. a CUDA device),
1325 // we need to make the file name for the device compilation different
1326 // from the host compilation.
1329 llvm::sys::path::replace_extension(F, "");
1331 Triple.str());
1332 F += "-";
1333 F += JA.getOffloadingArch().ArchName;
1334 }
1335 }
1336
1337 // If we're having more than one "-arch", we should name the files
1338 // differently so that every cc1 invocation writes to a different file.
1339 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1340 // name from the triple.
1341 if (hasMultipleArchs) {
1342 // First, remember the extension.
1343 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1344 // then, remove it.
1345 llvm::sys::path::replace_extension(F, "");
1346 // attach -<arch> to it.
1347 F += "-";
1348 F += Triple.getArchName();
1349 // put back the extension.
1350 llvm::sys::path::replace_extension(F, OldExtension);
1351 }
1352
1353 SmallString<32> Extension;
1354 Extension += "opt.";
1355 Extension += Format;
1356
1357 llvm::sys::path::replace_extension(F, Extension);
1358 CmdArgs.push_back(Args.MakeArgString(F));
1359 }
1360
1361 if (const Arg *A =
1362 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1363 CmdArgs.push_back("-opt-record-passes");
1364 CmdArgs.push_back(A->getValue());
1365 }
1366
1367 if (!Format.empty()) {
1368 CmdArgs.push_back("-opt-record-format");
1369 CmdArgs.push_back(Format.data());
1370 }
1371}
1372
1373void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1374 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1375 options::OPT_fno_aapcs_bitfield_width, true))
1376 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1377
1378 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1379 CmdArgs.push_back("-faapcs-bitfield-load");
1380}
1381
1382namespace {
1383void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1384 const ArgList &Args, ArgStringList &CmdArgs) {
1385 // Select the ABI to use.
1386 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1387 const char *ABIName = nullptr;
1388 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1389 ABIName = A->getValue();
1390 else
1391 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1392
1393 CmdArgs.push_back("-target-abi");
1394 CmdArgs.push_back(ABIName);
1395}
1396
1397void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1398 auto StrictAlignIter =
1399 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1400 return Arg == "+strict-align" || Arg == "-strict-align";
1401 });
1402 if (StrictAlignIter != CmdArgs.rend() &&
1403 StringRef(*StrictAlignIter) == "+strict-align")
1404 CmdArgs.push_back("-Wunaligned-access");
1405}
1406}
1407
1408static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1409 ArgStringList &CmdArgs, bool isAArch64) {
1410 const llvm::Triple &Triple = TC.getEffectiveTriple();
1411 const Arg *A = isAArch64
1412 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1413 options::OPT_mbranch_protection_EQ)
1414 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1415 const Arg *HardenPACRetArg = Args.getLastArg(options::OPT_mharden_pac_ret_EQ);
1416 const Driver &D = TC.getDriver();
1417
1418 if (HardenPACRetArg) {
1419 if (!isAArch64) {
1420 D.Diag(diag::err_drv_unsupported_opt_for_target)
1421 << HardenPACRetArg->getSpelling() << TC.getTriple().str();
1422 return;
1423 }
1424 StringRef ArgValue = HardenPACRetArg->getValue();
1425 if (ArgValue != "none" && ArgValue != "load-return-address") {
1426 D.Diag(diag::err_drv_unsupported_option_argument)
1427 << HardenPACRetArg->getSpelling() << ArgValue;
1428 return;
1429 }
1430 if (ArgValue != "none" &&
1431 Args.hasFlagNoClaim(options::OPT_mexecute_only,
1432 options::OPT_mno_execute_only, false)) {
1433 D.Diag(diag::err_drv_incompatible_options)
1434 << HardenPACRetArg->getAsString(Args) << "-mexecute-only";
1435 return;
1436 }
1437 }
1438
1439 // Check CmdArgs because some toolchains bypass the driver args and add to
1440 // the frontend args directly.
1441 bool HasPtrauthReturns =
1442 llvm::is_contained(CmdArgs, StringRef("-fptrauth-returns")) ||
1443 Args.hasFlagNoClaim(options::OPT_fptrauth_returns,
1444 options::OPT_fno_ptrauth_returns, false);
1445
1446 auto RenderHardenPACRet = [&](StringRef Scope) {
1447 if (!HardenPACRetArg)
1448 return;
1449 if (Scope == "none" && !HasPtrauthReturns)
1450 D.Diag(diag::warn_harden_pac_ret_requires_pac_ret);
1451 else
1452 CmdArgs.push_back(Args.MakeArgString(Twine("-mharden-pac-ret=") +
1453 HardenPACRetArg->getValue()));
1454 };
1455
1456 if (!A) {
1457 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1458 CmdArgs.push_back("-msign-return-address=non-leaf");
1459 CmdArgs.push_back("-msign-return-address-key=a_key");
1460 CmdArgs.push_back("-mbranch-target-enforce");
1461 RenderHardenPACRet("non-leaf");
1462 } else {
1463 RenderHardenPACRet("none");
1464 }
1465 return;
1466 }
1467
1468 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1469 D.Diag(diag::warn_incompatible_branch_protection_option)
1470 << Triple.getArchName();
1471
1472 StringRef Scope, Key;
1473 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1474
1475 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1476 Scope = A->getValue();
1477 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1478 D.Diag(diag::err_drv_unsupported_option_argument)
1479 << A->getSpelling() << Scope;
1480 // This spelling cannot express a key, and AArch64 Windows and UEFI only
1481 // support B-key, so default to it there as parseBranchProtection() does.
1482 Key = isAArch64 && Triple.isOSWindowsOrUEFI() ? "b_key" : "a_key";
1483 IndirectBranches =
1484 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1485 BranchProtectionPAuthLR = false;
1486 GuardedControlStack = false;
1487 } else {
1488 StringRef DiagMsg;
1489 llvm::ARM::ParsedBranchProtection PBP;
1490 bool EnablePAuthLR = false;
1491
1492 // To know if we need to enable PAuth-LR As part of the standard branch
1493 // protection option, it needs to be determined if the feature has been
1494 // activated in the `march` argument. This information is stored within the
1495 // CmdArgs variable and can be found using a search.
1496 if (isAArch64) {
1497 auto isPAuthLR = [](const char *member) {
1498 llvm::AArch64::ExtensionInfo pauthlr_extension =
1499 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1500 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1501 member;
1502 };
1503
1504 if (llvm::any_of(CmdArgs, isPAuthLR))
1505 EnablePAuthLR = true;
1506 }
1507 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1508 EnablePAuthLR))
1509 D.Diag(diag::err_drv_unsupported_option_argument)
1510 << A->getSpelling() << DiagMsg;
1511 if (!isAArch64 && PBP.Key == "b_key")
1512 D.Diag(diag::warn_unsupported_branch_protection)
1513 << "b-key" << A->getAsString(Args);
1514 Scope = PBP.Scope;
1515 Key = PBP.Key;
1516 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1517 IndirectBranches = PBP.BranchTargetEnforcement;
1518 GuardedControlStack = PBP.GuardedControlStack;
1519 }
1520
1521 // GCS is currently untested with ptrauth-returns, but enabling this could be
1522 // allowed in future after testing with a suitable system.
1523 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1524 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1525 D.Diag(diag::err_drv_unsupported_opt_for_target)
1526 << A->getAsString(Args) << Triple.getTriple();
1527 else if (HasPtrauthReturns)
1528 D.Diag(diag::err_drv_incompatible_options)
1529 << A->getAsString(Args) << "-fptrauth-returns";
1530 }
1531
1532 CmdArgs.push_back(
1533 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1534 if (Scope != "none")
1535 CmdArgs.push_back(
1536 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1537 if (BranchProtectionPAuthLR)
1538 CmdArgs.push_back(
1539 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1540 if (IndirectBranches)
1541 CmdArgs.push_back("-mbranch-target-enforce");
1542
1543 if (GuardedControlStack)
1544 CmdArgs.push_back("-mguarded-control-stack");
1545
1546 RenderHardenPACRet(Scope);
1547}
1548
1549void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1550 ArgStringList &CmdArgs, bool KernelOrKext) const {
1551 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1552
1553 // Determine floating point ABI from the options & target defaults.
1555 if (ABI == arm::FloatABI::Soft) {
1556 // Floating point operations and argument passing are soft.
1557 // FIXME: This changes CPP defines, we need -target-soft-float.
1558 CmdArgs.push_back("-msoft-float");
1559 CmdArgs.push_back("-mfloat-abi");
1560 CmdArgs.push_back("soft");
1561 } else if (ABI == arm::FloatABI::SoftFP) {
1562 // Floating point operations are hard, but argument passing is soft.
1563 CmdArgs.push_back("-mfloat-abi");
1564 CmdArgs.push_back("soft");
1565 } else {
1566 // Floating point operations and argument passing are hard.
1567 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1568 CmdArgs.push_back("-mfloat-abi");
1569 CmdArgs.push_back("hard");
1570 }
1571
1572 // Forward the -mglobal-merge option for explicit control over the pass.
1573 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1574 options::OPT_mno_global_merge)) {
1575 CmdArgs.push_back("-mllvm");
1576 if (A->getOption().matches(options::OPT_mno_global_merge))
1577 CmdArgs.push_back("-arm-global-merge=false");
1578 else
1579 CmdArgs.push_back("-arm-global-merge=true");
1580 }
1581
1582 if (!Args.hasFlag(options::OPT_mimplicit_float,
1583 options::OPT_mno_implicit_float, true))
1584 CmdArgs.push_back("-no-implicit-float");
1585
1586 if (Args.getLastArg(options::OPT_mcmse))
1587 CmdArgs.push_back("-mcmse");
1588
1589 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1590
1591 // Enable/disable return address signing and indirect branch targets.
1592 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1593
1594 AddUnalignedAccessWarning(CmdArgs);
1595}
1596
1597void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1598 ArgStringList &CmdArgs) const {
1599 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1600 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1601 A->render(Args, CmdArgs);
1602 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1603 A->render(Args, CmdArgs);
1604}
1605
1606void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1607 const ArgList &Args, bool KernelOrKext,
1608 ArgStringList &CmdArgs) const {
1609 const ToolChain &TC = getToolChain();
1610
1611 // Add the target features
1612 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1613
1614 // Add target specific flags.
1615 switch (TC.getArch()) {
1616 default:
1617 break;
1618
1619 case llvm::Triple::arm:
1620 case llvm::Triple::armeb:
1621 case llvm::Triple::thumb:
1622 case llvm::Triple::thumbeb:
1623 // Use the effective triple, which takes into account the deployment target.
1624 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1625 break;
1626
1627 case llvm::Triple::aarch64:
1628 case llvm::Triple::aarch64_32:
1629 case llvm::Triple::aarch64_be:
1630 AddAArch64TargetArgs(Args, CmdArgs);
1631 break;
1632
1633 case llvm::Triple::amdgpu:
1634 AddAMDGPUTargetArgs(Args, CmdArgs);
1635 break;
1636
1637 case llvm::Triple::loongarch32:
1638 case llvm::Triple::loongarch64:
1639 AddLoongArchTargetArgs(Args, CmdArgs);
1640 break;
1641
1642 case llvm::Triple::mips:
1643 case llvm::Triple::mipsel:
1644 case llvm::Triple::mips64:
1645 case llvm::Triple::mips64el:
1646 AddMIPSTargetArgs(Args, CmdArgs);
1647 break;
1648
1649 case llvm::Triple::ppc:
1650 case llvm::Triple::ppcle:
1651 case llvm::Triple::ppc64:
1652 case llvm::Triple::ppc64le:
1653 AddPPCTargetArgs(Args, CmdArgs);
1654 break;
1655
1656 case llvm::Triple::riscv32:
1657 case llvm::Triple::riscv64:
1658 case llvm::Triple::riscv32be:
1659 case llvm::Triple::riscv64be:
1660 AddRISCVTargetArgs(Args, CmdArgs);
1661 break;
1662
1663 case llvm::Triple::sparc:
1664 case llvm::Triple::sparcel:
1665 case llvm::Triple::sparcv9:
1666 AddSparcTargetArgs(Args, CmdArgs);
1667 break;
1668
1669 case llvm::Triple::systemz:
1670 AddSystemZTargetArgs(Args, CmdArgs);
1671 break;
1672
1673 case llvm::Triple::x86:
1674 case llvm::Triple::x86_64:
1675 AddX86TargetArgs(Args, CmdArgs);
1676 break;
1677
1678 case llvm::Triple::lanai:
1679 AddLanaiTargetArgs(Args, CmdArgs);
1680 break;
1681
1682 case llvm::Triple::hexagon:
1683 AddHexagonTargetArgs(Args, CmdArgs);
1684 break;
1685
1686 case llvm::Triple::wasm32:
1687 case llvm::Triple::wasm64:
1688 AddWebAssemblyTargetArgs(Args, CmdArgs);
1689 break;
1690
1691 case llvm::Triple::ve:
1692 AddVETargetArgs(Args, CmdArgs);
1693 break;
1694
1695 case llvm::Triple::bpfel:
1696 case llvm::Triple::bpfeb:
1697 Args.AddAllArgs(CmdArgs, options::OPT_fbpf_no_enum_reloc_EQ);
1698 break;
1699 }
1700}
1701
1702namespace {
1703void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1704 ArgStringList &CmdArgs) {
1705 const char *ABIName = nullptr;
1706 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1707 ABIName = A->getValue();
1708 else if (Triple.isOSDarwin())
1709 ABIName = "darwinpcs";
1710 // TODO: we probably want to have some target hook here.
1711 else if (Triple.isOSLinux() &&
1712 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1713 ABIName = "pauthtest";
1714 else
1715 ABIName = "aapcs";
1716
1717 CmdArgs.push_back("-target-abi");
1718 CmdArgs.push_back(ABIName);
1719}
1720}
1721
1722void Clang::AddAArch64TargetArgs(const ArgList &Args,
1723 ArgStringList &CmdArgs) const {
1724 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1725
1726 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1727 Args.hasArg(options::OPT_mkernel) ||
1728 Args.hasArg(options::OPT_fapple_kext))
1729 CmdArgs.push_back("-disable-red-zone");
1730
1731 if (!Args.hasFlag(options::OPT_mimplicit_float,
1732 options::OPT_mno_implicit_float, true))
1733 CmdArgs.push_back("-no-implicit-float");
1734
1735 RenderAArch64ABI(Triple, Args, CmdArgs);
1736
1737 // Forward the -mglobal-merge option for explicit control over the pass.
1738 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1739 options::OPT_mno_global_merge)) {
1740 CmdArgs.push_back("-mllvm");
1741 if (A->getOption().matches(options::OPT_mno_global_merge))
1742 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1743 else
1744 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1745 }
1746
1747 // Handle -msve_vector_bits=<bits>
1748 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1749 StringRef VScaleMax) {
1750 StringRef Val = A->getValue();
1751 const Driver &D = getToolChain().getDriver();
1752 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1753 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1754 Val == "1024+" || Val == "2048+") {
1755 unsigned Bits = 0;
1756 if (!Val.consume_back("+")) {
1757 bool Invalid = Val.getAsInteger(10, Bits);
1758 (void)Invalid;
1759 assert(!Invalid && "Failed to parse value");
1760 CmdArgs.push_back(
1761 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1762 }
1763
1764 bool Invalid = Val.getAsInteger(10, Bits);
1765 (void)Invalid;
1766 assert(!Invalid && "Failed to parse value");
1767
1768 CmdArgs.push_back(
1769 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1770 } else if (Val == "scalable") {
1771 // Silently drop requests for vector-length agnostic code as it's implied.
1772 } else {
1773 // Handle the unsupported values passed to msve-vector-bits.
1774 D.Diag(diag::err_drv_unsupported_option_argument)
1775 << A->getSpelling() << Val;
1776 }
1777 };
1778 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1779 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1780 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1781 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1782
1783 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1784
1785 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1786 CmdArgs.push_back("-tune-cpu");
1787 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1788 }
1789
1790 AddUnalignedAccessWarning(CmdArgs);
1791
1792 if (Triple.isOSDarwin() ||
1793 (Triple.isOSLinux() &&
1794 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1795 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1796 options::OPT_fno_ptrauth_intrinsics);
1797 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1798 options::OPT_fno_ptrauth_calls);
1799 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1800 options::OPT_fno_ptrauth_returns);
1801 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1802 options::OPT_fno_ptrauth_auth_traps);
1803 Args.addOptInFlag(
1804 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1805 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1806 Args.addOptInFlag(
1807 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1808 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1809 Args.addOptInFlag(
1810 CmdArgs, options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1811 options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1812 Args.addOptInFlag(
1813 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1814 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1815 Args.addOptInFlag(
1816 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1817 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1818 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1819 options::OPT_fno_ptrauth_indirect_gotos);
1820 }
1821 if (Triple.isOSLinux() &&
1822 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1823 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1824 options::OPT_fno_ptrauth_init_fini);
1825 Args.addOptInFlag(
1826 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1827 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1828 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1829 options::OPT_fno_ptrauth_elf_got);
1830 }
1831 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1832 options::OPT_fno_aarch64_jump_table_hardening);
1833
1834 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1835 options::OPT_fno_ptrauth_objc_isa);
1836 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1837 options::OPT_fno_ptrauth_objc_interface_sel);
1838 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1839 options::OPT_fno_ptrauth_objc_class_ro);
1840
1841 // Enable/disable return address signing and indirect branch targets.
1842 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1843}
1844
1845void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1846 ArgStringList &CmdArgs) const {
1847 const llvm::Triple &Triple = getToolChain().getTriple();
1848
1849 CmdArgs.push_back("-target-abi");
1850 CmdArgs.push_back(
1851 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1852 .data());
1853
1854 // Handle -mtune.
1855 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1856 std::string TuneCPU = A->getValue();
1857 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1858 CmdArgs.push_back("-tune-cpu");
1859 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1860 }
1861
1862 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1863 options::OPT_mno_annotate_tablejump)) {
1864 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1865 CmdArgs.push_back("-mllvm");
1866 CmdArgs.push_back("-loongarch-annotate-tablejump");
1867 }
1868 }
1869}
1870
1871void Clang::AddMIPSTargetArgs(const ArgList &Args,
1872 ArgStringList &CmdArgs) const {
1873 const Driver &D = getToolChain().getDriver();
1874 StringRef CPUName;
1875 StringRef ABIName;
1876 const llvm::Triple &Triple = getToolChain().getTriple();
1877 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1878
1879 CmdArgs.push_back("-target-abi");
1880 CmdArgs.push_back(ABIName.data());
1881
1882 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1883 if (ABI == mips::FloatABI::Soft) {
1884 // Floating point operations and argument passing are soft.
1885 CmdArgs.push_back("-msoft-float");
1886 CmdArgs.push_back("-mfloat-abi");
1887 CmdArgs.push_back("soft");
1888 } else {
1889 // Floating point operations and argument passing are hard.
1890 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1891 CmdArgs.push_back("-mfloat-abi");
1892 CmdArgs.push_back("hard");
1893 }
1894
1895 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1896 options::OPT_mno_ldc1_sdc1)) {
1897 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1898 CmdArgs.push_back("-mllvm");
1899 CmdArgs.push_back("-mno-ldc1-sdc1");
1900 }
1901 }
1902
1903 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1904 options::OPT_mno_check_zero_division)) {
1905 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1906 CmdArgs.push_back("-mllvm");
1907 CmdArgs.push_back("-mno-check-zero-division");
1908 }
1909 }
1910
1911 if (Args.getLastArg(options::OPT_mfix4300)) {
1912 CmdArgs.push_back("-mllvm");
1913 CmdArgs.push_back("-mfix4300");
1914 }
1915
1916 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1917 StringRef v = A->getValue();
1918 CmdArgs.push_back("-mllvm");
1919 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1920 A->claim();
1921 }
1922
1923 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1924 Arg *ABICalls =
1925 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1926
1927 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1928 // -mgpopt is the default for static, -fno-pic environments but these two
1929 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1930 // the only case where -mllvm -mgpopt is passed.
1931 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1932 // passed explicitly when compiling something with -mabicalls
1933 // (implictly) in affect. Currently the warning is in the backend.
1934 //
1935 // When the ABI in use is N64, we also need to determine the PIC mode that
1936 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1937 bool NoABICalls =
1938 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1939
1940 llvm::Reloc::Model RelocationModel;
1941 unsigned PICLevel;
1942 bool IsPIE;
1943 std::tie(RelocationModel, PICLevel, IsPIE) =
1944 ParsePICArgs(getToolChain(), Args);
1945
1946 NoABICalls = NoABICalls ||
1947 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1948
1949 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1950 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1951 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1952 CmdArgs.push_back("-mllvm");
1953 CmdArgs.push_back("-mgpopt");
1954
1955 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1956 options::OPT_mno_local_sdata);
1957 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1958 options::OPT_mno_extern_sdata);
1959 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1960 options::OPT_mno_embedded_data);
1961 if (LocalSData) {
1962 CmdArgs.push_back("-mllvm");
1963 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1964 CmdArgs.push_back("-mlocal-sdata=1");
1965 } else {
1966 CmdArgs.push_back("-mlocal-sdata=0");
1967 }
1968 LocalSData->claim();
1969 }
1970
1971 if (ExternSData) {
1972 CmdArgs.push_back("-mllvm");
1973 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1974 CmdArgs.push_back("-mextern-sdata=1");
1975 } else {
1976 CmdArgs.push_back("-mextern-sdata=0");
1977 }
1978 ExternSData->claim();
1979 }
1980
1981 if (EmbeddedData) {
1982 CmdArgs.push_back("-mllvm");
1983 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1984 CmdArgs.push_back("-membedded-data=1");
1985 } else {
1986 CmdArgs.push_back("-membedded-data=0");
1987 }
1988 EmbeddedData->claim();
1989 }
1990
1991 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1992 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1993
1994 if (GPOpt)
1995 GPOpt->claim();
1996
1997 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1998 StringRef Val = StringRef(A->getValue());
1999 if (mips::hasCompactBranches(CPUName)) {
2000 if (Val == "never" || Val == "always" || Val == "optimal") {
2001 CmdArgs.push_back("-mllvm");
2002 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2003 } else
2004 D.Diag(diag::err_drv_unsupported_option_argument)
2005 << A->getSpelling() << Val;
2006 } else
2007 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2008 }
2009
2010 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2011 options::OPT_mno_relax_pic_calls)) {
2012 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2013 CmdArgs.push_back("-mllvm");
2014 CmdArgs.push_back("-mips-jalr-reloc=0");
2015 }
2016 }
2017}
2018
2019void Clang::AddPPCTargetArgs(const ArgList &Args,
2020 ArgStringList &CmdArgs) const {
2021 const Driver &D = getToolChain().getDriver();
2022 const llvm::Triple &T = getToolChain().getTriple();
2023 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2024 CmdArgs.push_back("-tune-cpu");
2025 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
2026 CmdArgs.push_back(Args.MakeArgString(CPU));
2027 }
2028
2029 // Select the ABI to use.
2030 const char *ABIName = nullptr;
2031 if (T.isOSBinFormatELF()) {
2032 switch (getToolChain().getArch()) {
2033 case llvm::Triple::ppc64: {
2034 if (T.isPPC64ELFv2ABI())
2035 ABIName = "elfv2";
2036 else
2037 ABIName = "elfv1";
2038 break;
2039 }
2040 case llvm::Triple::ppc64le:
2041 ABIName = "elfv2";
2042 break;
2043 default:
2044 break;
2045 }
2046 }
2047
2048 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2049 bool VecExtabi = false;
2050 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2051 StringRef V = A->getValue();
2052 if (V == "ieeelongdouble") {
2053 IEEELongDouble = true;
2054 A->claim();
2055 } else if (V == "ibmlongdouble") {
2056 IEEELongDouble = false;
2057 A->claim();
2058 } else if (V == "vec-default") {
2059 VecExtabi = false;
2060 A->claim();
2061 } else if (V == "vec-extabi") {
2062 VecExtabi = true;
2063 A->claim();
2064 } else if (V == "elfv1") {
2065 ABIName = "elfv1";
2066 A->claim();
2067 } else if (V == "elfv2") {
2068 ABIName = "elfv2";
2069 A->claim();
2070 } else if (V != "altivec")
2071 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2072 // the option if given as we don't have backend support for any targets
2073 // that don't use the altivec abi.
2074 ABIName = A->getValue();
2075 }
2076 if (IEEELongDouble)
2077 CmdArgs.push_back("-mabi=ieeelongdouble");
2078 if (VecExtabi) {
2079 if (!T.isOSAIX())
2080 D.Diag(diag::err_drv_unsupported_opt_for_target)
2081 << "-mabi=vec-extabi" << T.str();
2082 CmdArgs.push_back("-mabi=vec-extabi");
2083 }
2084
2085 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2086 CmdArgs.push_back("-disable-red-zone");
2087
2089 if (FloatABI == ppc::FloatABI::Soft) {
2090 // Floating point operations and argument passing are soft.
2091 CmdArgs.push_back("-msoft-float");
2092 CmdArgs.push_back("-mfloat-abi");
2093 CmdArgs.push_back("soft");
2094 } else {
2095 // Floating point operations and argument passing are hard.
2096 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2097 CmdArgs.push_back("-mfloat-abi");
2098 CmdArgs.push_back("hard");
2099 }
2100
2101 if (ABIName) {
2102 CmdArgs.push_back("-target-abi");
2103 CmdArgs.push_back(ABIName);
2104 }
2105}
2106
2107void Clang::AddRISCVTargetArgs(const ArgList &Args,
2108 ArgStringList &CmdArgs) const {
2109 const llvm::Triple &Triple = getToolChain().getTriple();
2110 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2111
2112 CmdArgs.push_back("-target-abi");
2113 CmdArgs.push_back(ABIName.data());
2114
2115 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2116 CmdArgs.push_back("-msmall-data-limit");
2117 CmdArgs.push_back(A->getValue());
2118 }
2119
2120 if (!Args.hasFlag(options::OPT_mimplicit_float,
2121 options::OPT_mno_implicit_float, true))
2122 CmdArgs.push_back("-no-implicit-float");
2123
2124 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2125 if (!TuneCPU)
2126 return;
2127 if (!TuneCPU->empty()) {
2128 CmdArgs.push_back("-tune-cpu");
2129 // TuneCPU might or might not be the original -mtune string, so we
2130 // have to create a new copy here.
2131 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2132 }
2133
2134 // Handle -mrvv-vector-bits=<bits>
2135 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2136 StringRef Val = A->getValue();
2137 const Driver &D = getToolChain().getDriver();
2138
2139 // Get minimum VLen from march.
2140 unsigned MinVLen = 0;
2141 std::string Arch = riscv::getRISCVArch(Args, Triple);
2142 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2143 Arch, /*EnableExperimentalExtensions*/ true);
2144 // Ignore parsing error.
2145 if (!errorToBool(ISAInfo.takeError()))
2146 MinVLen = (*ISAInfo)->getMinVLen();
2147
2148 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2149 // as integer as long as we have a MinVLen.
2150 unsigned Bits = 0;
2151 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2152 Bits = MinVLen;
2153 } else if (!Val.getAsInteger(10, Bits)) {
2154 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2155 // at least MinVLen.
2156 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2157 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2158 Bits = 0;
2159 }
2160
2161 // If we got a valid value try to use it.
2162 if (Bits != 0) {
2163 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2164 CmdArgs.push_back(
2165 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2166 CmdArgs.push_back(
2167 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2168 } else if (Val != "scalable") {
2169 // Handle the unsupported values passed to mrvv-vector-bits.
2170 D.Diag(diag::err_drv_unsupported_option_argument)
2171 << A->getSpelling() << Val;
2172 }
2173 }
2174}
2175
2176void Clang::AddSparcTargetArgs(const ArgList &Args,
2177 ArgStringList &CmdArgs) const {
2179 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2180
2181 if (FloatABI == sparc::FloatABI::Soft) {
2182 // Floating point operations and argument passing are soft.
2183 CmdArgs.push_back("-msoft-float");
2184 CmdArgs.push_back("-mfloat-abi");
2185 CmdArgs.push_back("soft");
2186 } else {
2187 // Floating point operations and argument passing are hard.
2188 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2189 CmdArgs.push_back("-mfloat-abi");
2190 CmdArgs.push_back("hard");
2191 }
2192
2193 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2194 StringRef Name = A->getValue();
2195 std::string TuneCPU;
2196 if (Name == "native")
2197 TuneCPU = std::string(llvm::sys::getHostCPUName());
2198 else
2199 TuneCPU = std::string(Name);
2200
2201 CmdArgs.push_back("-tune-cpu");
2202 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2203 }
2204}
2205
2206void Clang::AddSystemZTargetArgs(const ArgList &Args,
2207 ArgStringList &CmdArgs) const {
2208 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2209 CmdArgs.push_back("-tune-cpu");
2210 if (strcmp(A->getValue(), "native") == 0)
2211 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2212 else
2213 CmdArgs.push_back(A->getValue());
2214 }
2215
2216 bool HasBackchain =
2217 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2218 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2219 options::OPT_mno_packed_stack, false);
2221 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2222 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2223
2224 // Only hard float ABI (-mhard-float) is supported on z/OS.
2225 const Driver &D = getToolChain().getDriver();
2226 const llvm::Triple &Triple = getToolChain().getTriple();
2227 if (HasSoftFloat && Triple.isOSzOS()) {
2228 D.Diag(diag::err_drv_unsupported_opt_for_target)
2229 << "-msoft-float" << Triple.str();
2230 }
2231 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2232 D.Diag(diag::err_drv_unsupported_opt)
2233 << "-mpacked-stack -mbackchain -mhard-float";
2234 }
2235 if (HasBackchain)
2236 CmdArgs.push_back("-mbackchain");
2237 if (HasPackedStack)
2238 CmdArgs.push_back("-mpacked-stack");
2239 if (HasSoftFloat) {
2240 // Floating point operations and argument passing are soft.
2241 CmdArgs.push_back("-msoft-float");
2242 CmdArgs.push_back("-mfloat-abi");
2243 CmdArgs.push_back("soft");
2244 }
2245
2246 if (Triple.isOSzOS())
2247 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2248 options::OPT_mno_zos_ppa1_name);
2249}
2250
2251void Clang::AddX86TargetArgs(const ArgList &Args,
2252 ArgStringList &CmdArgs) const {
2253 const Driver &D = getToolChain().getDriver();
2254 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2255
2256 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2257 Args.hasArg(options::OPT_mkernel) ||
2258 Args.hasArg(options::OPT_fapple_kext))
2259 CmdArgs.push_back("-disable-red-zone");
2260
2261 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2262 options::OPT_mno_tls_direct_seg_refs, true))
2263 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2264
2265 // Default to avoid implicit floating-point for kernel/kext code, but allow
2266 // that to be overridden with -mno-soft-float.
2267 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2268 Args.hasArg(options::OPT_fapple_kext));
2269 if (Arg *A = Args.getLastArg(
2270 options::OPT_msoft_float, options::OPT_mno_soft_float,
2271 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2272 const Option &O = A->getOption();
2273 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2274 O.matches(options::OPT_msoft_float));
2275 }
2276 if (NoImplicitFloat)
2277 CmdArgs.push_back("-no-implicit-float");
2278
2279 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2280 StringRef Value = A->getValue();
2281 if (Value == "intel" || Value == "att") {
2282 CmdArgs.push_back("-mllvm");
2283 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2284 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2285 } else {
2286 D.Diag(diag::err_drv_unsupported_option_argument)
2287 << A->getSpelling() << Value;
2288 }
2289 } else if (D.IsCLMode()) {
2290 CmdArgs.push_back("-mllvm");
2291 CmdArgs.push_back("-x86-asm-syntax=intel");
2292 }
2293
2294 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2295 options::OPT_mno_skip_rax_setup))
2296 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2297 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2298
2299 // Set flags to support MCU ABI.
2300 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2301 CmdArgs.push_back("-mfloat-abi");
2302 CmdArgs.push_back("soft");
2303 CmdArgs.push_back("-mstack-alignment=4");
2304 }
2305
2306 // Handle -mtune.
2307
2308 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2309 std::string TuneCPU;
2310 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2311 TuneCPU = "generic";
2312
2313 // Override based on -mtune.
2314 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2315 StringRef Name = A->getValue();
2316
2317 if (Name == "native") {
2318 Name = llvm::sys::getHostCPUName();
2319 if (!Name.empty())
2320 TuneCPU = std::string(Name);
2321 } else
2322 TuneCPU = std::string(Name);
2323 }
2324
2325 if (!TuneCPU.empty()) {
2326 CmdArgs.push_back("-tune-cpu");
2327 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2328 }
2329}
2330
2331static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2332 size_t Index = Option.find(Delimiter);
2333 if (Index != StringRef::npos)
2334 Option = Option.substr(0, Index);
2335 return Option;
2336}
2337
2338static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2339 Opt = getOptionName(Opt);
2340 if (CmdArgs.size() < 2)
2341 return;
2342
2343 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2344 StringRef Option = *It;
2345 if (!Option.starts_with(Opt))
2346 continue;
2347 Option = getOptionName(Option);
2348 if (Option != Opt)
2349 continue;
2350 if (StringRef(*(It - 1)) != "-mllvm")
2351 continue;
2352
2353 It = CmdArgs.erase(It);
2354 CmdArgs.erase(It - 1);
2355 return;
2356 }
2357}
2358
2359static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2360 checkAndRemoveLLVMArg(CmdArgs, A);
2361 CmdArgs.push_back("-mllvm");
2362 CmdArgs.push_back(A);
2363}
2364
2365static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2366 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2367 StringRef Option = *It;
2368 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2369 It = CmdArgs.erase(It);
2370 Ie = CmdArgs.end();
2371 } else {
2372 ++It;
2373 }
2374 }
2375
2376 CmdArgs.push_back("-menable-no-infs");
2377 CmdArgs.push_back("-menable-no-nans");
2378 CmdArgs.push_back("-fapprox-func");
2379 CmdArgs.push_back("-funsafe-math-optimizations");
2380 CmdArgs.push_back("-fno-signed-zeros");
2381 CmdArgs.push_back("-mreassociate");
2382 CmdArgs.push_back("-freciprocal-math");
2383 CmdArgs.push_back("-ffp-contract=fast");
2384 CmdArgs.push_back("-ffast-math");
2385 CmdArgs.push_back("-ffinite-math-only");
2386 CmdArgs.push_back("-D__FAST_MATH__");
2387 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2388}
2389
2390static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2391 ArgStringList &CmdArgs) {
2392 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2393 bool HasHVX = HvxVerOpt.has_value();
2394 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2395 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2396 options::OPT_mhexagon_hvx_ieee_fp) ||
2397 !HasHVX)
2398 return;
2399 unsigned HvxVerNum = 0;
2400 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2401 HvxVerNum = 0;
2402
2403 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2404 options::OPT_mhexagon_hvx_qfloat_EQ,
2405 options::OPT_mhexagon_hvx_ieee_fp)) {
2406 if (HvxVerNum >= 79) {
2407 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2408 const char *Mode =
2409 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2410 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2411 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2412 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2413 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2414 .Default(nullptr);
2415 if (!Mode) {
2416 D.Diag(diag::err_drv_invalid_value)
2417 << A->getAsString(Args) << A->getValue();
2418 return;
2419 }
2420 pushBackLLVMArg(CmdArgs, Mode);
2421 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2423 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2424 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2426 } else {
2427 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2428 }
2429 } else {
2430 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2431 options::OPT_mhexagon_hvx_qfloat_EQ,
2432 options::OPT_mno_hexagon_hvx_qfloat);
2433 QFloatArg &&
2434 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2435 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2436 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2437 << (std::string("HVX ") + HvxVer +
2438 "; falling back to legacy qfloat mode");
2439 }
2440 }
2441 }
2442}
2443
2444void Clang::AddHexagonTargetArgs(const ArgList &Args,
2445 ArgStringList &CmdArgs) const {
2446 CmdArgs.push_back("-mqdsp6-compat");
2447 CmdArgs.push_back("-Wreturn-type");
2448
2450 CmdArgs.push_back("-mllvm");
2451 CmdArgs.push_back(
2452 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2453 }
2454
2455 if (!Args.hasArg(options::OPT_fno_short_enums))
2456 CmdArgs.push_back("-fshort-enums");
2457 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2458 CmdArgs.push_back("-mllvm");
2459 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2460 }
2461 CmdArgs.push_back("-mllvm");
2462 CmdArgs.push_back("-machine-sink-split=0");
2463
2464 // Let debuggers find the caller's HLX vector stack pointer.
2465 if (const Arg *A = Args.getLastArg(options::OPT_g_Group);
2466 A && !A->getOption().matches(options::OPT_g0) &&
2467 !A->getOption().matches(options::OPT_ggdb0)) {
2468 CmdArgs.push_back("-mllvm");
2469 CmdArgs.push_back("-hexagon-save-parent-vsp");
2470 }
2471
2472 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2473}
2474
2475void Clang::AddLanaiTargetArgs(const ArgList &Args,
2476 ArgStringList &CmdArgs) const {
2477 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2478 StringRef CPUName = A->getValue();
2479
2480 CmdArgs.push_back("-target-cpu");
2481 CmdArgs.push_back(Args.MakeArgString(CPUName));
2482 }
2483 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2484 StringRef Value = A->getValue();
2485 // Only support mregparm=4 to support old usage. Report error for all other
2486 // cases.
2487 int Mregparm;
2488 if (Value.getAsInteger(10, Mregparm)) {
2489 if (Mregparm != 4) {
2491 diag::err_drv_unsupported_option_argument)
2492 << A->getSpelling() << Value;
2493 }
2494 }
2495 }
2496}
2497
2498void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2499 ArgStringList &CmdArgs) const {
2500 // Default to "hidden" visibility.
2501 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2502 options::OPT_fvisibility_ms_compat))
2503 CmdArgs.push_back("-fvisibility=hidden");
2504}
2505
2506void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2507 // Floating point operations and argument passing are hard.
2508 CmdArgs.push_back("-mfloat-abi");
2509 CmdArgs.push_back("hard");
2510}
2511
2512void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2513 StringRef Target, const InputInfo &Output,
2514 const InputInfo &Input, const ArgList &Args) const {
2515 // If this is a dry run, do not create the compilation database file.
2516 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2517 return;
2518
2519 using llvm::yaml::escape;
2520 const Driver &D = getToolChain().getDriver();
2521
2522 if (!CompilationDatabase) {
2523 std::error_code EC;
2524 auto File = std::make_unique<llvm::raw_fd_ostream>(
2525 Filename, EC,
2526 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2527 if (EC) {
2528 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2529 << EC.message();
2530 return;
2531 }
2532 CompilationDatabase = std::move(File);
2533 }
2534 auto &CDB = *CompilationDatabase;
2535 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2536 if (!CWD)
2537 CWD = ".";
2538 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2539 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2540 if (Output.isFilename())
2541 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2542 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2543 SmallString<128> Buf;
2544 Buf = "-x";
2545 Buf += types::getTypeName(Input.getType());
2546 CDB << ", \"" << escape(Buf) << "\"";
2547 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2548 Buf = "--sysroot=";
2549 Buf += D.SysRoot;
2550 CDB << ", \"" << escape(Buf) << "\"";
2551 }
2552 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2553 if (Output.isFilename())
2554 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2555 for (auto &A: Args) {
2556 auto &O = A->getOption();
2557 // Skip language selection, which is positional.
2558 if (O.getID() == options::OPT_x)
2559 continue;
2560 // Skip writing dependency output and the compilation database itself.
2561 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2562 continue;
2563 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2564 continue;
2565 // Skip inputs.
2566 if (O.getKind() == Option::InputClass)
2567 continue;
2568 // Skip output.
2569 if (O.getID() == options::OPT_o)
2570 continue;
2571 // All other arguments are quoted and appended.
2572 ArgStringList ASL;
2573 A->render(Args, ASL);
2574 for (auto &it: ASL)
2575 CDB << ", \"" << escape(it) << "\"";
2576 }
2577 Buf = "--target=";
2578 Buf += Target;
2579 CDB << ", \"" << escape(Buf) << "\"]},\n";
2580}
2581
2582void Clang::DumpCompilationDatabaseFragmentToDir(
2583 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2584 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2585 // If this is a dry run, do not create the compilation database file.
2586 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2587 return;
2588
2589 if (CompilationDatabase)
2590 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2591
2592 SmallString<256> Path = Dir;
2593 const auto &Driver = C.getDriver();
2594 Driver.getVFS().makeAbsolute(Path);
2595 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2596 if (Err) {
2597 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2598 return;
2599 }
2600
2601 llvm::sys::path::append(
2602 Path,
2603 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2604 int FD;
2605 SmallString<256> TempPath;
2606 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2607 llvm::sys::fs::OF_Text);
2608 if (Err) {
2609 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2610 return;
2611 }
2612 CompilationDatabase =
2613 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2614 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2615}
2616
2617static bool CheckARMImplicitITArg(StringRef Value) {
2618 return Value == "always" || Value == "never" || Value == "arm" ||
2619 Value == "thumb";
2620}
2621
2622static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2623 StringRef Value) {
2624 CmdArgs.push_back("-mllvm");
2625 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2626}
2627
2629 const ArgList &Args,
2630 ArgStringList &CmdArgs,
2631 const Driver &D) {
2632 // Default to -mno-relax-all.
2633 //
2634 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2635 // cannot be done by assembler branch relaxation as it needs a free temporary
2636 // register. Because of this, branch relaxation is handled by a MachineIR pass
2637 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2638 // MachineIR branch relaxation inaccurate and it will miss cases where an
2639 // indirect branch is necessary.
2640 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2641 options::OPT_mno_relax_all);
2642
2643 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2644 options::OPT_mno_incremental_linker_compatible);
2645
2646 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2647
2648 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2649 options::OPT_fno_emit_compact_unwind_non_canonical);
2650
2651 // If you add more args here, also add them to the block below that
2652 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2653
2654 // When passing -I arguments to the assembler we sometimes need to
2655 // unconditionally take the next argument. For example, when parsing
2656 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2657 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2658 // arg after parsing the '-I' arg.
2659 bool TakeNextArg = false;
2660
2661 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2662 bool IsELF = Triple.isOSBinFormatELF();
2663 bool Crel = false, ExperimentalCrel = false;
2664 StringRef RelocSectionSym;
2665 bool SFrame = false, ExperimentalSFrame = false;
2666 bool ImplicitMapSyms = false;
2667 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2668 bool UseNoExecStack = false;
2669 bool Msa = false;
2670 const char *MipsTargetFeature = nullptr;
2671 llvm::SmallVector<const char *> SparcTargetFeatures;
2672 StringRef ImplicitIt;
2673 for (const Arg *A :
2674 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2675 options::OPT_mimplicit_it_EQ)) {
2676 A->claim();
2677
2678 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2679 switch (C.getDefaultToolChain().getArch()) {
2680 case llvm::Triple::arm:
2681 case llvm::Triple::armeb:
2682 case llvm::Triple::thumb:
2683 case llvm::Triple::thumbeb:
2684 // Only store the value; the last value set takes effect.
2685 ImplicitIt = A->getValue();
2686 if (!CheckARMImplicitITArg(ImplicitIt))
2687 D.Diag(diag::err_drv_unsupported_option_argument)
2688 << A->getSpelling() << ImplicitIt;
2689 continue;
2690 default:
2691 break;
2692 }
2693 }
2694
2695 for (StringRef Value : A->getValues()) {
2696 if (TakeNextArg) {
2697 CmdArgs.push_back(Value.data());
2698 TakeNextArg = false;
2699 continue;
2700 }
2701
2702 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2703 Value == "-mbig-obj")
2704 continue; // LLVM handles bigobj automatically
2705
2706 auto Equal = Value.split('=');
2707 auto checkArg = [&](bool ValidTarget,
2708 std::initializer_list<const char *> Set) {
2709 if (!ValidTarget) {
2710 D.Diag(diag::err_drv_unsupported_opt_for_target)
2711 << (Twine("-Wa,") + Equal.first + "=").str()
2712 << Triple.getTriple();
2713 } else if (!llvm::is_contained(Set, Equal.second)) {
2714 D.Diag(diag::err_drv_unsupported_option_argument)
2715 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2716 }
2717 };
2718 switch (C.getDefaultToolChain().getArch()) {
2719 default:
2720 break;
2721 case llvm::Triple::x86:
2722 case llvm::Triple::x86_64:
2723 if (Equal.first == "-mrelax-relocations" ||
2724 Equal.first == "--mrelax-relocations") {
2725 UseRelaxRelocations = Equal.second == "yes";
2726 checkArg(IsELF, {"yes", "no"});
2727 continue;
2728 }
2729 if (Value == "-msse2avx") {
2730 CmdArgs.push_back("-msse2avx");
2731 continue;
2732 }
2733 break;
2734 case llvm::Triple::wasm32:
2735 case llvm::Triple::wasm64:
2736 if (Value == "--no-type-check") {
2737 CmdArgs.push_back("-mno-type-check");
2738 continue;
2739 }
2740 break;
2741 case llvm::Triple::thumb:
2742 case llvm::Triple::thumbeb:
2743 case llvm::Triple::arm:
2744 case llvm::Triple::armeb:
2745 if (Equal.first == "-mimplicit-it") {
2746 // Only store the value; the last value set takes effect.
2747 ImplicitIt = Equal.second;
2748 checkArg(true, {"always", "never", "arm", "thumb"});
2749 continue;
2750 }
2751 if (Value == "-mthumb")
2752 // -mthumb has already been processed in ComputeLLVMTriple()
2753 // recognize but skip over here.
2754 continue;
2755 break;
2756 case llvm::Triple::aarch64:
2757 case llvm::Triple::aarch64_be:
2758 case llvm::Triple::aarch64_32:
2759 if (Equal.first == "-mmapsyms") {
2760 ImplicitMapSyms = Equal.second == "implicit";
2761 checkArg(IsELF, {"default", "implicit"});
2762 continue;
2763 }
2764 break;
2765 case llvm::Triple::mips:
2766 case llvm::Triple::mipsel:
2767 case llvm::Triple::mips64:
2768 case llvm::Triple::mips64el:
2769 if (Value == "--trap") {
2770 CmdArgs.push_back("-target-feature");
2771 CmdArgs.push_back("+use-tcc-in-div");
2772 continue;
2773 }
2774 if (Value == "--break") {
2775 CmdArgs.push_back("-target-feature");
2776 CmdArgs.push_back("-use-tcc-in-div");
2777 continue;
2778 }
2779 if (Value.starts_with("-msoft-float")) {
2780 CmdArgs.push_back("-target-feature");
2781 CmdArgs.push_back("+soft-float");
2782 continue;
2783 }
2784 if (Value.starts_with("-mhard-float")) {
2785 CmdArgs.push_back("-target-feature");
2786 CmdArgs.push_back("-soft-float");
2787 continue;
2788 }
2789 if (Value == "-mmsa") {
2790 Msa = true;
2791 continue;
2792 }
2793 if (Value == "-mno-msa") {
2794 Msa = false;
2795 continue;
2796 }
2797 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2798 .Case("-mips1", "+mips1")
2799 .Case("-mips2", "+mips2")
2800 .Case("-mips3", "+mips3")
2801 .Case("-mips4", "+mips4")
2802 .Case("-mips5", "+mips5")
2803 .Case("-mips32", "+mips32")
2804 .Case("-mips32r2", "+mips32r2")
2805 .Case("-mips32r3", "+mips32r3")
2806 .Case("-mips32r5", "+mips32r5")
2807 .Case("-mips32r6", "+mips32r6")
2808 .Case("-mips64", "+mips64")
2809 .Case("-mips64r2", "+mips64r2")
2810 .Case("-mips64r3", "+mips64r3")
2811 .Case("-mips64r5", "+mips64r5")
2812 .Case("-mips64r6", "+mips64r6")
2813 .Default(nullptr);
2814 if (MipsTargetFeature)
2815 continue;
2816 break;
2817
2818 case llvm::Triple::sparc:
2819 case llvm::Triple::sparcel:
2820 case llvm::Triple::sparcv9:
2821 if (Value == "--undeclared-regs") {
2822 // LLVM already allows undeclared use of G registers, so this option
2823 // becomes a no-op. This solely exists for GNU compatibility.
2824 // TODO implement --no-undeclared-regs
2825 continue;
2826 }
2827 SparcTargetFeatures =
2828 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2829 .Case("-Av8", {"-v8plus"})
2830 .Case("-Av8plus", {"+v8plus", "+v9"})
2831 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2832 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2833 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3",
2834 "+ua2005", "+ua2007"})
2835 .Case("-Av9", {"+v9"})
2836 .Case("-Av9a", {"+v9", "+vis"})
2837 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2838 .Case("-Av9d",
2839 {"+v9", "+vis", "+vis2", "+vis3", "+ua2005", "+ua2007"})
2840 .Default({});
2841 if (!SparcTargetFeatures.empty())
2842 continue;
2843 break;
2844 }
2845
2846 if (Value == "-force_cpusubtype_ALL") {
2847 // Do nothing, this is the default and we don't support anything else.
2848 } else if (Value == "-L") {
2849 CmdArgs.push_back("-msave-temp-labels");
2850 } else if (Value == "--fatal-warnings") {
2851 CmdArgs.push_back("-massembler-fatal-warnings");
2852 } else if (Value == "--no-warn" || Value == "-W") {
2853 CmdArgs.push_back("-massembler-no-warn");
2854 } else if (Value == "--noexecstack") {
2855 UseNoExecStack = true;
2856 } else if (Value.starts_with("-compress-debug-sections") ||
2857 Value.starts_with("--compress-debug-sections") ||
2858 Value == "-nocompress-debug-sections" ||
2859 Value == "--nocompress-debug-sections") {
2860 CmdArgs.push_back(Value.data());
2861 } else if (Value == "--crel") {
2862 Crel = true;
2863 } else if (Value == "--no-crel") {
2864 Crel = false;
2865 } else if (Value == "--allow-experimental-crel") {
2866 ExperimentalCrel = true;
2867 } else if (Value.starts_with("--reloc-section-sym=")) {
2868 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2869 } else if (Value.starts_with("-I")) {
2870 CmdArgs.push_back(Value.data());
2871 // We need to consume the next argument if the current arg is a plain
2872 // -I. The next arg will be the include directory.
2873 if (Value == "-I")
2874 TakeNextArg = true;
2875 } else if (Value.starts_with("-gdwarf-")) {
2876 // "-gdwarf-N" options are not cc1as options.
2877 unsigned DwarfVersion = DwarfVersionNum(Value);
2878 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2879 CmdArgs.push_back(Value.data());
2880 } else {
2881 RenderDebugEnablingArgs(Args, CmdArgs,
2882 llvm::codegenoptions::DebugInfoConstructor,
2883 DwarfVersion, llvm::DebuggerKind::Default);
2884 }
2885 } else if (Value == "--gsframe") {
2886 SFrame = true;
2887 } else if (Value == "--allow-experimental-sframe") {
2888 ExperimentalSFrame = true;
2889 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2890 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2891 // Do nothing, we'll validate it later.
2892 } else if (Value == "-defsym" || Value == "--defsym") {
2893 if (A->getNumValues() != 2) {
2894 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2895 break;
2896 }
2897 const char *S = A->getValue(1);
2898 auto Pair = StringRef(S).split('=');
2899 auto Sym = Pair.first;
2900 auto SVal = Pair.second;
2901
2902 if (Sym.empty() || SVal.empty()) {
2903 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2904 break;
2905 }
2906 int64_t IVal;
2907 if (SVal.getAsInteger(0, IVal)) {
2908 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2909 break;
2910 }
2911 CmdArgs.push_back("--defsym");
2912 TakeNextArg = true;
2913 } else if (Value == "-fdebug-compilation-dir") {
2914 CmdArgs.push_back("-fdebug-compilation-dir");
2915 TakeNextArg = true;
2916 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2917 // The flag is a -Wa / -Xassembler argument and Options doesn't
2918 // parse the argument, so this isn't automatically aliased to
2919 // -fdebug-compilation-dir (without '=') here.
2920 CmdArgs.push_back("-fdebug-compilation-dir");
2921 CmdArgs.push_back(Value.data());
2922 } else if (Value == "--version") {
2923 D.PrintVersion(C, llvm::outs());
2924 } else {
2925 D.Diag(diag::err_drv_unsupported_option_argument)
2926 << A->getSpelling() << Value;
2927 }
2928 }
2929 }
2930 if (ImplicitIt.size())
2931 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2932 if (Crel) {
2933 if (!ExperimentalCrel)
2934 D.Diag(diag::err_drv_experimental_crel);
2935 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2936 CmdArgs.push_back("--crel");
2937 } else {
2938 D.Diag(diag::err_drv_unsupported_opt_for_target)
2939 << "-Wa,--crel" << D.getTargetTriple();
2940 }
2941 }
2942 if (!RelocSectionSym.empty()) {
2943 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2944 RelocSectionSym != "none")
2945 D.Diag(diag::err_drv_invalid_value)
2946 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2947 << RelocSectionSym;
2948 else if (Triple.isOSBinFormatELF())
2949 CmdArgs.push_back(
2950 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2951 else
2952 D.Diag(diag::err_drv_unsupported_opt_for_target)
2953 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2954 }
2955 if (SFrame) {
2956 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2957 if (!ExperimentalSFrame)
2958 D.Diag(diag::err_drv_experimental_sframe);
2959 else
2960 CmdArgs.push_back("--gsframe");
2961 } else {
2962 D.Diag(diag::err_drv_unsupported_opt_for_target)
2963 << "-Wa,--gsframe" << D.getTargetTriple();
2964 }
2965 }
2966 if (ImplicitMapSyms)
2967 CmdArgs.push_back("-mmapsyms=implicit");
2968 if (Msa)
2969 CmdArgs.push_back("-mmsa");
2970 if (!UseRelaxRelocations)
2971 CmdArgs.push_back("-mrelax-relocations=no");
2972 if (UseNoExecStack)
2973 CmdArgs.push_back("-mnoexecstack");
2974 if (MipsTargetFeature != nullptr) {
2975 CmdArgs.push_back("-target-feature");
2976 CmdArgs.push_back(MipsTargetFeature);
2977 }
2978
2979 for (const char *Feature : SparcTargetFeatures) {
2980 CmdArgs.push_back("-target-feature");
2981 CmdArgs.push_back(Feature);
2982 }
2983
2984 // forward -fembed-bitcode to assmebler
2985 if (C.getDriver().embedBitcodeEnabled() ||
2986 C.getDriver().embedBitcodeMarkerOnly())
2987 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2988
2989 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2990 CmdArgs.push_back("-as-secure-log-file");
2991 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2992 }
2993}
2994
2995static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2996 bool OFastEnabled, const ArgList &Args,
2997 ArgStringList &CmdArgs,
2998 const JobAction &JA) {
2999 // List of veclibs which when used with -fveclib imply -fno-math-errno.
3000 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
3001 llvm::StringLiteral("SLEEF")};
3002 bool NoMathErrnoWasImpliedByVecLib = false;
3003 const Arg *VecLibArg = nullptr;
3004 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
3005 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
3006
3007 // Handle various floating point optimization flags, mapping them to the
3008 // appropriate LLVM code generation flags. This is complicated by several
3009 // "umbrella" flags, so we do this by stepping through the flags incrementally
3010 // adjusting what we think is enabled/disabled, then at the end setting the
3011 // LLVM flags based on the final state.
3012 bool HonorINFs = true;
3013 bool HonorNaNs = true;
3014 bool ApproxFunc = false;
3015 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3016 bool MathErrno = TC.IsMathErrnoDefault();
3017 bool AssociativeMath = false;
3018 bool ReciprocalMath = false;
3019 bool SignedZeros = true;
3020 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
3021 bool TrappingMathPresent = false; // Is trapping-math in args, and not
3022 // overriden by ffp-exception-behavior?
3023 bool RoundingFPMath = false;
3024 // -ffp-model values: strict, fast, precise
3025 StringRef FPModel = "";
3026 // -ffp-exception-behavior options: strict, maytrap, ignore
3027 StringRef FPExceptionBehavior = "";
3028 // -ffp-eval-method options: double, extended, source
3029 StringRef FPEvalMethod = "";
3030 llvm::DenormalMode DenormalFPMath =
3031 TC.getDefaultDenormalModeForType(Args, JA);
3032 llvm::DenormalMode DenormalFP32Math =
3033 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
3034
3035 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3036 // If one wasn't given by the user, don't pass it here.
3037 StringRef FPContract;
3038 // Explicit contraction options and unsafe math establish a fallback.
3039 // Without one, disabling unsafe math leaves precise/strict models unchanged.
3040 std::optional<StringRef> FPContractFallback;
3041 StringRef LastFpContractOverrideOption;
3042 const bool UseFrontendFPContractDefault =
3045 if (!UseFrontendFPContractDefault)
3046 FPContract = "on";
3047 bool StrictFPModel = false;
3048 StringRef Float16ExcessPrecision = "";
3049 StringRef BFloat16ExcessPrecision = "";
3051 std::string ComplexRangeStr;
3052 StringRef LastComplexRangeOption;
3053
3054 auto enableUnsafeFPContract = [&]() {
3055 FPContract = "fast";
3056 if (!FPContractFallback)
3057 FPContractFallback = "on";
3058 };
3059
3060 // Lambda to set fast-math options. This is also used by -ffp-model=fast
3061 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
3062 if (Aggressive) {
3063 HonorINFs = false;
3064 HonorNaNs = false;
3066 LastComplexRangeOption, Range);
3067 } else {
3068 HonorINFs = true;
3069 HonorNaNs = true;
3070 setComplexRange(D, CallerOption,
3072 LastComplexRangeOption, Range);
3073 }
3074 MathErrno = false;
3075 AssociativeMath = true;
3076 ReciprocalMath = true;
3077 ApproxFunc = true;
3078 SignedZeros = false;
3079 TrappingMath = false;
3080 RoundingFPMath = false;
3081 FPExceptionBehavior = "";
3082 enableUnsafeFPContract();
3083 };
3084
3085 // Lambda to consolidate common handling for fp-contract
3086 auto restoreFPContractState = [&]() {
3087 if (!UseFrontendFPContractDefault && FPContractFallback)
3088 FPContract = *FPContractFallback;
3089 LastFpContractOverrideOption = "";
3090 };
3091
3092 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3093 CmdArgs.push_back("-mlimit-float-precision");
3094 CmdArgs.push_back(A->getValue());
3095 }
3096
3097 for (const Arg *A : Args) {
3098 llvm::scope_exit CheckMathErrnoForVecLib(
3099 [&, MathErrnoBeforeArg = MathErrno] {
3100 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3101 ArgThatEnabledMathErrnoAfterVecLib = A;
3102 });
3103
3104 switch (A->getOption().getID()) {
3105 // If this isn't an FP option skip the claim below
3106 default: continue;
3107
3108 case options::OPT_fcx_limited_range:
3109 setComplexRange(D, A->getSpelling(),
3111 LastComplexRangeOption, Range);
3112 break;
3113 case options::OPT_fno_cx_limited_range:
3114 setComplexRange(D, A->getSpelling(),
3116 LastComplexRangeOption, Range);
3117 break;
3118 case options::OPT_fcx_fortran_rules:
3119 setComplexRange(D, A->getSpelling(),
3121 LastComplexRangeOption, Range);
3122 break;
3123 case options::OPT_fno_cx_fortran_rules:
3124 setComplexRange(D, A->getSpelling(),
3126 LastComplexRangeOption, Range);
3127 break;
3128 case options::OPT_fcomplex_arithmetic_EQ: {
3130 StringRef Val = A->getValue();
3131 if (Val == "full")
3133 else if (Val == "improved")
3135 else if (Val == "promoted")
3137 else if (Val == "basic")
3139 else {
3140 D.Diag(diag::err_drv_unsupported_option_argument)
3141 << A->getSpelling() << Val;
3142 break;
3143 }
3144 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3145 LastComplexRangeOption, Range);
3146 break;
3147 }
3148 case options::OPT_ffp_model_EQ: {
3149 // If -ffp-model= is seen, reset to fno-fast-math
3150 HonorINFs = true;
3151 HonorNaNs = true;
3152 ApproxFunc = false;
3153 // Turning *off* -ffast-math restores the toolchain default.
3154 MathErrno = TC.IsMathErrnoDefault();
3155 AssociativeMath = false;
3156 ReciprocalMath = false;
3157 SignedZeros = true;
3158
3159 StringRef Val = A->getValue();
3160 if (OFastEnabled && Val != "aggressive") {
3161 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3162 D.Diag(clang::diag::warn_drv_overriding_option)
3163 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3164 break;
3165 }
3166 StrictFPModel = false;
3167 if (!FPModel.empty() && FPModel != Val)
3168 D.Diag(clang::diag::warn_drv_overriding_option)
3169 << Args.MakeArgString("-ffp-model=" + FPModel)
3170 << Args.MakeArgString("-ffp-model=" + Val);
3171 if (Val == "fast") {
3172 FPModel = Val;
3173 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3174 // applyFastMath sets fp-contract="fast"
3175 LastFpContractOverrideOption = "-ffp-model=fast";
3176 } else if (Val == "aggressive") {
3177 FPModel = Val;
3178 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3179 // applyFastMath sets fp-contract="fast"
3180 LastFpContractOverrideOption = "-ffp-model=aggressive";
3181 } else if (Val == "precise") {
3182 FPModel = Val;
3183 FPContract = "on";
3184 LastFpContractOverrideOption = "-ffp-model=precise";
3185 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3187 LastComplexRangeOption, Range);
3188 } else if (Val == "strict") {
3189 StrictFPModel = true;
3190 FPExceptionBehavior = "strict";
3191 FPModel = Val;
3192 FPContract = "off";
3193 LastFpContractOverrideOption = "-ffp-model=strict";
3194 TrappingMath = true;
3195 RoundingFPMath = true;
3196 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3198 LastComplexRangeOption, Range);
3199 } else
3200 D.Diag(diag::err_drv_unsupported_option_argument)
3201 << A->getSpelling() << Val;
3202 break;
3203 }
3204
3205 // Options controlling individual features
3206 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3207 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3208 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3209 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3210 case options::OPT_fapprox_func: ApproxFunc = true; break;
3211 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3212 case options::OPT_fmath_errno: MathErrno = true; break;
3213 case options::OPT_fno_math_errno: MathErrno = false; break;
3214 case options::OPT_fassociative_math: AssociativeMath = true; break;
3215 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3216 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3217 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3218 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3219 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3220 case options::OPT_ftrapping_math:
3221 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3222 FPExceptionBehavior != "strict")
3223 // Warn that previous value of option is overridden.
3224 D.Diag(clang::diag::warn_drv_overriding_option)
3225 << Args.MakeArgString("-ffp-exception-behavior=" +
3226 FPExceptionBehavior)
3227 << "-ftrapping-math";
3228 TrappingMath = true;
3229 TrappingMathPresent = true;
3230 FPExceptionBehavior = "strict";
3231 break;
3232 case options::OPT_fveclib:
3233 VecLibArg = A;
3234 NoMathErrnoWasImpliedByVecLib =
3235 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3236 if (NoMathErrnoWasImpliedByVecLib)
3237 MathErrno = false;
3238 break;
3239 case options::OPT_fno_trapping_math:
3240 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3241 FPExceptionBehavior != "ignore")
3242 // Warn that previous value of option is overridden.
3243 D.Diag(clang::diag::warn_drv_overriding_option)
3244 << Args.MakeArgString("-ffp-exception-behavior=" +
3245 FPExceptionBehavior)
3246 << "-fno-trapping-math";
3247 TrappingMath = false;
3248 TrappingMathPresent = true;
3249 FPExceptionBehavior = "ignore";
3250 break;
3251
3252 case options::OPT_frounding_math:
3253 RoundingFPMath = true;
3254 break;
3255
3256 case options::OPT_fno_rounding_math:
3257 RoundingFPMath = false;
3258 break;
3259
3260 case options::OPT_fdenormal_fp_math_EQ:
3261 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3262 DenormalFP32Math = DenormalFPMath;
3263 if (!DenormalFPMath.isValid()) {
3264 D.Diag(diag::err_drv_invalid_value)
3265 << A->getAsString(Args) << A->getValue();
3266 }
3267 break;
3268
3269 case options::OPT_fdenormal_fp_math_f32_EQ:
3270 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3271 if (!DenormalFP32Math.isValid()) {
3272 D.Diag(diag::err_drv_invalid_value)
3273 << A->getAsString(Args) << A->getValue();
3274 }
3275 break;
3276
3277 // Validate and pass through -ffp-contract option.
3278 case options::OPT_ffp_contract: {
3279 StringRef Val = A->getValue();
3280 if (Val == "fast" || Val == "on" || Val == "off" ||
3281 Val == "fast-honor-pragmas") {
3282 if (Val != FPContract && LastFpContractOverrideOption != "") {
3283 D.Diag(clang::diag::warn_drv_overriding_option)
3284 << LastFpContractOverrideOption
3285 << Args.MakeArgString("-ffp-contract=" + Val);
3286 }
3287
3288 FPContract = Val;
3289 FPContractFallback = Val;
3290 LastFpContractOverrideOption = "";
3291 } else
3292 D.Diag(diag::err_drv_unsupported_option_argument)
3293 << A->getSpelling() << Val;
3294 break;
3295 }
3296
3297 // Validate and pass through -ffp-exception-behavior option.
3298 case options::OPT_ffp_exception_behavior_EQ: {
3299 StringRef Val = A->getValue();
3300 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3301 FPExceptionBehavior != Val)
3302 // Warn that previous value of option is overridden.
3303 D.Diag(clang::diag::warn_drv_overriding_option)
3304 << Args.MakeArgString("-ffp-exception-behavior=" +
3305 FPExceptionBehavior)
3306 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3307 TrappingMath = TrappingMathPresent = false;
3308 if (Val == "ignore" || Val == "maytrap")
3309 FPExceptionBehavior = Val;
3310 else if (Val == "strict") {
3311 FPExceptionBehavior = Val;
3312 TrappingMath = TrappingMathPresent = true;
3313 } else
3314 D.Diag(diag::err_drv_unsupported_option_argument)
3315 << A->getSpelling() << Val;
3316 break;
3317 }
3318
3319 // Validate and pass through -ffp-eval-method option.
3320 case options::OPT_ffp_eval_method_EQ: {
3321 StringRef Val = A->getValue();
3322 if (Val == "double" || Val == "extended" || Val == "source")
3323 FPEvalMethod = Val;
3324 else
3325 D.Diag(diag::err_drv_unsupported_option_argument)
3326 << A->getSpelling() << Val;
3327 break;
3328 }
3329
3330 case options::OPT_fexcess_precision_EQ: {
3331 StringRef Val = A->getValue();
3332 const llvm::Triple::ArchType Arch = TC.getArch();
3333 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3334 if (Val == "standard" || Val == "fast")
3335 Float16ExcessPrecision = Val;
3336 // To make it GCC compatible, allow the value of "16" which
3337 // means disable excess precision, the same meaning than clang's
3338 // equivalent value "none".
3339 else if (Val == "16")
3340 Float16ExcessPrecision = "none";
3341 else
3342 D.Diag(diag::err_drv_unsupported_option_argument)
3343 << A->getSpelling() << Val;
3344 } else {
3345 if (!(Val == "standard" || Val == "fast"))
3346 D.Diag(diag::err_drv_unsupported_option_argument)
3347 << A->getSpelling() << Val;
3348 }
3349 BFloat16ExcessPrecision = Float16ExcessPrecision;
3350 break;
3351 }
3352 case options::OPT_ffinite_math_only:
3353 HonorINFs = false;
3354 HonorNaNs = false;
3355 break;
3356 case options::OPT_fno_finite_math_only:
3357 HonorINFs = true;
3358 HonorNaNs = true;
3359 break;
3360
3361 case options::OPT_funsafe_math_optimizations:
3362 AssociativeMath = true;
3363 ReciprocalMath = true;
3364 SignedZeros = false;
3365 ApproxFunc = true;
3366 TrappingMath = false;
3367 FPExceptionBehavior = "";
3368 enableUnsafeFPContract();
3369 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3370 break;
3371 case options::OPT_fno_unsafe_math_optimizations:
3372 AssociativeMath = false;
3373 ReciprocalMath = false;
3374 SignedZeros = true;
3375 ApproxFunc = false;
3376 restoreFPContractState();
3377 break;
3378
3379 case options::OPT_cl_fast_relaxed_math:
3380 applyFastMath(true, A->getSpelling());
3381 break;
3382
3383 case options::OPT_Ofast:
3384 // If -Ofast is the optimization level, then -ffast-math should be enabled
3385 if (!OFastEnabled)
3386 continue;
3387 [[fallthrough]];
3388 case options::OPT_ffast_math:
3389 applyFastMath(true, A->getSpelling());
3390 if (A->getOption().getID() == options::OPT_Ofast)
3391 LastFpContractOverrideOption = "-Ofast";
3392 else
3393 LastFpContractOverrideOption = "-ffast-math";
3394 break;
3395 case options::OPT_fno_fast_math:
3396 HonorINFs = true;
3397 HonorNaNs = true;
3398 // Turning on -ffast-math (with either flag) removes the need for
3399 // MathErrno. However, turning *off* -ffast-math merely restores the
3400 // toolchain default (which may be false).
3401 MathErrno = TC.IsMathErrnoDefault();
3402 AssociativeMath = false;
3403 ReciprocalMath = false;
3404 ApproxFunc = false;
3405 SignedZeros = true;
3406 restoreFPContractState();
3408 setComplexRange(D, A->getSpelling(),
3410 LastComplexRangeOption, Range);
3411 else
3413 LastComplexRangeOption = "";
3414 break;
3415 } // End switch (A->getOption().getID())
3416
3417 // The StrictFPModel local variable is needed to report warnings
3418 // in the way we intend. If -ffp-model=strict has been used, we
3419 // want to report a warning for the next option encountered that
3420 // takes us out of the settings described by fp-model=strict, but
3421 // we don't want to continue issuing warnings for other conflicting
3422 // options after that.
3423 if (StrictFPModel) {
3424 // If -ffp-model=strict has been specified on command line but
3425 // subsequent options conflict then emit warning diagnostic.
3426 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3427 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3428 FPContract == "off")
3429 // OK: Current Arg doesn't conflict with -ffp-model=strict
3430 ;
3431 else {
3432 StrictFPModel = false;
3433 FPModel = "";
3434 // The warning for -ffp-contract would have been reported by the
3435 // OPT_ffp_contract_EQ handler above. A special check here is needed
3436 // to avoid duplicating the warning.
3437 auto RHS = (A->getNumValues() == 0)
3438 ? A->getSpelling()
3439 : Args.MakeArgString(A->getSpelling() + A->getValue());
3440 if (A->getSpelling() != "-ffp-contract=") {
3441 if (RHS != "-ffp-model=strict")
3442 D.Diag(clang::diag::warn_drv_overriding_option)
3443 << "-ffp-model=strict" << RHS;
3444 }
3445 }
3446 }
3447
3448 // If we handled this option claim it
3449 A->claim();
3450 }
3451
3452 if (!HonorINFs)
3453 CmdArgs.push_back("-menable-no-infs");
3454
3455 if (!HonorNaNs)
3456 CmdArgs.push_back("-menable-no-nans");
3457
3458 if (ApproxFunc)
3459 CmdArgs.push_back("-fapprox-func");
3460
3461 if (MathErrno) {
3462 CmdArgs.push_back("-fmath-errno");
3463 if (NoMathErrnoWasImpliedByVecLib)
3464 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3465 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3466 << VecLibArg->getAsString(Args);
3467 }
3468
3469 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3470 !TrappingMath)
3471 CmdArgs.push_back("-funsafe-math-optimizations");
3472
3473 if (!SignedZeros)
3474 CmdArgs.push_back("-fno-signed-zeros");
3475
3476 if (AssociativeMath && !SignedZeros && !TrappingMath)
3477 CmdArgs.push_back("-mreassociate");
3478
3479 if (ReciprocalMath)
3480 CmdArgs.push_back("-freciprocal-math");
3481
3482 if (TrappingMath) {
3483 // FP Exception Behavior is also set to strict
3484 assert(FPExceptionBehavior == "strict");
3485 }
3486
3487 // The default is IEEE.
3488 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3489 llvm::SmallString<64> DenormFlag;
3490 llvm::raw_svector_ostream ArgStr(DenormFlag);
3491 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3492 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3493 }
3494
3495 // Add f32 specific denormal mode flag if it's different.
3496 if (DenormalFP32Math != DenormalFPMath) {
3497 llvm::SmallString<64> DenormFlag;
3498 llvm::raw_svector_ostream ArgStr(DenormFlag);
3499 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3500 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3501 }
3502
3503 if (!FPContract.empty())
3504 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3505
3506 if (RoundingFPMath)
3507 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3508 else
3509 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3510
3511 if (!FPExceptionBehavior.empty())
3512 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3513 FPExceptionBehavior));
3514
3515 if (!FPEvalMethod.empty())
3516 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3517
3518 if (!Float16ExcessPrecision.empty())
3519 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3520 Float16ExcessPrecision));
3521 if (!BFloat16ExcessPrecision.empty())
3522 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3523 BFloat16ExcessPrecision));
3524
3525 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3526 if (!Recip.empty())
3527 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3528
3529 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3530 // individual features enabled by -ffast-math instead of the option itself as
3531 // that's consistent with gcc's behaviour.
3532 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3533 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3534 CmdArgs.push_back("-ffast-math");
3535
3536 // Handle __FINITE_MATH_ONLY__ similarly.
3537 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3538 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3539 // -menable-no-nans are set by the user.
3540 bool shouldAddFiniteMathOnly = false;
3541 if (!HonorINFs && !HonorNaNs) {
3542 shouldAddFiniteMathOnly = true;
3543 } else {
3544 bool InfValues = true;
3545 bool NanValues = true;
3546 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3547 StringRef ArgValue = Arg->getValue();
3548 if (ArgValue == "-menable-no-nans")
3549 NanValues = false;
3550 else if (ArgValue == "-menable-no-infs")
3551 InfValues = false;
3552 }
3553 if (!NanValues && !InfValues)
3554 shouldAddFiniteMathOnly = true;
3555 }
3556 if (shouldAddFiniteMathOnly) {
3557 CmdArgs.push_back("-ffinite-math-only");
3558 }
3559 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3560 CmdArgs.push_back("-mfpmath");
3561 CmdArgs.push_back(A->getValue());
3562 }
3563
3564 // Disable a codegen optimization for floating-point casts.
3565 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3566 options::OPT_fstrict_float_cast_overflow, false))
3567 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3568
3570 ComplexRangeStr = renderComplexRangeOption(Range);
3571 if (!ComplexRangeStr.empty()) {
3572 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3573 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3574 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3575 complexRangeKindToStr(Range)));
3576 }
3577 if (Args.hasArg(options::OPT_fcx_limited_range))
3578 CmdArgs.push_back("-fcx-limited-range");
3579 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3580 CmdArgs.push_back("-fcx-fortran-rules");
3581 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3582 CmdArgs.push_back("-fno-cx-limited-range");
3583 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3584 CmdArgs.push_back("-fno-cx-fortran-rules");
3585}
3586
3587static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3588 const llvm::Triple &Triple,
3589 const InputInfo &Input) {
3590 // Add default argument set.
3591 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3592 CmdArgs.push_back("-analyzer-checker=core");
3593 CmdArgs.push_back("-analyzer-checker=apiModeling");
3594
3595 if (!Triple.isWindowsMSVCEnvironment()) {
3596 CmdArgs.push_back("-analyzer-checker=unix");
3597 } else {
3598 // Enable "unix" checkers that also work on Windows.
3599 CmdArgs.push_back("-analyzer-checker=unix.API");
3600 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3601 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3602 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3603 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3604 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3605 }
3606
3607 // Disable some unix checkers for PS4/PS5.
3608 if (Triple.isPS()) {
3609 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3610 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3611 }
3612
3613 if (Triple.isOSDarwin()) {
3614 CmdArgs.push_back("-analyzer-checker=osx");
3615 CmdArgs.push_back(
3616 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3617 }
3618 else if (Triple.isOSFuchsia())
3619 CmdArgs.push_back("-analyzer-checker=fuchsia");
3620
3621 CmdArgs.push_back("-analyzer-checker=deadcode");
3622
3623 if (types::isCXX(Input.getType()))
3624 CmdArgs.push_back("-analyzer-checker=cplusplus");
3625
3626 if (!Triple.isPS()) {
3627 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3628 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3629 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3630 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3631 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3632 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3633 }
3634
3635 // Default nullability checks.
3636 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3637 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3638 }
3639
3640 // Set the output format. The default is plist, for (lame) historical reasons.
3641 CmdArgs.push_back("-analyzer-output");
3642 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3643 CmdArgs.push_back(A->getValue());
3644 else
3645 CmdArgs.push_back("plist");
3646
3647 // Disable the presentation of standard compiler warnings when using
3648 // --analyze. We only want to show static analyzer diagnostics or frontend
3649 // errors.
3650 CmdArgs.push_back("-w");
3651
3652 // Add -Xanalyzer arguments when running as analyzer.
3653 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3654}
3655
3656static bool isValidSymbolName(StringRef S) {
3657 if (S.empty())
3658 return false;
3659
3660 if (std::isdigit(S[0]))
3661 return false;
3662
3663 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3664}
3665
3666static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3667 const ArgList &Args, ArgStringList &CmdArgs,
3668 bool KernelOrKext) {
3669 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3670
3671 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3672 // doesn't even have a stack!
3673 if (EffectiveTriple.isNVPTX())
3674 return;
3675
3676 // -stack-protector=0 is default.
3678 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3679 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3680
3681 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3682 options::OPT_fstack_protector_all,
3683 options::OPT_fstack_protector_strong,
3684 options::OPT_fstack_protector)) {
3685 if (A->getOption().matches(options::OPT_fstack_protector))
3686 StackProtectorLevel =
3687 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3688 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3689 StackProtectorLevel = LangOptions::SSPStrong;
3690 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3691 StackProtectorLevel = LangOptions::SSPReq;
3692
3693 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3694 D.Diag(diag::warn_drv_unsupported_option_for_target)
3695 << A->getSpelling() << EffectiveTriple.getTriple();
3696 StackProtectorLevel = DefaultStackProtectorLevel;
3697 }
3698 } else {
3699 StackProtectorLevel = DefaultStackProtectorLevel;
3700 }
3701
3702 if (StackProtectorLevel) {
3703 CmdArgs.push_back("-stack-protector");
3704 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3705 }
3706
3707 // --param ssp-buffer-size=
3708 for (const Arg *A : Args.filtered(options::OPT__param)) {
3709 StringRef Str(A->getValue());
3710 if (Str.consume_front("ssp-buffer-size=")) {
3711 if (StackProtectorLevel) {
3712 CmdArgs.push_back("-stack-protector-buffer-size");
3713 // FIXME: Verify the argument is a valid integer.
3714 CmdArgs.push_back(Args.MakeArgString(Str));
3715 }
3716 A->claim();
3717 }
3718 }
3719
3720 const std::string &TripleStr = EffectiveTriple.getTriple();
3721 StringRef GuardValue;
3722 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3723 GuardValue = A->getValue();
3724 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3725 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3726 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3727 !EffectiveTriple.isSystemZ())
3728 D.Diag(diag::err_drv_unsupported_opt_for_target)
3729 << A->getAsString(Args) << TripleStr;
3730 // z/OS only supports the tls mode.
3731 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3732 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3733 << A->getOption().getName() << GuardValue << "tls";
3734 return;
3735 }
3736 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3737 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3738 GuardValue != "tls" && GuardValue != "global") {
3739 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3740 << A->getOption().getName() << GuardValue << "tls global";
3741 return;
3742 }
3743 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3744 GuardValue == "tls") {
3745 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3746 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3747 << A->getAsString(Args);
3748 return;
3749 }
3750 // Check whether the target subarch supports the hardware TLS register
3751 if (!arm::isHardTPSupported(EffectiveTriple)) {
3752 D.Diag(diag::err_target_unsupported_tp_hard)
3753 << EffectiveTriple.getArchName();
3754 return;
3755 }
3756 // Check whether the user asked for something other than -mtp=cp15
3757 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3758 StringRef Value = A->getValue();
3759 if (Value != "cp15") {
3760 D.Diag(diag::err_drv_argument_not_allowed_with)
3761 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3762 return;
3763 }
3764 }
3765 CmdArgs.push_back("-target-feature");
3766 CmdArgs.push_back("+read-tp-tpidruro");
3767 }
3768 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3769 GuardValue != "global") {
3770 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3771 << A->getOption().getName() << GuardValue << "sysreg global";
3772 return;
3773 }
3774 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3775 if (GuardValue != "tls" && GuardValue != "global") {
3776 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3777 << A->getOption().getName() << GuardValue << "tls global";
3778 return;
3779 }
3780 if (GuardValue == "tls") {
3781 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3782 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3783 << A->getAsString(Args);
3784 return;
3785 }
3786 }
3787 }
3788 A->render(Args, CmdArgs);
3789 }
3790
3791 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3792 StringRef Value = A->getValue();
3793 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3794 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3795 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3796 D.Diag(diag::err_drv_unsupported_opt_for_target)
3797 << A->getAsString(Args) << TripleStr;
3798 int Offset;
3799 if (Value.getAsInteger(10, Offset)) {
3800 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3801 return;
3802 }
3803 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3804 (Offset < 0 || Offset > 0xfffff)) {
3805 D.Diag(diag::err_drv_invalid_int_value)
3806 << A->getOption().getName() << Value;
3807 return;
3808 }
3809 A->render(Args, CmdArgs);
3810 }
3811
3812 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3813 StringRef Value = A->getValue();
3814 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3815 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3816 D.Diag(diag::err_drv_unsupported_opt_for_target)
3817 << A->getAsString(Args) << TripleStr;
3818 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3819 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3820 << A->getOption().getName() << Value << "fs gs";
3821 return;
3822 }
3823 if (EffectiveTriple.isAArch64() &&
3824 llvm::StringSwitch<bool>(Value)
3825 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3826 "tpidr_el2", "far_el1", "far_el2"},
3827 false)
3828 .Default(true)) {
3829 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3830 << A->getOption().getName() << Value
3831 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3832 return;
3833 }
3834 if (EffectiveTriple.isRISCV() && Value != "tp") {
3835 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3836 << A->getOption().getName() << Value << "tp";
3837 return;
3838 }
3839 if (EffectiveTriple.isPPC64() && Value != "r13") {
3840 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3841 << A->getOption().getName() << Value << "r13";
3842 return;
3843 }
3844 if (EffectiveTriple.isPPC32() && Value != "r2") {
3845 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3846 << A->getOption().getName() << Value << "r2";
3847 return;
3848 }
3849 A->render(Args, CmdArgs);
3850 }
3851
3852 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3853 StringRef Value = A->getValue();
3854 if (!isValidSymbolName(Value)) {
3855 D.Diag(diag::err_drv_argument_only_allowed_with)
3856 << A->getOption().getName() << "legal symbol name";
3857 return;
3858 }
3859 A->render(Args, CmdArgs);
3860 }
3861
3862 if (Arg *A =
3863 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3864 if (!EffectiveTriple.isAArch64())
3865 D.Diag(diag::err_drv_unsupported_opt_for_target)
3866 << A->getAsString(Args) << TripleStr;
3867 StringRef Value = A->getValue();
3868 unsigned Width;
3869 if (Value.getAsInteger(10, Width)) {
3870 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3871 return;
3872 }
3873 if (Width != 4 && Width != 8) {
3874 D.Diag(diag::err_drv_invalid_int_value)
3875 << A->getOption().getName() << Value;
3876 }
3877 }
3878 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3879 if (!EffectiveTriple.isSystemZ()) {
3880 D.Diag(diag::err_drv_unsupported_opt_for_target)
3881 << A->getAsString(Args) << TripleStr;
3882 return;
3883 }
3884 if (GuardValue != "global") {
3885 D.Diag(diag::err_drv_argument_only_allowed_with)
3886 << "-mstack-protector-guard-record"
3887 << "-mstack-protector-guard=global";
3888 return;
3889 }
3890 A->render(Args, CmdArgs);
3891 }
3892}
3893
3894static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3895 ArgStringList &CmdArgs) {
3896 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3897
3898 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3899 !EffectiveTriple.isOSFuchsia())
3900 return;
3901
3902 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3903 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3904 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3905 return;
3906
3907 if (Args.hasFlag(options::OPT_fstack_clash_protection,
3908 options::OPT_fno_stack_clash_protection,
3909 EffectiveTriple.isAndroid()))
3910 CmdArgs.push_back("-fstack-clash-protection");
3911}
3912
3914 const ToolChain &TC,
3915 const ArgList &Args,
3916 ArgStringList &CmdArgs) {
3917 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3918 StringRef TrivialAutoVarInit = "";
3919
3920 for (const Arg *A : Args) {
3921 switch (A->getOption().getID()) {
3922 default:
3923 continue;
3924 case options::OPT_ftrivial_auto_var_init: {
3925 A->claim();
3926 StringRef Val = A->getValue();
3927 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3928 TrivialAutoVarInit = Val;
3929 else
3930 D.Diag(diag::err_drv_unsupported_option_argument)
3931 << A->getSpelling() << Val;
3932 break;
3933 }
3934 }
3935 }
3936
3937 if (TrivialAutoVarInit.empty())
3938 switch (DefaultTrivialAutoVarInit) {
3940 break;
3942 TrivialAutoVarInit = "pattern";
3943 break;
3945 TrivialAutoVarInit = "zero";
3946 break;
3947 }
3948
3949 if (!TrivialAutoVarInit.empty()) {
3950 CmdArgs.push_back(
3951 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3952 }
3953
3954 if (Arg *A =
3955 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3956 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3957 StringRef(
3958 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3959 "uninitialized")
3960 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3961 A->claim();
3962 StringRef Val = A->getValue();
3963 if (std::stoi(Val.str()) <= 0)
3964 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3965 CmdArgs.push_back(
3966 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3967 }
3968
3969 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3970 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3971 StringRef(
3972 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3973 "uninitialized")
3974 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3975 A->claim();
3976 StringRef Val = A->getValue();
3977 if (std::stoi(Val.str()) <= 0)
3978 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3979 CmdArgs.push_back(
3980 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3981 }
3982}
3983
3984static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3985 types::ID InputType) {
3986 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3987 // for denormal flushing handling based on the target.
3988 const unsigned ForwardedArguments[] = {
3989 options::OPT_cl_opt_disable,
3990 options::OPT_cl_strict_aliasing,
3991 options::OPT_cl_single_precision_constant,
3992 options::OPT_cl_finite_math_only,
3993 options::OPT_cl_kernel_arg_info,
3994 options::OPT_cl_unsafe_math_optimizations,
3995 options::OPT_cl_fast_relaxed_math,
3996 options::OPT_cl_no_signed_zeros,
3997 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3998 options::OPT_cl_uniform_work_group_size
3999 };
4000
4001 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
4002 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
4003 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
4004 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
4005 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
4006 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
4007 }
4008
4009 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
4010 CmdArgs.push_back("-menable-no-infs");
4011 CmdArgs.push_back("-menable-no-nans");
4012 }
4013
4014 for (const auto &Arg : ForwardedArguments)
4015 if (const auto *A = Args.getLastArg(Arg))
4016 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
4017
4018 Args.ClaimAllArgs(options::OPT_cl_mad_enable);
4019
4020 // Only add the default headers if we are compiling OpenCL sources.
4021 if ((types::isOpenCL(InputType) ||
4022 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
4023 !Args.hasArg(options::OPT_cl_no_stdinc)) {
4024 CmdArgs.push_back("-finclude-default-header");
4025 CmdArgs.push_back("-fdeclare-opencl-builtins");
4026 }
4027}
4028
4029static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
4030 ArgStringList &CmdArgs, types::ID InputType) {
4031 const unsigned ForwardedArguments[] = {
4032 options::OPT_hlsl_all_resources_bound,
4033 options::OPT_dxil_validator_version,
4034 options::OPT_res_may_alias,
4035 options::OPT_D,
4036 options::OPT_I,
4037 options::OPT_O,
4038 options::OPT_emit_llvm,
4039 options::OPT_emit_obj,
4040 options::OPT_disable_llvm_passes,
4041 options::OPT_fnative_half_type,
4042 options::OPT_fnative_int16_type,
4043 options::OPT_fmatrix_memory_layout_EQ,
4044 options::OPT_hlsl_entrypoint,
4045 options::OPT_fdx_rootsignature_define,
4046 options::OPT_fdx_rootsignature_version,
4047 options::OPT_fdx_semantic_signature_packing_mode_EQ,
4048 options::OPT_fhlsl_spv_use_unknown_image_format,
4049 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
4050 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
4051 options::OPT_fhlsl_spv_preserve_interface,
4052 options::OPT_fhlsl_spv_support_nonzero_base_instance};
4053 if (!types::isHLSL(InputType))
4054 return;
4055 for (const auto &Arg : ForwardedArguments)
4056 if (const auto *A = Args.getLastArg(Arg))
4057 A->renderAsInput(Args, CmdArgs);
4058 // Add the default headers if dxc_no_stdinc is not set.
4059 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
4060 !Args.hasArg(options::OPT_nostdinc))
4061 CmdArgs.push_back("-finclude-default-header");
4062
4063 if (Args.hasArg(options::OPT_dxc_Zss)) {
4064 if (Args.hasArg(options::OPT_dxc_Zsb))
4065 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
4066 CmdArgs.push_back("-mllvm");
4067 CmdArgs.push_back("-dx-Zss");
4068 }
4069 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
4070 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4071 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
4072 CmdArgs.push_back("-mllvm");
4073 CmdArgs.push_back("--dx-source-in-debug-module");
4074 }
4075 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
4076 CmdArgs.push_back("-mllvm");
4077 CmdArgs.push_back("--dx-strip-debug");
4078 }
4079 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
4080 CmdArgs.push_back("-mllvm");
4081 CmdArgs.push_back("--dx-pdb-in-private");
4082 }
4083 CmdArgs.push_back("-load-bool-from-mem=nonzero");
4084}
4085
4086static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4087 ArgStringList &CmdArgs, types::ID InputType) {
4088 if (!Args.hasArg(options::OPT_fopenacc))
4089 return;
4090
4091 CmdArgs.push_back("-fopenacc");
4092}
4093
4094static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4095 const ArgList &Args, ArgStringList &CmdArgs) {
4096 // -fbuiltin is default unless -mkernel is used.
4097 bool UseBuiltins =
4098 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4099 !Args.hasArg(options::OPT_mkernel));
4100 if (!UseBuiltins)
4101 CmdArgs.push_back("-fno-builtin");
4102
4103 // -ffreestanding implies -fno-builtin.
4104 if (Args.hasArg(options::OPT_ffreestanding))
4105 UseBuiltins = false;
4106
4107 // Process the -fno-builtin-* options.
4108 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4109 A->claim();
4110
4111 // If -fno-builtin is specified, then there's no need to pass the option to
4112 // the frontend.
4113 if (UseBuiltins)
4114 A->render(Args, CmdArgs);
4115 }
4116}
4117
4119 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4120 Twine Path{Str};
4121 Path.toVector(Result);
4122 return Path.getSingleStringRef() != "";
4123 }
4124 if (llvm::sys::path::cache_directory(Result)) {
4125 llvm::sys::path::append(Result, "clang");
4126 llvm::sys::path::append(Result, "ModuleCache");
4127 return true;
4128 }
4129 return false;
4130}
4131
4134 const char *BaseInput) {
4135 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4136 return StringRef(ModuleOutputEQ->getValue());
4137
4138 SmallString<256> OutputPath;
4139 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4140 FinalOutput && Args.hasArg(options::OPT_c))
4141 OutputPath = FinalOutput->getValue();
4142 else {
4143 llvm::sys::fs::current_path(OutputPath);
4144 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4145 }
4146
4147 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4148 llvm::sys::path::replace_extension(OutputPath, Extension);
4149 return OutputPath;
4150}
4151
4153 const ArgList &Args, const InputInfo &Input,
4154 const InputInfo &Output, bool HaveStd20,
4155 ArgStringList &CmdArgs) {
4156 const bool IsCXX = types::isCXX(Input.getType());
4157 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4158 bool HaveModules = HaveStdCXXModules;
4159
4160 // -fmodules enables the use of precompiled modules (off by default).
4161 // Users can pass -fno-cxx-modules to turn off modules support for
4162 // C++/Objective-C++ programs.
4163 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4164 options::OPT_fno_cxx_modules, true);
4165 bool HaveClangModules = false;
4166 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4167 if (AllowedInCXX || !IsCXX) {
4168 CmdArgs.push_back("-fmodules");
4169 HaveClangModules = true;
4170 }
4171 }
4172
4173 HaveModules |= HaveClangModules;
4174
4175 if (HaveModules && !AllowedInCXX)
4176 CmdArgs.push_back("-fno-cxx-modules");
4177
4178 // -fmodule-maps enables implicit reading of module map files. By default,
4179 // this is enabled if we are using Clang's flavor of precompiled modules.
4180 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4181 options::OPT_fno_implicit_module_maps, HaveClangModules))
4182 CmdArgs.push_back("-fimplicit-module-maps");
4183
4184 // -fmodules-decluse checks that modules used are declared so (off by default)
4185 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4186 options::OPT_fno_modules_decluse);
4187
4188 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4189 // all #included headers are part of modules.
4190 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4191 options::OPT_fno_modules_strict_decluse, false))
4192 CmdArgs.push_back("-fmodules-strict-decluse");
4193
4194 Args.addOptInFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4195 options::OPT_fno_modulemap_allow_subdirectory_search);
4196
4197 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4198 bool ImplicitModules = false;
4199 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4200 options::OPT_fno_implicit_modules, HaveClangModules)) {
4201 if (HaveModules)
4202 CmdArgs.push_back("-fno-implicit-modules");
4203 } else if (HaveModules) {
4204 ImplicitModules = true;
4205 // -fmodule-cache-path specifies where our implicitly-built module files
4206 // should be written.
4207 SmallString<128> Path;
4208 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4209 Path = A->getValue();
4210
4211 bool HasPath = true;
4212 if (C.isForDiagnostics()) {
4213 // When generating crash reports, we want to emit the modules along with
4214 // the reproduction sources, so we ignore any provided module path.
4215 Path = Output.getFilename();
4216 llvm::sys::path::replace_extension(Path, ".cache");
4217 llvm::sys::path::append(Path, "modules");
4218 } else if (Path.empty()) {
4219 // No module path was provided: use the default.
4220 HasPath = Driver::getDefaultModuleCachePath(Path);
4221 }
4222
4223 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4224 // That being said, that failure is unlikely and not caching is harmless.
4225 if (HasPath) {
4226 const char Arg[] = "-fmodules-cache-path=";
4227 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4228 CmdArgs.push_back(Args.MakeArgString(Path));
4229 }
4230
4231 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4232 }
4233
4234 if (HaveModules) {
4235 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4236 options::OPT_fno_prebuilt_implicit_modules, false))
4237 CmdArgs.push_back("-fprebuilt-implicit-modules");
4238 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4239 options::OPT_fno_modules_validate_input_files_content,
4240 false))
4241 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4242 }
4243
4244 // -fmodule-name specifies the module that is currently being built (or
4245 // used for header checking by -fmodule-maps).
4246 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4247
4248 // -fmodule-map-file can be used to specify files containing module
4249 // definitions.
4250 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4251
4252 // -fbuiltin-module-map can be used to load the clang
4253 // builtin headers modulemap file.
4254 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4255 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4256 llvm::sys::path::append(BuiltinModuleMap, "include");
4257 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4258 if (llvm::sys::fs::exists(BuiltinModuleMap))
4259 CmdArgs.push_back(
4260 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4261 }
4262
4263 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4264 // names to precompiled module files (the module is loaded only if used).
4265 // The -fmodule-file=<file> form can be used to unconditionally load
4266 // precompiled module files (whether used or not).
4267 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4268 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4269
4270 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4271 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4272 CmdArgs.push_back(Args.MakeArgString(
4273 std::string("-fprebuilt-module-path=") + A->getValue()));
4274 A->claim();
4275 }
4276 } else
4277 Args.ClaimAllArgs(options::OPT_fmodule_file);
4278
4279 // When building modules and generating crashdumps, we need to dump a module
4280 // dependency VFS alongside the output.
4281 if (HaveClangModules && C.isForDiagnostics()) {
4282 SmallString<128> VFSDir(Output.getFilename());
4283 llvm::sys::path::replace_extension(VFSDir, ".cache");
4284 // Add the cache directory as a temp so the crash diagnostics pick it up.
4285 C.addTempFile(Args.MakeArgString(VFSDir));
4286
4287 llvm::sys::path::append(VFSDir, "vfs");
4288 CmdArgs.push_back("-module-dependency-dir");
4289 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4290 }
4291
4292 if (HaveClangModules)
4293 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4294
4295 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4296 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_search_path);
4297 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4298 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4299
4300 if (HaveClangModules) {
4301 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4302
4303 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4304 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4305 D.Diag(diag::err_drv_argument_not_allowed_with)
4306 << A->getAsString(Args) << "-fbuild-session-timestamp";
4307
4308 llvm::sys::fs::file_status Status;
4309 if (llvm::sys::fs::status(A->getValue(), Status))
4310 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4311 CmdArgs.push_back(Args.MakeArgString(
4312 "-fbuild-session-timestamp=" +
4313 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4314 Status.getLastModificationTime().time_since_epoch())
4315 .count())));
4316 }
4317
4318 if (Args.getLastArg(
4319 options::OPT_fmodules_validate_once_per_build_session)) {
4320 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4321 options::OPT_fbuild_session_file))
4322 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4323
4324 Args.AddLastArg(CmdArgs,
4325 options::OPT_fmodules_validate_once_per_build_session);
4326 }
4327
4328 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4329 options::OPT_fno_modules_validate_system_headers,
4330 ImplicitModules))
4331 CmdArgs.push_back("-fmodules-validate-system-headers");
4332
4333 if (Args.hasFlag(options::OPT_fmodules_validate_directory_dependencies,
4334 options::OPT_fno_modules_validate_directory_dependencies,
4335 false))
4336 CmdArgs.push_back("-fmodules-validate-directory-dependencies");
4337
4338 Args.AddLastArg(CmdArgs,
4339 options::OPT_fmodules_disable_diagnostic_validation);
4340 } else {
4341 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4342 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4343 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4344 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4345 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4346 Args.ClaimAllArgs(options::OPT_fmodules_validate_directory_dependencies);
4347 Args.ClaimAllArgs(options::OPT_fno_modules_validate_directory_dependencies);
4348 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4349 }
4350
4351 // FIXME: We provisionally don't check ODR violations for decls in the global
4352 // module fragment.
4353 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4354
4355 if (Input.getType() == driver::types::TY_CXXModule ||
4356 Input.getType() == driver::types::TY_PP_CXXModule) {
4357 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4358 CmdArgs.push_back("-fmodules-reduced-bmi");
4359
4360 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4361 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4362 else if (!(Args.hasArg(options::OPT__precompile) ||
4363 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4364 Args.hasArg(options::OPT_fmodule_output))
4365 // If --precompile is specified, we will always generate a module file if
4366 // we're compiling an importable module unit. This is fine even if the
4367 // compilation process won't reach the point of generating the module file
4368 // (e.g., in the preprocessing mode), since the attached flag
4369 // '-fmodule-output' is useless.
4370 //
4371 // But if '--precompile' is specified, it might be annoying to always
4372 // generate the module file as '--precompile' will generate the module
4373 // file anyway.
4374 CmdArgs.push_back(Args.MakeArgString(
4375 "-fmodule-output=" +
4377 }
4378
4379 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4380 Args.hasArg(options::OPT__precompile) &&
4381 (!Args.hasArg(options::OPT_o) ||
4382 Args.getLastArg(options::OPT_o)->getValue() ==
4384 D.Diag(diag::err_drv_reduced_module_output_overrided);
4385 }
4386
4387 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4388 // other translation units than module units. This is more user friendly to
4389 // allow end uers to enable this feature without asking for help from build
4390 // systems.
4391 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4392 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4393
4394 // We need to include the case the input file is a module file here.
4395 // Since the default compilation model for C++ module interface unit will
4396 // create temporary module file and compile the temporary module file
4397 // to get the object file. Then the `-fmodule-output` flag will be
4398 // brought to the second compilation process. So we have to claim it for
4399 // the case too.
4400 if (Input.getType() == driver::types::TY_CXXModule ||
4401 Input.getType() == driver::types::TY_PP_CXXModule ||
4402 Input.getType() == driver::types::TY_ModuleFile) {
4403 Args.ClaimAllArgs(options::OPT_fmodule_output);
4404 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4405 }
4406
4407 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4408 CmdArgs.push_back("-fmodules-embed-all-files");
4409
4410 return HaveModules;
4411}
4412
4413static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4414 ArgStringList &CmdArgs) {
4415 // -fsigned-char is default.
4416 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4417 options::OPT_fno_signed_char,
4418 options::OPT_funsigned_char,
4419 options::OPT_fno_unsigned_char)) {
4420 if (A->getOption().matches(options::OPT_funsigned_char) ||
4421 A->getOption().matches(options::OPT_fno_signed_char)) {
4422 CmdArgs.push_back("-fno-signed-char");
4423 }
4424 } else if (!isSignedCharDefault(T)) {
4425 CmdArgs.push_back("-fno-signed-char");
4426 }
4427
4428 // The default depends on the language standard.
4429 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4430
4431 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4432 options::OPT_fno_short_wchar)) {
4433 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4434 CmdArgs.push_back("-fwchar-type=short");
4435 CmdArgs.push_back("-fno-signed-wchar");
4436 } else {
4437 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4438 CmdArgs.push_back("-fwchar-type=int");
4439 if (T.isOSzOS() ||
4440 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4441 CmdArgs.push_back("-fno-signed-wchar");
4442 else
4443 CmdArgs.push_back("-fsigned-wchar");
4444 }
4445 } else if (T.isOSzOS())
4446 CmdArgs.push_back("-fno-signed-wchar");
4447}
4448
4449static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4450 const llvm::Triple &T, const ArgList &Args,
4451 ObjCRuntime &Runtime, bool InferCovariantReturns,
4452 const InputInfo &Input, ArgStringList &CmdArgs) {
4453 const llvm::Triple::ArchType Arch = TC.getArch();
4454
4455 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4456 // is the default. Except for deployment target of 10.5, next runtime is
4457 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4458 if (Runtime.isNonFragile()) {
4459 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4460 options::OPT_fno_objc_legacy_dispatch,
4462 if (TC.UseObjCMixedDispatch())
4463 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4464 else
4465 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4466 }
4467 }
4468
4469 // Forward -fobjc-direct-precondition-thunk to cc1
4470 // Defaults to false and needs explict turn on for now
4471 // TODO: switch to default true and needs explict turn off in the future.
4472 // TODO: add support for other runtimes
4473 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4474 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4475 if (Runtime.isNeXTFamily()) {
4476 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4477 } else {
4478 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4479 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4480 }
4481 }
4482
4483 if (types::isObjC(Input.getType())) {
4484 // Pass down -fobjc-msgsend-selector-stubs if present.
4485 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4486 options::OPT_fno_objc_msgsend_selector_stubs, false))
4487 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4488
4489 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4490 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4491 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4492 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4493 }
4494
4495 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4496 // to do Array/Dictionary subscripting by default.
4497 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4498 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4499 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4500
4501 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4502 // NOTE: This logic is duplicated in ToolChains.cpp.
4503 if (isObjCAutoRefCount(Args)) {
4504 TC.CheckObjCARC();
4505
4506 CmdArgs.push_back("-fobjc-arc");
4507
4508 // FIXME: It seems like this entire block, and several around it should be
4509 // wrapped in isObjC, but for now we just use it here as this is where it
4510 // was being used previously.
4511 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4513 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4514 else
4515 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4516 }
4517
4518 // Allow the user to enable full exceptions code emission.
4519 // We default off for Objective-C, on for Objective-C++.
4520 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4521 options::OPT_fno_objc_arc_exceptions,
4522 /*Default=*/types::isCXX(Input.getType())))
4523 CmdArgs.push_back("-fobjc-arc-exceptions");
4524 }
4525
4526 // Silence warning for full exception code emission options when explicitly
4527 // set to use no ARC.
4528 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4529 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4530 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4531 }
4532
4533 // Allow the user to control whether messages can be converted to runtime
4534 // functions.
4535 if (types::isObjC(Input.getType())) {
4536 auto *Arg = Args.getLastArg(
4537 options::OPT_fobjc_convert_messages_to_runtime_calls,
4538 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4539 if (Arg &&
4540 Arg->getOption().matches(
4541 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4542 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4543 }
4544
4545 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4546 // rewriter.
4547 if (InferCovariantReturns)
4548 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4549
4550 // Pass down -fobjc-weak or -fno-objc-weak if present.
4551 if (types::isObjC(Input.getType())) {
4552 auto WeakArg =
4553 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4554 if (!WeakArg) {
4555 // nothing to do
4556 } else if (!Runtime.allowsWeak()) {
4557 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4558 D.Diag(diag::err_objc_weak_unsupported);
4559 } else {
4560 WeakArg->render(Args, CmdArgs);
4561 }
4562 }
4563
4564 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4565 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4566
4567 // Forward constant literal flags to cc1.
4568 if (types::isObjC(Input.getType())) {
4569 bool EnableConstantLiterals =
4570 Args.hasFlag(options::OPT_fobjc_constant_literals,
4571 options::OPT_fno_objc_constant_literals,
4572 /*default=*/true) &&
4573 Runtime.hasConstantLiteralClasses();
4574 if (EnableConstantLiterals)
4575 CmdArgs.push_back("-fobjc-constant-literals");
4576 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4577 options::OPT_fno_constant_nsnumber_literals,
4578 /*default=*/true) &&
4579 EnableConstantLiterals)
4580 CmdArgs.push_back("-fconstant-nsnumber-literals");
4581 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4582 options::OPT_fno_constant_nsarray_literals,
4583 /*default=*/true) &&
4584 EnableConstantLiterals)
4585 CmdArgs.push_back("-fconstant-nsarray-literals");
4586 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4587 options::OPT_fno_constant_nsdictionary_literals,
4588 /*default=*/true) &&
4589 EnableConstantLiterals)
4590 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4591 }
4592}
4593
4594static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4595 ArgStringList &CmdArgs) {
4596 bool CaretDefault = true;
4597 bool ColumnDefault = true;
4598
4599 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4600 options::OPT__SLASH_diagnostics_column,
4601 options::OPT__SLASH_diagnostics_caret)) {
4602 switch (A->getOption().getID()) {
4603 case options::OPT__SLASH_diagnostics_caret:
4604 CaretDefault = true;
4605 ColumnDefault = true;
4606 break;
4607 case options::OPT__SLASH_diagnostics_column:
4608 CaretDefault = false;
4609 ColumnDefault = true;
4610 break;
4611 case options::OPT__SLASH_diagnostics_classic:
4612 CaretDefault = false;
4613 ColumnDefault = false;
4614 break;
4615 }
4616 }
4617
4618 // -fcaret-diagnostics is default.
4619 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4620 options::OPT_fno_caret_diagnostics, CaretDefault))
4621 CmdArgs.push_back("-fno-caret-diagnostics");
4622
4623 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4624 options::OPT_fno_diagnostics_fixit_info);
4625 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4626 options::OPT_fno_diagnostics_show_option);
4627
4628 if (const Arg *A =
4629 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4630 CmdArgs.push_back("-fdiagnostics-show-category");
4631 CmdArgs.push_back(A->getValue());
4632 }
4633
4634 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4635 options::OPT_fno_diagnostics_show_hotness);
4636
4637 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_safety_c,
4638 options::OPT_fno_lifetime_safety_c);
4639
4640 if (const Arg *A =
4641 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4642 std::string Opt =
4643 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4644 CmdArgs.push_back(Args.MakeArgString(Opt));
4645 }
4646
4647 if (const Arg *A =
4648 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4649 std::string Opt =
4650 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4651 CmdArgs.push_back(Args.MakeArgString(Opt));
4652 }
4653
4654 if (const Arg *A =
4655 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4656 options::OPT_fno_diagnostics_show_inlining_chain)) {
4657 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4658 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4659 else
4660 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4661 }
4662
4663 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4664 CmdArgs.push_back("-fdiagnostics-format");
4665 CmdArgs.push_back(A->getValue());
4666 if (StringRef(A->getValue()) == "sarif" ||
4667 StringRef(A->getValue()) == "SARIF")
4668 D.Diag(diag::warn_drv_sarif_format_unstable);
4669 }
4670
4671 if (const Arg *A = Args.getLastArg(
4672 options::OPT_fdiagnostics_show_note_include_stack,
4673 options::OPT_fno_diagnostics_show_note_include_stack)) {
4674 const Option &O = A->getOption();
4675 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4676 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4677 else
4678 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4679 }
4680
4681 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4682
4683 if (Args.hasArg(options::OPT_fansi_escape_codes))
4684 CmdArgs.push_back("-fansi-escape-codes");
4685
4686 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4687 options::OPT_fno_show_source_location);
4688
4689 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4690 options::OPT_fno_diagnostics_show_line_numbers);
4691
4692 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4693 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4694
4695 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4696 ColumnDefault))
4697 CmdArgs.push_back("-fno-show-column");
4698
4699 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4700 options::OPT_fno_spell_checking);
4701
4702 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4703}
4704
4705static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4706 const ArgList &Args, ArgStringList &CmdArgs,
4707 unsigned DwarfVersion) {
4708 auto *DwarfFormatArg =
4709 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4710 if (!DwarfFormatArg)
4711 return;
4712
4713 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4714 if (DwarfVersion < 3)
4715 D.Diag(diag::err_drv_argument_only_allowed_with)
4716 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4717 else if (!T.isArch64Bit())
4718 D.Diag(diag::err_drv_argument_only_allowed_with)
4719 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4720 else if (!T.isOSBinFormatELF())
4721 D.Diag(diag::err_drv_argument_only_allowed_with)
4722 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4723 }
4724
4725 DwarfFormatArg->render(Args, CmdArgs);
4726}
4727
4728static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4729 const ArgList &Args) {
4730 bool NeedsSimpleTemplateNames =
4731 Args.hasFlag(options::OPT_gsimple_template_names,
4732 options::OPT_gno_simple_template_names,
4734 if (!NeedsSimpleTemplateNames)
4735 return false;
4736
4737 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4738 if (!checkDebugInfoOption(A, Args, D, TC))
4739 return false;
4740
4741 return true;
4742}
4743
4744static void
4745renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4746 const ArgList &Args, types::ID InputType,
4747 ArgStringList &CmdArgs, const InputInfo &Output,
4748 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4749 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4750 bool IRInput = isLLVMIR(InputType);
4751 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4752 !isHIP(InputType) && !isObjC(InputType) &&
4753 !isOpenCL(InputType);
4754
4755 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4756
4757 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4758 options::OPT_fno_debug_record_sysroot, true))
4759 CmdArgs.push_back("-fno-debug-record-sysroot");
4760
4761 // The 'g' groups options involve a somewhat intricate sequence of decisions
4762 // about what to pass from the driver to the frontend, but by the time they
4763 // reach cc1 they've been factored into three well-defined orthogonal choices:
4764 // * what level of debug info to generate
4765 // * what dwarf version to write
4766 // * what debugger tuning to use
4767 // This avoids having to monkey around further in cc1 other than to disable
4768 // codeview if not running in a Windows environment. Perhaps even that
4769 // decision should be made in the driver as well though.
4770 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4771
4772 bool SplitDWARFInlining =
4773 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4774 options::OPT_fno_split_dwarf_inlining, false);
4775
4776 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4777 // object file generation and no IR generation, -gN should not be needed. So
4778 // allow -gsplit-dwarf with either -gN or IR input.
4779 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4780 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4781 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4782 D.Diag(diag::err_drv_unsupported_opt_for_target)
4783 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4784 << TC.getTripleString();
4785 return;
4786 }
4787 Arg *SplitDWARFArg;
4788 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4789 if (DwarfFission != DwarfFissionKind::None &&
4790 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4791 DwarfFission = DwarfFissionKind::None;
4792 SplitDWARFInlining = false;
4793 }
4794 }
4795 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4796 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4797
4798 // If the last option explicitly specified a debug-info level, use it.
4799 if (checkDebugInfoOption(A, Args, D, TC) &&
4800 A->getOption().matches(options::OPT_gN_Group)) {
4801 DebugInfoKind = debugLevelToInfoKind(*A);
4802 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4803 // complicated if you've disabled inline info in the skeleton CUs
4804 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4805 // line-tables-only, so let those compose naturally in that case.
4806 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4807 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4808 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4809 SplitDWARFInlining))
4810 DwarfFission = DwarfFissionKind::None;
4811 }
4812 }
4813
4814 // If a debugger tuning argument appeared, remember it.
4815 bool HasDebuggerTuning = false;
4816 if (const Arg *A =
4817 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4818 HasDebuggerTuning = true;
4819 if (checkDebugInfoOption(A, Args, D, TC)) {
4820 if (A->getOption().matches(options::OPT_glldb))
4821 DebuggerTuning = llvm::DebuggerKind::LLDB;
4822 else if (A->getOption().matches(options::OPT_gsce))
4823 DebuggerTuning = llvm::DebuggerKind::SCE;
4824 else if (A->getOption().matches(options::OPT_gdbx))
4825 DebuggerTuning = llvm::DebuggerKind::DBX;
4826 else
4827 DebuggerTuning = llvm::DebuggerKind::GDB;
4828 }
4829 }
4830
4831 // If a -gdwarf argument appeared, remember it.
4832 bool EmitDwarf = false;
4833 if (const Arg *A = getDwarfNArg(Args))
4834 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4835
4836 bool EmitCodeView = false;
4837 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4838 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4839
4840 // If the user asked for debug info but did not explicitly specify -gcodeview
4841 // or -gdwarf, ask the toolchain for the default format.
4842 if (!EmitCodeView && !EmitDwarf &&
4843 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4844 switch (TC.getDefaultDebugFormat()) {
4845 case llvm::codegenoptions::DIF_CodeView:
4846 EmitCodeView = true;
4847 break;
4848 case llvm::codegenoptions::DIF_DWARF:
4849 EmitDwarf = true;
4850 break;
4851 }
4852 }
4853
4854 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4855 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4856 // be lower than what the user wanted.
4857 if (EmitDwarf) {
4858 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4859 // Clamp effective DWARF version to the max supported by the toolchain.
4860 EffectiveDWARFVersion =
4861 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4862 } else {
4863 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4864 }
4865
4866 // -gline-directives-only supported only for the DWARF debug info.
4867 if (RequestedDWARFVersion == 0 &&
4868 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4869 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4870
4871 // strict DWARF is set to false by default. But for DBX, we need it to be set
4872 // as true by default.
4873 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4874 (void)checkDebugInfoOption(A, Args, D, TC);
4875 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4876 DebuggerTuning == llvm::DebuggerKind::DBX))
4877 CmdArgs.push_back("-gstrict-dwarf");
4878
4879 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4880 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4881
4882 // Column info is included by default for everything except SCE and
4883 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4884 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4885 // practice, however, the Microsoft debuggers don't handle missing end columns
4886 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4887 // it's better not to include any column info.
4888 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4889 (void)checkDebugInfoOption(A, Args, D, TC);
4890 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4891 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4892 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4893 DebuggerTuning != llvm::DebuggerKind::DBX)))
4894 CmdArgs.push_back("-gno-column-info");
4895
4896 if (!Args.hasFlag(options::OPT_gcall_site_info,
4897 options::OPT_gno_call_site_info, true))
4898 CmdArgs.push_back("-gno-call-site-info");
4899
4900 // FIXME: Move backend command line options to the module.
4901 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4902 // If -gline-tables-only or -gline-directives-only is the last option it
4903 // wins.
4904 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4905 TC)) {
4906 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4907 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4908 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4909 CmdArgs.push_back("-dwarf-ext-refs");
4910 CmdArgs.push_back("-fmodule-format=obj");
4911 }
4912 }
4913 }
4914
4915 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4916 CmdArgs.push_back("-fsplit-dwarf-inlining");
4917
4918 // After we've dealt with all combinations of things that could
4919 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4920 // figure out if we need to "upgrade" it to standalone debug info.
4921 // We parse these two '-f' options whether or not they will be used,
4922 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4923 bool NeedFullDebug = Args.hasFlag(
4924 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4925 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4927 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4928 (void)checkDebugInfoOption(A, Args, D, TC);
4929
4930 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4931 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4932 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4933 options::OPT_feliminate_unused_debug_types, false))
4934 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4935 else if (NeedFullDebug)
4936 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4937 }
4938
4939 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4940 false)) {
4941 // Source embedding is a vendor extension to DWARF v5. By now we have
4942 // checked if a DWARF version was stated explicitly, and have otherwise
4943 // fallen back to the target default, so if this is still not at least 5
4944 // we emit an error.
4945 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4946 if (RequestedDWARFVersion < 5)
4947 D.Diag(diag::err_drv_argument_only_allowed_with)
4948 << A->getAsString(Args) << "-gdwarf-5";
4949 else if (EffectiveDWARFVersion < 5)
4950 // The toolchain has reduced allowed dwarf version, so we can't enable
4951 // -gembed-source.
4952 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4953 << A->getAsString(Args) << TC.getTripleString() << 5
4954 << EffectiveDWARFVersion;
4955 else if (checkDebugInfoOption(A, Args, D, TC))
4956 CmdArgs.push_back("-gembed-source");
4957 }
4958
4959 // Enable Key Instructions by default if we're emitting DWARF, the language is
4960 // plain C or C++, and optimisations are enabled.
4961 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4962 bool KeyInstructionsOnByDefault =
4963 EmitDwarf && PlainCOrCXX && OptLevel &&
4964 !OptLevel->getOption().matches(options::OPT_O0);
4965 if (Args.hasFlag(options::OPT_gkey_instructions,
4966 options::OPT_gno_key_instructions,
4967 KeyInstructionsOnByDefault))
4968 CmdArgs.push_back("-gkey-instructions");
4969
4970 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4971 options::OPT_gno_structor_decl_linkage_names, true))
4972 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4973
4974 if (Args.hasFlag(options::OPT_fdynamic_debugging,
4975 options::OPT_fno_dynamic_debugging, false)) {
4976 // As this is an experimental feature we can afford to be strict about
4977 // supported configurations.
4978 // NOTE on adding target support, consider adding "tail-pad-to-size"
4979 // support in `llvm::prepareForDynamicDebugging`.
4980 if (!TC.getTriple().isX86())
4981 D.Diag(diag::err_drv_unsupported_opt_for_target)
4982 << Args.getLastArg(options::OPT_fdynamic_debugging)->getAsString(Args)
4983 << T.getTriple();
4984 if (IsUsingLTO)
4985 D.Diag(diag::err_drv_dyndbg_lto);
4986 if (DwarfFission != DwarfFissionKind::None)
4987 D.Diag(diag::err_drv_dyndbg_incompatible)
4988 << Args.getLastArg(options::OPT_gsplit_dwarf)->getAsString(Args);
4989 // There's no fundamental reason why IR input should be incompatible, but
4990 // it would add some complexity, and reducing the test matrix is valuable.
4991 if (IRInput)
4992 D.Diag(diag::err_drv_dyndbg_ir);
4993
4994 // Disable composition with sanitizers for now.
4995 if (auto *San = Args.getLastArg(options::OPT_fsanitize_EQ))
4996 D.Diag(diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4997
4998 if (!EmitDwarf)
4999 D.Diag(diag::warn_drv_dyndbg_req_debug);
5000 else
5001 CmdArgs.push_back("-fdynamic-debugging");
5002 }
5003
5004 if (EmitCodeView) {
5005 CmdArgs.push_back("-gcodeview");
5006
5007 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
5008 options::OPT_gno_codeview_ghash);
5009
5010 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
5011 options::OPT_gno_codeview_command_line);
5012 }
5013
5014 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
5015 options::OPT_gno_inline_line_tables);
5016
5017 // When emitting remarks, we need at least debug lines in the output.
5018 if (willEmitRemarks(Args) &&
5019 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
5020 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
5021
5022 // Adjust the debug info kind for the given toolchain.
5023 TC.adjustDebugInfoKind(DebugInfoKind, Args);
5024
5025 // On AIX, the debugger tuning option can be omitted if it is not explicitly
5026 // set.
5027 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
5028 T.isOSAIX() && !HasDebuggerTuning
5029 ? llvm::DebuggerKind::Default
5030 : DebuggerTuning);
5031
5032 // -fdebug-macro turns on macro debug info generation.
5033 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
5034 false))
5035 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
5036 D, TC))
5037 CmdArgs.push_back("-debug-info-macro");
5038
5039 // -ggnu-pubnames turns on gnu style pubnames in the backend.
5040 const auto *PubnamesArg =
5041 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
5042 options::OPT_gpubnames, options::OPT_gno_pubnames);
5043 if (DwarfFission != DwarfFissionKind::None ||
5044 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
5045 const bool OptionSet =
5046 (PubnamesArg &&
5047 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
5048 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
5049 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
5050 (!PubnamesArg ||
5051 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
5052 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
5053 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
5054 options::OPT_gpubnames)
5055 ? "-gpubnames"
5056 : "-ggnu-pubnames");
5057 }
5058
5059 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
5060 if (getDebugSimpleTemplateNames(TC, D, Args)) {
5061 ForwardTemplateParams = true;
5062 CmdArgs.push_back("-gsimple-template-names=simple");
5063 }
5064
5065 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
5066 bool UseDebugTemplateAlias =
5067 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
5068 if (const auto *DebugTemplateAlias = Args.getLastArg(
5069 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
5070 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5071 // asks for it we should let them have it (if the target supports it).
5072 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
5073 const auto &Opt = DebugTemplateAlias->getOption();
5074 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
5075 }
5076 }
5077 if (UseDebugTemplateAlias)
5078 CmdArgs.push_back("-gtemplate-alias");
5079
5080 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
5081 StringRef v = A->getValue();
5082 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
5083 }
5084
5085 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
5086 options::OPT_fno_debug_ranges_base_address);
5087
5088 // -gdwarf-aranges turns on the emission of the aranges section in the
5089 // backend.
5090 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
5091 A && checkDebugInfoOption(A, Args, D, TC)) {
5092 CmdArgs.push_back("-mllvm");
5093 CmdArgs.push_back("-generate-arange-section");
5094 }
5095
5096 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
5097 options::OPT_fno_force_dwarf_frame);
5098
5099 bool EnableTypeUnits = false;
5100 if (Args.hasFlag(options::OPT_fdebug_types_section,
5101 options::OPT_fno_debug_types_section, false)) {
5102 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5103 D.Diag(diag::err_drv_unsupported_opt_for_target)
5104 << Args.getLastArg(options::OPT_fdebug_types_section)
5105 ->getAsString(Args)
5106 << T.getTriple();
5107 } else if (checkDebugInfoOption(
5108 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
5109 TC)) {
5110 EnableTypeUnits = true;
5111 CmdArgs.push_back("-mllvm");
5112 CmdArgs.push_back("-generate-type-units");
5113 }
5114 }
5115
5116 if (const Arg *A =
5117 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
5118 options::OPT_gno_omit_unreferenced_methods))
5119 (void)checkDebugInfoOption(A, Args, D, TC);
5120 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
5121 options::OPT_gno_omit_unreferenced_methods, false) &&
5122 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5123 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5124 !EnableTypeUnits) {
5125 CmdArgs.push_back("-gomit-unreferenced-methods");
5126 }
5127
5128 // To avoid join/split of directory+filename, the integrated assembler prefers
5129 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5130 // form before DWARF v5.
5131 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5132 options::OPT_fno_dwarf_directory_asm,
5133 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5134 CmdArgs.push_back("-fno-dwarf-directory-asm");
5135
5136 // Decide how to render forward declarations of template instantiations.
5137 // SCE wants full descriptions, others just get them in the name.
5138 if (ForwardTemplateParams)
5139 CmdArgs.push_back("-debug-forward-template-params");
5140
5141 // Do we need to explicitly import anonymous namespaces into the parent
5142 // scope?
5143 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5144 CmdArgs.push_back("-dwarf-explicit-import");
5145
5146 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5147 if (useMachORelocatableDwarf(T, EffectiveDWARFVersion))
5148 CmdArgs.push_back("-grelocatable-dwarf");
5149 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5150
5151 // This controls whether or not we perform JustMyCode instrumentation.
5152 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5153 if (TC.getTriple().isOSBinFormatELF() ||
5154 TC.getTriple().isWindowsMSVCEnvironment()) {
5155 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5156 CmdArgs.push_back("-fjmc");
5157 else if (D.IsCLMode())
5158 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5159 << "'/Zi', '/Z7'";
5160 else
5161 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5162 << "-g";
5163 } else {
5164 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5165 }
5166 }
5167
5168 // Add in -fdebug-compilation-dir if necessary.
5169 const char *DebugCompilationDir =
5170 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5171
5172 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5173
5174 // Add the output path to the object file for CodeView debug infos.
5175 if (EmitCodeView && Output.isFilename())
5176 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5177 Output.getFilename());
5178}
5179
5180static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5181 ArgStringList &CmdArgs) {
5182 unsigned RTOptionID = options::OPT__SLASH_MT;
5183
5184 if (Args.hasArg(options::OPT__SLASH_LDd))
5185 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5186 // but defining _DEBUG is sticky.
5187 RTOptionID = options::OPT__SLASH_MTd;
5188
5189 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5190 RTOptionID = A->getOption().getID();
5191
5192 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5193 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5194 .Case("static", options::OPT__SLASH_MT)
5195 .Case("static_dbg", options::OPT__SLASH_MTd)
5196 .Case("dll", options::OPT__SLASH_MD)
5197 .Case("dll_dbg", options::OPT__SLASH_MDd)
5198 .Default(options::OPT__SLASH_MT);
5199 }
5200
5201 StringRef FlagForCRT;
5202 switch (RTOptionID) {
5203 case options::OPT__SLASH_MD:
5204 if (Args.hasArg(options::OPT__SLASH_LDd))
5205 CmdArgs.push_back("-D_DEBUG");
5206 CmdArgs.push_back("-D_MT");
5207 CmdArgs.push_back("-D_DLL");
5208 FlagForCRT = "--dependent-lib=msvcrt";
5209 break;
5210 case options::OPT__SLASH_MDd:
5211 CmdArgs.push_back("-D_DEBUG");
5212 CmdArgs.push_back("-D_MT");
5213 CmdArgs.push_back("-D_DLL");
5214 FlagForCRT = "--dependent-lib=msvcrtd";
5215 break;
5216 case options::OPT__SLASH_MT:
5217 if (Args.hasArg(options::OPT__SLASH_LDd))
5218 CmdArgs.push_back("-D_DEBUG");
5219 CmdArgs.push_back("-D_MT");
5220 CmdArgs.push_back("-flto-visibility-public-std");
5221 FlagForCRT = "--dependent-lib=libcmt";
5222 break;
5223 case options::OPT__SLASH_MTd:
5224 CmdArgs.push_back("-D_DEBUG");
5225 CmdArgs.push_back("-D_MT");
5226 CmdArgs.push_back("-flto-visibility-public-std");
5227 FlagForCRT = "--dependent-lib=libcmtd";
5228 break;
5229 default:
5230 llvm_unreachable("Unexpected option ID.");
5231 }
5232
5233 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5234 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5235 } else {
5236 CmdArgs.push_back(FlagForCRT.data());
5237
5238 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5239 // users want. The /Za flag to cl.exe turns this off, but it's not
5240 // implemented in clang.
5241 CmdArgs.push_back("--dependent-lib=oldnames");
5242 }
5243
5244 // SYCL: Add SYCL runtime library dependency
5245 // SYCL runtime is a required dependency similar to CRT, so we use
5246 // --dependent-lib to embed it in the object file metadata
5247 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5248 !Args.hasArg(options::OPT_nolibsycl) &&
5249 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5250
5251 // Determine debug vs release based on CRT flags
5252 bool IsDebugBuild = false;
5253
5254 // Check -fms-runtime-lib=dll_dbg
5255 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5256 StringRef RuntimeVal = A->getValue();
5257 if (RuntimeVal == "dll_dbg")
5258 IsDebugBuild = true;
5259 }
5260
5261 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5262 // overriding options (e.g., /MDd /MD -> /MD wins)
5263 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5264 if (A->getOption().matches(options::OPT__SLASH_MDd))
5265 IsDebugBuild = true;
5266 }
5267
5268 // Add appropriate SYCL runtime library dependency
5269 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5270 : "--dependent-lib=LLVMSYCL");
5271 }
5272
5273 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5274 // even if the file doesn't actually refer to any of the routines because
5275 // the CRT itself has incomplete dependency markings.
5276 if (TC.getTriple().isWindowsArm64EC())
5277 CmdArgs.push_back("--dependent-lib=softintrin");
5278}
5279
5281 const InputInfo &Output, const InputInfoList &Inputs,
5282 const ArgList &Args, const char *LinkingOutput) const {
5283 const auto &TC = getToolChain();
5284 const llvm::Triple &RawTriple = TC.getTriple();
5285 const llvm::Triple &Triple = TC.getEffectiveTriple();
5286 const std::string &TripleStr = Triple.getTriple();
5287
5288 bool KernelOrKext =
5289 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5290 const Driver &D = TC.getDriver();
5291 ArgStringList CmdArgs;
5292
5293 assert(Inputs.size() >= 1 && "Must have at least one input.");
5294 // CUDA/HIP compilation may have multiple inputs (source file + results of
5295 // device-side compilations). OpenMP device jobs also take the host IR as a
5296 // second input. Module precompilation accepts a list of header files to
5297 // include as part of the module. API extraction accepts a list of header
5298 // files whose API information is emitted in the output. All other jobs are
5299 // expected to have exactly one input. SYCL compilation only expects a
5300 // single input.
5301 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5302 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5303 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5304 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5305 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5306 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5307 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5308 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5309 bool UsesLLVMOffloading = Args.hasFlag(
5310 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
5311 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5313 bool IsHostOffloadingAction =
5316 (JA.isHostOffloading(C.getActiveOffloadKinds()));
5317
5318 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5319 bool IsRDCMode = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5320 /*Default=*/IsSYCL);
5321
5322 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5323 bool IsUsingLTO = LTOMode != LTOK_None;
5324
5325 // Extract API doesn't have a main input file, so invent a fake one as a
5326 // placeholder.
5327 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5328 "extract-api");
5329
5330 const InputInfo &Input =
5331 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5332
5333 InputInfoList ExtractAPIInputs;
5334 InputInfoList HostOffloadingInputs;
5335 const InputInfo *OpenMPDeviceInput = nullptr;
5336 for (const InputInfo &I : Inputs) {
5337 if (&I == &Input || I.getType() == types::TY_Nothing) {
5338 // This is the primary input or contains nothing.
5339 } else if (IsExtractAPI) {
5340 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5341 if (I.getType() != ExpectedInputType) {
5342 D.Diag(diag::err_drv_extract_api_wrong_kind)
5343 << I.getFilename() << types::getTypeName(I.getType())
5344 << types::getTypeName(ExpectedInputType);
5345 }
5346 ExtractAPIInputs.push_back(I);
5347 } else if (IsHostOffloadingAction) {
5348 HostOffloadingInputs.push_back(I);
5349 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5350 OpenMPDeviceInput = &I;
5351 } else {
5352 llvm_unreachable("unexpectedly given multiple inputs");
5353 }
5354 }
5355
5356 bool IsUEFI = RawTriple.isUEFI();
5357 bool IsIAMCU = RawTriple.isOSIAMCU();
5358
5359 // C++ is not supported for IAMCU.
5360 if (IsIAMCU && types::isCXX(Input.getType()))
5361 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5362
5363 // Invoke ourselves in -cc1 mode.
5364 //
5365 // FIXME: Implement custom jobs for internal actions.
5366 CmdArgs.push_back("-cc1");
5367
5368 // Add the "effective" target triple.
5369 CmdArgs.push_back("-triple");
5370 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5371
5372 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5373
5374 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5375 if (AuxTriple) {
5376 CmdArgs.push_back("-aux-triple");
5377 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5378
5379 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5380 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5381 // Windows), we need to pass Windows-specific flags to cc1.
5382 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5384 // Figure out the device side triple for the host-side compilation.
5385 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5386 ++I) {
5388 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5389 if (OffloadToolChains.first == OffloadToolChains.second)
5390 continue;
5391
5392 const llvm::Triple &DeviceAuxTriple =
5393 OffloadToolChains.first->second->getTriple();
5394 CmdArgs.push_back("-aux-triple");
5395 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5396 break;
5397 }
5398 }
5399
5400 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5401 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5402 Args.ClaimAllArgs(options::OPT_MJ);
5403 } else if (const Arg *GenCDBFragment =
5404 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5405 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5406 TripleStr, Output, Input, Args);
5407 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5408 }
5409
5410 if ((getToolChain().getTriple().isAMDGPU() ||
5411 (getToolChain().getTriple().isSPIRV() &&
5412 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5413 // Device side compilation printf
5414 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5415 CmdArgs.push_back(Args.MakeArgString(
5416 "-mprintf-kind=" +
5417 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5418 // Force compiler error on invalid conversion specifiers
5419 CmdArgs.push_back(
5420 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5421 }
5422 }
5423
5424 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5425 // We need to figure out which CUDA version we're compiling for, as that
5426 // determines how we load and launch GPU kernels.
5427 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5428 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5429 assert(CTC && "Expected valid CUDA Toolchain.");
5430 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5431 CmdArgs.push_back(Args.MakeArgString(
5432 Twine("-target-sdk-version=") +
5433 CudaVersionToString(CTC->CudaInstallation.version())));
5434 }
5435
5436 // Optimization level for CodeGen.
5437 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5438 if (A->getOption().matches(options::OPT_O4)) {
5439 CmdArgs.push_back("-O3");
5440 D.Diag(diag::warn_O4_is_O3);
5441 } else {
5442 A->render(Args, CmdArgs);
5443 }
5444 }
5445
5446 // Unconditionally claim the printf option now to avoid unused diagnostic.
5447 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5448 PF->claim();
5449
5450 if (IsSYCL) {
5451 if (IsSYCLDevice) {
5452 // We want to compile sycl kernels.
5453 CmdArgs.push_back("-fsycl-is-device");
5454
5455 // Set O2 optimization level by default
5456 if (!Args.getLastArg(options::OPT_O_Group))
5457 CmdArgs.push_back("-O2");
5458 } else {
5459 // Add any options that are needed specific to SYCL offload while
5460 // performing the host side compilation.
5461
5462 // Let the front-end host compilation flow know about SYCL offload
5463 // compilation.
5464 CmdArgs.push_back("-fsycl-is-host");
5465 }
5466
5467 // Set options for both host and device.
5468 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5469 if (SYCLStdArg) {
5470 SYCLStdArg->render(Args, CmdArgs);
5471 } else {
5472 // Ensure the default version in SYCL mode is 2020.
5473 CmdArgs.push_back("-sycl-std=2020");
5474 }
5475 }
5476
5477 if (Args.hasFlag(options::OPT_fclangir, options::OPT_fno_clangir, false))
5478 CmdArgs.push_back("-fclangir");
5479
5480 if (IsOpenMPDevice) {
5481 // We have to pass the triple of the host if compiling for an OpenMP device.
5482 const llvm::Triple &HostTriple =
5483 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5484 CmdArgs.push_back("-aux-triple");
5485 CmdArgs.push_back(HostTriple.str().c_str());
5486 }
5487
5488 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5489 Triple.getArch() == llvm::Triple::thumb)) {
5490 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5491 unsigned Version = 0;
5492 bool Failure =
5493 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5494 if (Failure || Version < 7)
5495 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5496 << TripleStr;
5497 }
5498
5499 // Push all default warning arguments that are specific to
5500 // the given target. These come before user provided warning options
5501 // are provided.
5502 TC.addClangWarningOptions(CmdArgs);
5503
5504 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5505 if (Triple.isSPIR() || Triple.isSPIRV())
5506 CmdArgs.push_back("-Wspir-compat");
5507
5508 // Select the appropriate action.
5509 RewriteKind rewriteKind = RK_None;
5510
5511 bool UnifiedLTO = false;
5512 if (IsUsingLTO) {
5513 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5514 options::OPT_fno_unified_lto, Triple.isPS());
5515 if (UnifiedLTO)
5516 CmdArgs.push_back("-funified-lto");
5517 }
5518
5519 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5520 CmdArgs.push_back("-fdefined-pointer-subtraction");
5521
5522 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5523 // it claims when not running an assembler. Otherwise, clang would emit
5524 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5525 // flags while debugging something. That'd be somewhat inconvenient, and it's
5526 // also inconsistent with most other flags -- we don't warn on
5527 // -ffunction-sections not being used in -E mode either for example, even
5528 // though it's not really used either.
5529 if (!isa<AssembleJobAction>(JA)) {
5530 // The args claimed here should match the args used in
5531 // CollectArgsForIntegratedAssembler().
5532 if (TC.useIntegratedAs()) {
5533 Args.ClaimAllArgs(options::OPT_mrelax_all);
5534 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5535 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5536 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5537 switch (C.getDefaultToolChain().getArch()) {
5538 case llvm::Triple::arm:
5539 case llvm::Triple::armeb:
5540 case llvm::Triple::thumb:
5541 case llvm::Triple::thumbeb:
5542 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5543 break;
5544 default:
5545 break;
5546 }
5547 }
5548 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5549 Args.ClaimAllArgs(options::OPT_Xassembler);
5550 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5551 }
5552
5553 bool IsAMDSPIRVForHIPDevice =
5554 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5555 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5556
5557 if (isa<AnalyzeJobAction>(JA)) {
5558 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5559 CmdArgs.push_back("-analyze");
5560 } else if (isa<PreprocessJobAction>(JA)) {
5561 if (Output.getType() == types::TY_Dependencies)
5562 CmdArgs.push_back("-Eonly");
5563 else {
5564 CmdArgs.push_back("-E");
5565 if (Args.hasArg(options::OPT_rewrite_objc) &&
5566 !Args.hasArg(options::OPT_g_Group))
5567 CmdArgs.push_back("-P");
5568 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5569 CmdArgs.push_back("-fdirectives-only");
5570 }
5571 } else if (isa<AssembleJobAction>(JA)) {
5572 CmdArgs.push_back("-emit-obj");
5573
5574 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5575
5576 // Also ignore explicit -force_cpusubtype_ALL option.
5577 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5578 } else if (isa<PrecompileJobAction>(JA)) {
5579 if (JA.getType() == types::TY_Nothing)
5580 CmdArgs.push_back("-fsyntax-only");
5581 else if (JA.getType() == types::TY_ModuleFile) {
5582 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5583 ((Input.getType() == types::TY_CXXStdModule ||
5584 Input.getType() == types::TY_PP_CXXStdModule) &&
5585 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5586 CmdArgs.push_back("-emit-reduced-module-interface");
5587 else
5588 CmdArgs.push_back("-emit-module-interface");
5589 } else if (JA.getType() == types::TY_HeaderUnit)
5590 CmdArgs.push_back("-emit-header-unit");
5591 else if (!Args.hasArg(options::OPT_ignore_pch))
5592 CmdArgs.push_back("-emit-pch");
5593 } else if (isa<VerifyPCHJobAction>(JA)) {
5594 CmdArgs.push_back("-verify-pch");
5595 } else if (isa<ExtractAPIJobAction>(JA)) {
5596 assert(JA.getType() == types::TY_API_INFO &&
5597 "Extract API actions must generate a API information.");
5598 CmdArgs.push_back("-extract-api");
5599
5600 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5601 PrettySGFArg->render(Args, CmdArgs);
5602
5603 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5604
5605 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5606 ProductNameArg->render(Args, CmdArgs);
5607 if (Arg *ExtractAPIIgnoresFileArg =
5608 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5609 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5610 if (Arg *EmitExtensionSymbolGraphs =
5611 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5612 if (!SymbolGraphDirArg)
5613 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5614
5615 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5616 }
5617 if (SymbolGraphDirArg)
5618 SymbolGraphDirArg->render(Args, CmdArgs);
5619 } else {
5620 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5621 "Invalid action for clang tool.");
5622 if (JA.getType() == types::TY_Nothing) {
5623 CmdArgs.push_back("-fsyntax-only");
5624 } else if (JA.getType() == types::TY_LLVM_IR ||
5625 JA.getType() == types::TY_LTO_IR) {
5626 CmdArgs.push_back("-emit-llvm");
5627 } else if (JA.getType() == types::TY_LLVM_BC ||
5628 JA.getType() == types::TY_LTO_BC) {
5629 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5630 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5631 Args.hasArg(options::OPT_emit_llvm)) {
5632 CmdArgs.push_back("-emit-llvm");
5633 } else {
5634 CmdArgs.push_back("-emit-llvm-bc");
5635 }
5636 } else if (JA.getType() == types::TY_IFS ||
5637 JA.getType() == types::TY_IFS_CPP) {
5638 StringRef ArgStr =
5639 Args.hasArg(options::OPT_interface_stub_version_EQ)
5640 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5641 : "ifs-v1";
5642 CmdArgs.push_back("-emit-interface-stubs");
5643 CmdArgs.push_back(
5644 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5645 } else if (JA.getType() == types::TY_PP_Asm) {
5646 CmdArgs.push_back("-S");
5647 } else if (JA.getType() == types::TY_AST) {
5648 if (!Args.hasArg(options::OPT_ignore_pch))
5649 CmdArgs.push_back("-emit-pch");
5650 } else if (JA.getType() == types::TY_ModuleFile) {
5651 CmdArgs.push_back("-module-file-info");
5652 } else if (JA.getType() == types::TY_RewrittenObjC) {
5653 CmdArgs.push_back("-rewrite-objc");
5654 rewriteKind = RK_NonFragile;
5655 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5656 CmdArgs.push_back("-rewrite-objc");
5657 rewriteKind = RK_Fragile;
5658 } else if (JA.getType() == types::TY_CIR) {
5659 CmdArgs.push_back("-emit-cir");
5660 } else if (JA.getType() == types::TY_CIRBC) {
5661 CmdArgs.push_back("-emit-cir-bc");
5662 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5663 CmdArgs.push_back("-emit-obj");
5664 } else {
5665 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5666 }
5667
5668 // Preserve use-list order by default when emitting bitcode, so that
5669 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5670 // same result as running passes here. For LTO, we don't need to preserve
5671 // the use-list order, since serialization to bitcode is part of the flow.
5672 if (JA.getType() == types::TY_LLVM_BC)
5673 CmdArgs.push_back("-emit-llvm-uselists");
5674
5675 if (IsUsingLTO) {
5676 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5677 options::OPT_foffload_lto_EQ);
5678 if (Triple.isNVPTX() && !IsRDCMode &&
5680 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5681 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5682 << "-fno-gpu-rdc";
5683 } else {
5684 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5685 CmdArgs.push_back(Args.MakeArgString(
5686 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5687 // PS4 uses the legacy LTO API, which does not support some of the
5688 // features enabled by -flto-unit.
5689 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5690 CmdArgs.push_back("-flto-unit");
5691 }
5692 }
5693 }
5694
5695 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5696
5697 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5698 if (!types::isLLVMIR(Input.getType()))
5699 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5700 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5701 }
5702
5703 if (Triple.isPPC())
5704 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5705 options::OPT_mno_regnames);
5706
5707 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5708 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5709
5710 if (Args.getLastArg(options::OPT_save_temps_EQ))
5711 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5712
5713 if (Args.getLastArg(options::OPT_save_dynamic_debugging_temps))
5714 Args.AddLastArg(CmdArgs, options::OPT_save_dynamic_debugging_temps);
5715
5716 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5717 options::OPT_fmemory_profile_EQ,
5718 options::OPT_fno_memory_profile);
5719 if (MemProfArg &&
5720 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5721 MemProfArg->render(Args, CmdArgs);
5722
5723 if (auto *MemProfUseArg =
5724 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5725 if (MemProfArg)
5726 D.Diag(diag::err_drv_argument_not_allowed_with)
5727 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5728 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5729 options::OPT_fprofile_generate_EQ))
5730 D.Diag(diag::err_drv_argument_not_allowed_with)
5731 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5732 MemProfUseArg->render(Args, CmdArgs);
5733 }
5734
5735 auto *CopyProfArg =
5736 Args.getLastArg(options::OPT_fcopyprof, options::OPT_fno_copyprof);
5737 if (CopyProfArg &&
5738 !CopyProfArg->getOption().matches(options::OPT_fno_copyprof)) {
5739 CopyProfArg->render(Args, CmdArgs);
5740 Args.AddLastArg(CmdArgs, options::OPT_fcopyprof_static_size_threshold_EQ);
5741 }
5742
5743 // Embed-bitcode option.
5744 // Only white-listed flags below are allowed to be embedded.
5745 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5747 // Add flags implied by -fembed-bitcode.
5748 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5749 // Disable all llvm IR level optimizations.
5750 CmdArgs.push_back("-disable-llvm-passes");
5751
5752 // Render target options.
5753 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5755
5756 // reject options that shouldn't be supported in bitcode
5757 // also reject kernel/kext
5758 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5759 options::OPT_mkernel,
5760 options::OPT_fapple_kext,
5761 options::OPT_ffunction_sections,
5762 options::OPT_fno_function_sections,
5763 options::OPT_fdata_sections,
5764 options::OPT_fno_data_sections,
5765 options::OPT_fbasic_block_sections_EQ,
5766 options::OPT_funique_internal_linkage_names,
5767 options::OPT_fno_unique_internal_linkage_names,
5768 options::OPT_funique_section_names,
5769 options::OPT_fno_unique_section_names,
5770 options::OPT_funique_basic_block_section_names,
5771 options::OPT_fno_unique_basic_block_section_names,
5772 options::OPT_mrestrict_it,
5773 options::OPT_mno_restrict_it,
5774 options::OPT_mstackrealign,
5775 options::OPT_mno_stackrealign,
5776 options::OPT_mstack_alignment,
5777 options::OPT_mcmodel_EQ,
5778 options::OPT_mlong_calls,
5779 options::OPT_mno_long_calls,
5780 options::OPT_ggnu_pubnames,
5781 options::OPT_gdwarf_aranges,
5782 options::OPT_fdebug_types_section,
5783 options::OPT_fno_debug_types_section,
5784 options::OPT_fdwarf_directory_asm,
5785 options::OPT_fno_dwarf_directory_asm,
5786 options::OPT_mrelax_all,
5787 options::OPT_mno_relax_all,
5788 options::OPT_ftrap_function_EQ,
5789 options::OPT_ffixed_r9,
5790 options::OPT_mfix_cortex_a53_835769,
5791 options::OPT_mno_fix_cortex_a53_835769,
5792 options::OPT_ffixed_x18,
5793 options::OPT_mglobal_merge,
5794 options::OPT_mno_global_merge,
5795 options::OPT_mred_zone,
5796 options::OPT_mno_red_zone,
5797 options::OPT_Wa_COMMA,
5798 options::OPT_Xassembler,
5799 options::OPT_mllvm,
5800 options::OPT_mmlir,
5801 };
5802 for (const auto &A : Args)
5803 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5804 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5805
5806 // Render the CodeGen options that need to be passed.
5807 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5808 options::OPT_fno_optimize_sibling_calls);
5809
5811 CmdArgs, JA);
5812
5813 // Render ABI arguments
5814 switch (TC.getArch()) {
5815 default: break;
5816 case llvm::Triple::arm:
5817 case llvm::Triple::armeb:
5818 case llvm::Triple::thumbeb:
5819 RenderARMABI(D, Triple, Args, CmdArgs);
5820 break;
5821 case llvm::Triple::aarch64:
5822 case llvm::Triple::aarch64_32:
5823 case llvm::Triple::aarch64_be:
5824 RenderAArch64ABI(Triple, Args, CmdArgs);
5825 break;
5826 }
5827
5828 // Input/Output file.
5829 if (Output.getType() == types::TY_Dependencies) {
5830 // Handled with other dependency code.
5831 } else if (Output.isFilename()) {
5832 CmdArgs.push_back("-o");
5833 CmdArgs.push_back(Output.getFilename());
5834 } else {
5835 assert(Output.isNothing() && "Input output.");
5836 }
5837
5838 for (const auto &II : Inputs) {
5839 addDashXForInput(Args, II, CmdArgs);
5840 if (II.isFilename())
5841 CmdArgs.push_back(II.getFilename());
5842 else
5843 II.getInputArg().renderAsInput(Args, CmdArgs);
5844 }
5845
5846 C.addCommand(std::make_unique<Command>(
5848 CmdArgs, Inputs, Output, D.getPrependArg()));
5849 return;
5850 }
5851
5852 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5853 CmdArgs.push_back("-fembed-bitcode=marker");
5854
5855 // We normally speed up the clang process a bit by skipping destructors at
5856 // exit, but when we're generating diagnostics we can rely on some of the
5857 // cleanup.
5858 if (!C.isForDiagnostics())
5859 CmdArgs.push_back("-disable-free");
5860 CmdArgs.push_back("-clear-ast-before-backend");
5861
5862#ifdef NDEBUG
5863 const bool IsAssertBuild = false;
5864#else
5865 const bool IsAssertBuild = true;
5866#endif
5867
5868 // Disable the verification pass in no-asserts builds unless otherwise
5869 // specified.
5870 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5871 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5872 CmdArgs.push_back("-disable-llvm-verifier");
5873 }
5874
5875 // Discard value names in no-asserts builds unless otherwise specified.
5876 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5877 options::OPT_fno_discard_value_names, !IsAssertBuild))
5878 CmdArgs.push_back("-discard-value-names");
5879
5880 // Set the main file name, so that debug info works even with
5881 // -save-temps.
5882 CmdArgs.push_back("-main-file-name");
5883 CmdArgs.push_back(getBaseInputName(Args, Input));
5884
5885 // Some flags which affect the language (via preprocessor
5886 // defines).
5887 if (Args.hasArg(options::OPT_static))
5888 CmdArgs.push_back("-static-define");
5889
5890 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5891
5892 if (Args.hasArg(options::OPT_municode))
5893 CmdArgs.push_back("-DUNICODE");
5894
5895 if (isa<AnalyzeJobAction>(JA))
5896 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5897
5898 if (isa<AnalyzeJobAction>(JA) ||
5899 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5900 CmdArgs.push_back("-setup-static-analyzer");
5901
5902 // Enable compatilibily mode to avoid analyzer-config related errors.
5903 // Since we can't access frontend flags through hasArg, let's manually iterate
5904 // through them.
5905 bool FoundAnalyzerConfig = false;
5906 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5907 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5908 FoundAnalyzerConfig = true;
5909 break;
5910 }
5911 if (!FoundAnalyzerConfig)
5912 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5913 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5914 FoundAnalyzerConfig = true;
5915 break;
5916 }
5917 if (FoundAnalyzerConfig)
5918 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5919
5921
5922 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5923 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5924 if (FunctionAlignment) {
5925 CmdArgs.push_back("-function-alignment");
5926 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5927 }
5928
5929 if (const Arg *A =
5930 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5931 unsigned Value = 0;
5932 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5933 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5934 << A->getAsString(Args) << A->getValue();
5935 else if (!llvm::isPowerOf2_32(Value))
5936 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5937 << A->getAsString(Args) << A->getValue();
5938
5939 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5940 Twine(std::min(Value, 65536u))));
5941 }
5942
5943 // We support -falign-loops=N where N is a power of 2. GCC supports more
5944 // forms.
5945 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5946 unsigned Value = 0;
5947 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5948 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5949 << A->getAsString(Args) << A->getValue();
5950 else if (Value & (Value - 1))
5951 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5952 << A->getAsString(Args) << A->getValue();
5953 // Treat =0 as unspecified (use the target preference).
5954 if (Value)
5955 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5956 Twine(std::min(Value, 65536u))));
5957 }
5958
5959 if (Triple.isOSzOS()) {
5960 // On z/OS some of the system header feature macros need to
5961 // be defined to enable most cross platform projects to build
5962 // successfully. Ths include the libc++ library. A
5963 // complicating factor is that users can define these
5964 // macros to the same or different values. We need to add
5965 // the definition for these macros to the compilation command
5966 // if the user hasn't already defined them.
5967
5968 auto findMacroDefinition = [&](const std::string &Macro) {
5969 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5970 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5971 return M == Macro || M.find(Macro + '=') != std::string::npos;
5972 });
5973 };
5974
5975 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5976 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5977 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5978 // _OPEN_DEFAULT is required for XL compat
5979 if (!findMacroDefinition("_OPEN_DEFAULT"))
5980 CmdArgs.push_back("-D_OPEN_DEFAULT");
5981 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5982 // _XOPEN_SOURCE=600 is required for libcxx.
5983 if (!findMacroDefinition("_XOPEN_SOURCE"))
5984 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5985 }
5986 }
5987
5988 llvm::Reloc::Model RelocationModel;
5989 unsigned PICLevel;
5990 bool IsPIE;
5991 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5992 Arg *LastPICDataRelArg =
5993 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5994 options::OPT_mpic_data_is_text_relative);
5995 bool NoPICDataIsTextRelative = false;
5996 if (LastPICDataRelArg) {
5997 if (LastPICDataRelArg->getOption().matches(
5998 options::OPT_mno_pic_data_is_text_relative)) {
5999 NoPICDataIsTextRelative = true;
6000 if (!PICLevel)
6001 D.Diag(diag::err_drv_argument_only_allowed_with)
6002 << "-mno-pic-data-is-text-relative"
6003 << "-fpic/-fpie";
6004 }
6005 if (!Triple.isSystemZ())
6006 D.Diag(diag::err_drv_unsupported_opt_for_target)
6007 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
6008 : "-mpic-data-is-text-relative")
6009 << RawTriple.str();
6010 }
6011
6012 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
6013 RelocationModel == llvm::Reloc::ROPI_RWPI;
6014 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
6015 RelocationModel == llvm::Reloc::ROPI_RWPI;
6016
6017 if (Args.hasArg(options::OPT_mcmse) &&
6018 !Args.hasArg(options::OPT_fallow_unsupported)) {
6019 if (IsROPI)
6020 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
6021 if (IsRWPI)
6022 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
6023 }
6024
6025 if (IsROPI && types::isCXX(Input.getType()) &&
6026 !Args.hasArg(options::OPT_fallow_unsupported))
6027 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
6028
6029 const char *RMName = RelocationModelName(RelocationModel);
6030 if (RMName) {
6031 CmdArgs.push_back("-mrelocation-model");
6032 CmdArgs.push_back(RMName);
6033 }
6034 if (PICLevel > 0) {
6035 CmdArgs.push_back("-pic-level");
6036 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
6037 if (IsPIE)
6038 CmdArgs.push_back("-pic-is-pie");
6039 if (NoPICDataIsTextRelative)
6040 CmdArgs.push_back("-mcmodel=medium");
6041 }
6042
6043 if (RelocationModel == llvm::Reloc::ROPI ||
6044 RelocationModel == llvm::Reloc::ROPI_RWPI)
6045 CmdArgs.push_back("-fropi");
6046 if (RelocationModel == llvm::Reloc::RWPI ||
6047 RelocationModel == llvm::Reloc::ROPI_RWPI)
6048 CmdArgs.push_back("-frwpi");
6049
6050 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
6051 // values (e.g. 4, which has no triple representation, and invalid values).
6052 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
6053 StringRef Value = A->getValue();
6054 if (Value != "gnu" && Value != "5") {
6055 CmdArgs.push_back("-meabi");
6056 CmdArgs.push_back(A->getValue());
6057 }
6058 }
6059
6060 // -fsemantic-interposition is forwarded to CC1: set the
6061 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
6062 // make default visibility external linkage definitions dso_preemptable.
6063 //
6064 // -fno-semantic-interposition: if the target supports .Lfoo$local local
6065 // aliases (make default visibility external linkage definitions dso_local).
6066 // This is the CC1 default for ELF to match COFF/Mach-O.
6067 //
6068 // Otherwise use Clang's traditional behavior: like
6069 // -fno-semantic-interposition but local aliases are not used. So references
6070 // can be interposed if not optimized out.
6071 if (Triple.isOSBinFormatELF()) {
6072 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
6073 options::OPT_fno_semantic_interposition);
6074 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6075 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6076 bool SupportsLocalAlias =
6077 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6078 if (!A)
6079 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6080 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
6081 A->render(Args, CmdArgs);
6082 else if (!SupportsLocalAlias)
6083 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6084 }
6085 }
6086
6087 {
6088 std::string Model;
6089 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
6090 if (!TC.isThreadModelSupported(A->getValue()))
6091 D.Diag(diag::err_drv_invalid_thread_model_for_target)
6092 << A->getValue() << A->getAsString(Args);
6093 Model = A->getValue();
6094 } else
6095 Model = TC.getThreadModel();
6096 if (Model != "posix") {
6097 CmdArgs.push_back("-mthread-model");
6098 CmdArgs.push_back(Args.MakeArgString(Model));
6099 }
6100 }
6101
6102 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6103 StringRef Name = A->getValue();
6104 if (Name == "SVML") {
6105 if (Triple.getArch() != llvm::Triple::x86 &&
6106 Triple.getArch() != llvm::Triple::x86_64)
6107 D.Diag(diag::err_drv_unsupported_opt_for_target)
6108 << Name << Triple.getArchName();
6109 } else if (Name == "AMDLIBM") {
6110 if (Triple.getArch() != llvm::Triple::x86 &&
6111 Triple.getArch() != llvm::Triple::x86_64)
6112 D.Diag(diag::err_drv_unsupported_opt_for_target)
6113 << Name << Triple.getArchName();
6114 } else if (Name == "libmvec") {
6115 if (Triple.getArch() != llvm::Triple::x86 &&
6116 Triple.getArch() != llvm::Triple::x86_64 &&
6117 Triple.getArch() != llvm::Triple::aarch64 &&
6118 Triple.getArch() != llvm::Triple::aarch64_be)
6119 D.Diag(diag::err_drv_unsupported_opt_for_target)
6120 << Name << Triple.getArchName();
6121 } else if (Name == "SLEEF" || Name == "ArmPL") {
6122 if (Triple.getArch() != llvm::Triple::aarch64 &&
6123 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6124 D.Diag(diag::err_drv_unsupported_opt_for_target)
6125 << Name << Triple.getArchName();
6126 }
6127 A->render(Args, CmdArgs);
6128 }
6129
6130 if (Args.hasFlag(options::OPT_fmerge_all_constants,
6131 options::OPT_fno_merge_all_constants, false))
6132 CmdArgs.push_back("-fmerge-all-constants");
6133
6134 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
6135 options::OPT_fno_delete_null_pointer_checks);
6136
6137 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6138 options::OPT_fno_lifetime_dse);
6139
6140 // LLVM Code Generator Options.
6141
6142 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6143 if (!Triple.isOSAIX() || Triple.isPPC32())
6144 D.Diag(diag::err_drv_unsupported_opt_for_target)
6145 << A->getSpelling() << RawTriple.str();
6146 CmdArgs.push_back("-mabi=quadword-atomics");
6147 }
6148
6149 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6150 // Emit the unsupported option error until the Clang's library integration
6151 // support for 128-bit long double is available for AIX.
6152 if (Triple.isOSAIX())
6153 D.Diag(diag::err_drv_unsupported_opt_for_target)
6154 << A->getSpelling() << RawTriple.str();
6155 }
6156
6157 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6158 StringRef V = A->getValue(), V1 = V;
6159 unsigned Size;
6160 if (V1.consumeInteger(10, Size) || !V1.empty())
6161 D.Diag(diag::err_drv_invalid_argument_to_option)
6162 << V << A->getOption().getName();
6163 else
6164 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6165 }
6166
6167 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6168 options::OPT_fno_jump_tables);
6169 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6170 options::OPT_fno_profile_sample_accurate);
6171 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6172 options::OPT_fno_preserve_as_comments);
6173
6174 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6175 CmdArgs.push_back("-mregparm");
6176 CmdArgs.push_back(A->getValue());
6177 }
6178
6179 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6180 options::OPT_msvr4_struct_return)) {
6181 if (!TC.getTriple().isPPC32()) {
6182 D.Diag(diag::err_drv_unsupported_opt_for_target)
6183 << A->getSpelling() << RawTriple.str();
6184 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6185 CmdArgs.push_back("-maix-struct-return");
6186 } else {
6187 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6188 CmdArgs.push_back("-msvr4-struct-return");
6189 }
6190 }
6191
6192 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6193 options::OPT_freg_struct_return)) {
6194 if (TC.getArch() != llvm::Triple::x86) {
6195 D.Diag(diag::err_drv_unsupported_opt_for_target)
6196 << A->getSpelling() << RawTriple.str();
6197 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6198 CmdArgs.push_back("-fpcc-struct-return");
6199 } else {
6200 assert(A->getOption().matches(options::OPT_freg_struct_return));
6201 CmdArgs.push_back("-freg-struct-return");
6202 }
6203 }
6204
6205 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6206 if (Triple.getArch() == llvm::Triple::m68k)
6207 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6208 else
6209 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6210 }
6211
6212 if (Args.hasArg(options::OPT_fenable_matrix)) {
6213 // enable-matrix is needed by both the LangOpts and by LLVM.
6214 CmdArgs.push_back("-fenable-matrix");
6215 CmdArgs.push_back("-mllvm");
6216 CmdArgs.push_back("-enable-matrix");
6217 // Only handle default layout if matrix is enabled
6218 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6219 StringRef Val = A->getValue();
6220 if (Val == "row-major" || Val == "column-major") {
6221 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6222 CmdArgs.push_back("-mllvm");
6223 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6224
6225 } else {
6226 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6227 }
6228 }
6229 }
6230
6232 getFramePointerKind(Args, RawTriple);
6233 const char *FPKeepKindStr = nullptr;
6234 switch (FPKeepKind) {
6236 FPKeepKindStr = "-mframe-pointer=none";
6237 break;
6239 FPKeepKindStr = "-mframe-pointer=reserved";
6240 break;
6242 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6243 break;
6245 FPKeepKindStr = "-mframe-pointer=non-leaf";
6246 break;
6248 FPKeepKindStr = "-mframe-pointer=all";
6249 break;
6250 }
6251 assert(FPKeepKindStr && "unknown FramePointerKind");
6252 CmdArgs.push_back(FPKeepKindStr);
6253
6254 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6255 options::OPT_fno_zero_initialized_in_bss);
6256
6257 bool OFastEnabled = isOptimizationLevelFast(Args);
6258 if (Args.hasArg(options::OPT_Ofast))
6259 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6260 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6261 // enabled. This alias option is being used to simplify the hasFlag logic.
6262 OptSpecifier StrictAliasingAliasOption =
6263 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6264 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6265 // doesn't do any TBAA.
6266 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6267 options::OPT_fno_strict_aliasing,
6268 !IsWindowsMSVC && !IsUEFI))
6269 CmdArgs.push_back("-relaxed-aliasing");
6270 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6271 false))
6272 CmdArgs.push_back("-no-pointer-tbaa");
6273 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6274 options::OPT_fno_struct_path_tbaa, true))
6275 CmdArgs.push_back("-no-struct-path-tbaa");
6276
6277 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6278 options::OPT_fno_strict_bool,
6279 options::OPT_fno_strict_bool_EQ)) {
6280 StringRef BFM = "";
6281 if (A->getOption().matches(options::OPT_fstrict_bool))
6282 BFM = "strict";
6283 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6284 BFM = "nonstrict";
6285 else if (A->getValue() == StringRef("truncate"))
6286 BFM = "truncate";
6287 else if (A->getValue() == StringRef("nonzero"))
6288 BFM = "nonzero";
6289 else
6290 D.Diag(diag::err_drv_invalid_value)
6291 << A->getAsString(Args) << A->getValue();
6292 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6293 } else if (KernelOrKext) {
6294 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6295 CmdArgs.push_back("-load-bool-from-mem=truncate");
6296 }
6297
6298 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6299 options::OPT_fno_strict_enums);
6300 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6301 options::OPT_fno_strict_return);
6302 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6303 options::OPT_fno_allow_editor_placeholders);
6304 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6305 options::OPT_fno_strict_vtable_pointers);
6306 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6307 options::OPT_fno_force_emit_vtables);
6308 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6309 options::OPT_fno_optimize_sibling_calls);
6310 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6311 options::OPT_fno_escaping_block_tail_calls);
6312
6313 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6314 options::OPT_fno_fine_grained_bitfield_accesses);
6315
6316 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6317 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6318
6319 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6320 options::OPT_fno_experimental_omit_vtable_rtti);
6321
6322 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6323 options::OPT_fno_disable_block_signature_string);
6324
6325 // Handle segmented stacks.
6326 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6327 options::OPT_fno_split_stack);
6328
6329 // -fprotect-parens=0 is default.
6330 if (Args.hasFlag(options::OPT_fprotect_parens,
6331 options::OPT_fno_protect_parens, false))
6332 CmdArgs.push_back("-fprotect-parens");
6333
6334 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6335
6336 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6337 options::OPT_fno_atomic_remote_memory);
6338 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6339 options::OPT_fno_atomic_fine_grained_memory);
6340 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6341 options::OPT_fno_atomic_ignore_denormal_mode);
6342
6343 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6344 const llvm::Triple::ArchType Arch = TC.getArch();
6345 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6346 StringRef V = A->getValue();
6347 if (V == "64")
6348 CmdArgs.push_back("-fextend-arguments=64");
6349 else if (V != "32")
6350 D.Diag(diag::err_drv_invalid_argument_to_option)
6351 << A->getValue() << A->getOption().getName();
6352 } else
6353 D.Diag(diag::err_drv_unsupported_opt_for_target)
6354 << A->getOption().getName() << TripleStr;
6355 }
6356
6357 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6358 if (TC.getArch() == llvm::Triple::avr)
6359 A->render(Args, CmdArgs);
6360 else
6361 D.Diag(diag::err_drv_unsupported_opt_for_target)
6362 << A->getAsString(Args) << TripleStr;
6363 }
6364
6365 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6366 if (TC.getTriple().isX86())
6367 A->render(Args, CmdArgs);
6368 else if (TC.getTriple().isPPC() &&
6369 (A->getOption().getID() != options::OPT_mlong_double_80))
6370 A->render(Args, CmdArgs);
6371 else
6372 D.Diag(diag::err_drv_unsupported_opt_for_target)
6373 << A->getAsString(Args) << TripleStr;
6374 }
6375
6376 // Decide whether to use verbose asm. Verbose assembly is the default on
6377 // toolchains which have the integrated assembler on by default.
6378 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6379 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6380 IsIntegratedAssemblerDefault))
6381 CmdArgs.push_back("-fno-verbose-asm");
6382
6383 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6384 // use that to indicate the MC default in the backend.
6385 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6386 StringRef V = A->getValue();
6387 unsigned Num;
6388 if (V == "none")
6389 A->render(Args, CmdArgs);
6390 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6391 (V.empty() || (V.consume_front(".") &&
6392 !V.consumeInteger(10, Num) && V.empty())))
6393 A->render(Args, CmdArgs);
6394 else
6395 D.Diag(diag::err_drv_invalid_argument_to_option)
6396 << A->getValue() << A->getOption().getName();
6397 }
6398
6399 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6400 // option to disable integrated-as explicitly.
6402 CmdArgs.push_back("-no-integrated-as");
6403
6404 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6405 CmdArgs.push_back("-mdebug-pass");
6406 CmdArgs.push_back("Structure");
6407 }
6408 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6409 CmdArgs.push_back("-mdebug-pass");
6410 CmdArgs.push_back("Arguments");
6411 }
6412
6413 // Enable -mconstructor-aliases except on darwin, where we have to work around
6414 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6415 // code, where aliases aren't supported.
6416 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6417 CmdArgs.push_back("-mconstructor-aliases");
6418
6419 // Darwin's kernel doesn't support guard variables; just die if we
6420 // try to use them.
6421 if (KernelOrKext && RawTriple.isOSDarwin())
6422 CmdArgs.push_back("-fforbid-guard-variables");
6423
6424 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6425 options::OPT_mno_ms_bitfields)) {
6426 if (A->getOption().matches(options::OPT_mms_bitfields))
6427 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6428 else
6429 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6430 }
6431
6432 if (Triple.isOSCygMing()) {
6433 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6434 options::OPT_fno_auto_import);
6435 }
6436
6437 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6438 Triple.isX86() && IsWindowsMSVC))
6439 CmdArgs.push_back("-fms-volatile");
6440
6441 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6442 // defaults to -fno-direct-access-external-data. Pass the option if different
6443 // from the default.
6444 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6445 options::OPT_fno_direct_access_external_data)) {
6446 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6447 (PICLevel == 0))
6448 A->render(Args, CmdArgs);
6449 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6450 // Some targets default to -fno-direct-access-external-data even for
6451 // -fno-pic.
6452 CmdArgs.push_back("-fno-direct-access-external-data");
6453 }
6454
6455 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6456 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6457
6458 // -fhosted is default.
6459 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6460 // use Freestanding.
6461 bool Freestanding =
6462 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6463 KernelOrKext;
6464 if (Freestanding)
6465 CmdArgs.push_back("-ffreestanding");
6466
6467 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6468
6470 auto SanitizeArgs =
6472 Args.AddLastArg(CmdArgs,
6473 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6474
6475 // This is a coarse approximation of what llvm-gcc actually does, both
6476 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6477 // complicated ways.
6478 bool IsAsyncUnwindTablesDefault =
6480 bool IsSyncUnwindTablesDefault =
6482
6483 bool AsyncUnwindTables = Args.hasFlag(
6484 options::OPT_fasynchronous_unwind_tables,
6485 options::OPT_fno_asynchronous_unwind_tables,
6486 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6487 !Freestanding);
6488 bool UnwindTables =
6489 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6490 IsSyncUnwindTablesDefault && !Freestanding);
6491 if (AsyncUnwindTables)
6492 CmdArgs.push_back("-funwind-tables=2");
6493 else if (UnwindTables)
6494 CmdArgs.push_back("-funwind-tables=1");
6495
6496 // Sframe unwind tables are independent of the other types. Although also
6497 // defined for aarch64, only x86_64 support is implemented at the moment.
6498 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6499 if (Triple.isOSBinFormatELF() && Triple.isX86())
6500 CmdArgs.push_back("--gsframe");
6501 else
6502 D.Diag(diag::err_drv_unsupported_opt_for_target)
6503 << A->getOption().getName() << TripleStr;
6504 }
6505
6506 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6507 // `--gpu-use-aux-triple-only` is specified.
6508 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6509 const ArgList &HostArgs =
6510 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6511 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6512 if (!HostCPU.empty()) {
6513 CmdArgs.push_back("-aux-target-cpu");
6514 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6515 }
6516 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6517 /*ForAS*/ false, /*IsAux*/ true);
6518 }
6519
6520 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6522
6523 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6524
6525 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6526 StringRef Value = A->getValue();
6527 unsigned TLSSize = 0;
6528 Value.getAsInteger(10, TLSSize);
6529 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6530 D.Diag(diag::err_drv_unsupported_opt_for_target)
6531 << A->getOption().getName() << TripleStr;
6532 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6533 D.Diag(diag::err_drv_invalid_int_value)
6534 << A->getOption().getName() << Value;
6535 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6536 }
6537
6538 if (isTLSDESCEnabled(TC, Args))
6539 CmdArgs.push_back("-enable-tlsdesc");
6540
6541 // Add the target cpu
6542 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6543 if (!CPU.empty()) {
6544 CmdArgs.push_back("-target-cpu");
6545 CmdArgs.push_back(Args.MakeArgString(CPU));
6546 }
6547
6548 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6549
6550 // Add clang-cl arguments.
6551 types::ID InputType = Input.getType();
6552 if (D.IsCLMode())
6553 AddClangCLArgs(Args, InputType, CmdArgs);
6554
6555 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6556 llvm::codegenoptions::NoDebugInfo;
6558 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6559 DebugInfoKind, DwarfFission, IsUsingLTO);
6560
6561 // Add the split debug info name to the command lines here so we
6562 // can propagate it to the backend.
6563 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6564 (TC.getTriple().isOSBinFormatELF() ||
6565 TC.getTriple().isOSBinFormatWasm() ||
6566 TC.getTriple().isOSBinFormatCOFF()) &&
6569 if (SplitDWARF) {
6570 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6571 CmdArgs.push_back("-split-dwarf-file");
6572 CmdArgs.push_back(SplitDWARFOut);
6573 if (DwarfFission == DwarfFissionKind::Split) {
6574 CmdArgs.push_back("-split-dwarf-output");
6575 CmdArgs.push_back(SplitDWARFOut);
6576 }
6577 }
6578
6579 // Pass the linker version in use.
6580 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6581 CmdArgs.push_back("-target-linker-version");
6582 CmdArgs.push_back(A->getValue());
6583 }
6584
6585 // Explicitly error on some things we know we don't support and can't just
6586 // ignore.
6587 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6588 Arg *Unsupported;
6589 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6590 TC.getArch() == llvm::Triple::x86) {
6591 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6592 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6593 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6594 << Unsupported->getOption().getName();
6595 }
6596 // The faltivec option has been superseded by the maltivec option.
6597 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6598 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6599 << Unsupported->getOption().getName()
6600 << "please use -maltivec and include altivec.h explicitly";
6601 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6602 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6603 << Unsupported->getOption().getName() << "please use -mno-altivec";
6604 }
6605
6606 Args.AddAllArgs(CmdArgs, options::OPT_v);
6607
6608 if (Args.getLastArg(options::OPT_H)) {
6609 CmdArgs.push_back("-H");
6610 CmdArgs.push_back("-sys-header-deps");
6611 }
6612 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6613
6615 CmdArgs.push_back("-header-include-file");
6616 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6617 ? D.CCPrintHeadersFilename.c_str()
6618 : "-");
6619 CmdArgs.push_back("-sys-header-deps");
6620 CmdArgs.push_back(Args.MakeArgString(
6621 "-header-include-format=" +
6623 CmdArgs.push_back(Args.MakeArgString(
6624 "-header-include-filtering=" +
6626 }
6627 Args.AddLastArg(CmdArgs, options::OPT_P);
6628 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6629
6630 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6631 CmdArgs.push_back("-diagnostic-log-file");
6632 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6633 ? D.CCLogDiagnosticsFilename.c_str()
6634 : "-");
6635 }
6636
6637 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6638 // crashes.
6639 if (D.CCGenDiagnostics)
6640 CmdArgs.push_back("-disable-pragma-debug-crash");
6641
6642 // Allow backend to put its diagnostic files in the same place as frontend
6643 // crash diagnostics files.
6644 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6645 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6646 CmdArgs.push_back("-mllvm");
6647 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6648 }
6649
6650 addSeparateSectionFlags(Triple, Args, CmdArgs);
6651
6652 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6653 options::OPT_fno_basic_block_address_map)) {
6654 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6655 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6656 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6657 A->render(Args, CmdArgs);
6658 } else {
6659 D.Diag(diag::err_drv_unsupported_opt_for_target)
6660 << A->getAsString(Args) << TripleStr;
6661 }
6662 }
6663
6664 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6665 StringRef Val = A->getValue();
6666 if (Val == "labels") {
6667 D.Diag(diag::warn_drv_deprecated_arg)
6668 << A->getAsString(Args) << /*hasReplacement=*/true
6669 << "-fbasic-block-address-map";
6670 CmdArgs.push_back("-fbasic-block-address-map");
6671 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6672 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6673 D.Diag(diag::err_drv_invalid_value)
6674 << A->getAsString(Args) << A->getValue();
6675 else
6676 A->render(Args, CmdArgs);
6677 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6678 // "all" is not supported on AArch64 since branch relaxation creates new
6679 // basic blocks for some cross-section branches.
6680 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6681 D.Diag(diag::err_drv_invalid_value)
6682 << A->getAsString(Args) << A->getValue();
6683 else
6684 A->render(Args, CmdArgs);
6685 } else if (Triple.isNVPTX()) {
6686 // Do not pass the option to the GPU compilation. We still want it enabled
6687 // for the host-side compilation, so seeing it here is not an error.
6688 } else if (Val != "none") {
6689 // =none is allowed everywhere. It's useful for overriding the option
6690 // and is the same as not specifying the option.
6691 D.Diag(diag::err_drv_unsupported_opt_for_target)
6692 << A->getAsString(Args) << TripleStr;
6693 }
6694 }
6695
6696 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6697 options::OPT_fno_unique_section_names);
6698 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6699 options::OPT_fno_separate_named_sections);
6700 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6701 options::OPT_fno_unique_internal_linkage_names);
6702 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6703 options::OPT_fno_unique_basic_block_section_names);
6704
6705 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6706
6707 if (Arg *A =
6708 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6709 options::OPT_fno_partition_static_data_sections)) {
6710 if (!A->getOption().matches(
6711 options::OPT_fno_partition_static_data_sections)) {
6712 // This codegen pass is only available on x86 and AArch64 ELF targets.
6713 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6714 A->render(Args, CmdArgs);
6715 CmdArgs.push_back("-mllvm");
6716 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6717 } else
6718 D.Diag(diag::err_drv_unsupported_opt_for_target)
6719 << A->getAsString(Args) << TripleStr;
6720 }
6721 }
6722
6723 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6724 options::OPT_finstrument_functions_after_inlining,
6725 options::OPT_finstrument_function_entry_bare);
6726 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6727 options::OPT_fno_convergent_functions);
6728
6729 // NVPTX doesn't support PGO or coverage
6730 if (!Triple.isNVPTX())
6731 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6732
6733 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6734
6735 if (getLastProfileSampleUseArg(Args) &&
6736 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6737 options::OPT_fno_sample_profile_use_profi, true)) {
6738 CmdArgs.push_back("-mllvm");
6739 CmdArgs.push_back("-sample-profile-use-profi");
6740 }
6741
6742 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6743 if (RawTriple.isPS() &&
6744 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6745 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6746 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6747 }
6748
6749 // Pass options for controlling the default header search paths.
6750 if (Args.hasArg(options::OPT_nostdinc)) {
6751 CmdArgs.push_back("-nostdsysteminc");
6752 CmdArgs.push_back("-nobuiltininc");
6753 } else {
6754 if (Args.hasArg(options::OPT_nostdlibinc))
6755 CmdArgs.push_back("-nostdsysteminc");
6756 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6757 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6758 }
6759
6760 // Pass the path to compiler resource files.
6761 CmdArgs.push_back("-resource-dir");
6762 CmdArgs.push_back(D.ResourceDir.c_str());
6763
6764 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6765
6766 // Add preprocessing options like -I, -D, etc. if we are using the
6767 // preprocessor.
6768 //
6769 // FIXME: Support -fpreprocessed
6771 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6772
6773 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6774 // that "The compiler can only warn and ignore the option if not recognized".
6775 // When building with ccache, it will pass -D options to clang even on
6776 // preprocessed inputs and configure concludes that -fPIC is not supported.
6777 Args.ClaimAllArgs(options::OPT_D);
6778
6779 // Warn about ignored options to clang.
6780 for (const Arg *A :
6781 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6782 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6783 A->claim();
6784 }
6785
6786 for (const Arg *A :
6787 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6788 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6789 A->claim();
6790 }
6791
6792 claimNoWarnArgs(Args);
6793
6794 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6795
6796 for (const Arg *A :
6797 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6798 A->claim();
6799 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6800 unsigned WarningNumber;
6801 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6802 D.Diag(diag::err_drv_invalid_int_value)
6803 << A->getAsString(Args) << A->getValue();
6804 continue;
6805 }
6806
6807 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6808 CmdArgs.push_back(Args.MakeArgString(
6809 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6810 }
6811 continue;
6812 }
6813 A->render(Args, CmdArgs);
6814 }
6815
6816 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6817
6818 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6819 CmdArgs.push_back("-pedantic");
6820 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6821 Args.AddLastArg(CmdArgs, options::OPT_w);
6822
6823 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6824 options::OPT_fno_fixed_point);
6825
6826 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6827 options::OPT_fno_experimental_overflow_behavior_types);
6828
6829 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6830 A->render(Args, CmdArgs);
6831
6832 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6833 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6834
6835 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6836 options::OPT_fno_experimental_omit_vtable_rtti);
6837
6838 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6839 A->render(Args, CmdArgs);
6840
6841 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6842 // (-ansi is equivalent to -std=c89 or -std=c++98).
6843 //
6844 // If a std is supplied, only add -trigraphs if it follows the
6845 // option.
6846 bool ImplyVCPPCVer = false;
6847 bool ImplyVCPPCXXVer = false;
6848 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6849 if (Std) {
6850 if (Std->getOption().matches(options::OPT_ansi))
6851 if (types::isCXX(InputType))
6852 CmdArgs.push_back("-std=c++98");
6853 else
6854 CmdArgs.push_back("-std=c89");
6855 else {
6856 if (IsSYCL) {
6857 const LangStandard *LangStd =
6858 LangStandard::getLangStandardForName(Std->getValue());
6859 if (LangStd) {
6860 // Use of -std= with 'C' is not supported for SYCL.
6861 if (LangStd->getLanguage() == Language::C)
6862 D.Diag(diag::err_drv_argument_not_allowed_with)
6863 << Std->getAsString(Args) << "-fsycl";
6864 // SYCL requires C++17 or later.
6865 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6866 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6867 }
6868 }
6869 Std->render(Args, CmdArgs);
6870 }
6871
6872 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6873 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6874 options::OPT_ftrigraphs,
6875 options::OPT_fno_trigraphs))
6876 if (A != Std)
6877 A->render(Args, CmdArgs);
6878 } else {
6879 // Honor -std-default.
6880 //
6881 // FIXME: Clang doesn't correctly handle -std= when the input language
6882 // doesn't match. For the time being just ignore this for C++ inputs;
6883 // eventually we want to do all the standard defaulting here instead of
6884 // splitting it between the driver and clang -cc1.
6885 if (!types::isCXX(InputType)) {
6886 if (!Args.hasArg(options::OPT__SLASH_std)) {
6887 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6888 /*Joined=*/true);
6889 } else
6890 ImplyVCPPCVer = true;
6891 }
6892 else if (IsWindowsMSVC)
6893 ImplyVCPPCXXVer = true;
6894
6895 if (IsSYCL && types::isCXX(InputType) &&
6896 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6897 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6898 // on the command line will override. On Windows MSVC, this is handled
6899 // by the ImplyVCPPCXXVer path below.
6900 CmdArgs.push_back("-std=c++17");
6901
6902 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6903 options::OPT_fno_trigraphs);
6904 }
6905
6906 // GCC's behavior for -Wwrite-strings is a bit strange:
6907 // * In C, this "warning flag" changes the types of string literals from
6908 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6909 // for the discarded qualifier.
6910 // * In C++, this is just a normal warning flag.
6911 //
6912 // Implementing this warning correctly in C is hard, so we follow GCC's
6913 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6914 // a non-const char* in C, rather than using this crude hack.
6915 if (!types::isCXX(InputType)) {
6916 // FIXME: This should behave just like a warning flag, and thus should also
6917 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6918 Arg *WriteStrings =
6919 Args.getLastArg(options::OPT_Wwrite_strings,
6920 options::OPT_Wno_write_strings, options::OPT_w);
6921 if (WriteStrings &&
6922 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6923 CmdArgs.push_back("-fconst-strings");
6924 }
6925
6926 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6927 // during C++ compilation, which it is by default. GCC keeps this define even
6928 // in the presence of '-w', match this behavior bug-for-bug.
6929 if (types::isCXX(InputType) &&
6930 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6931 true)) {
6932 CmdArgs.push_back("-fdeprecated-macro");
6933 }
6934
6935 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6936 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6937 if (Asm->getOption().matches(options::OPT_fasm))
6938 CmdArgs.push_back("-fgnu-keywords");
6939 else
6940 CmdArgs.push_back("-fno-gnu-keywords");
6941 }
6942
6943 if (!ShouldEnableAutolink(Args, TC, JA))
6944 CmdArgs.push_back("-fno-autolink");
6945
6946 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6947 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6948 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6949 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6950
6951 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6952
6953 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6954 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6955 Args.AddLastArg(CmdArgs,
6956 options::OPT_fno_experimental_new_constant_interpreter);
6957 } else {
6958 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6959 Args.AddLastArg(CmdArgs,
6960 options::OPT_fexperimental_new_constant_interpreter);
6961 }
6962
6963 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6964 CmdArgs.push_back("-fbracket-depth");
6965 CmdArgs.push_back(A->getValue());
6966 }
6967
6968 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6969 options::OPT_Wlarge_by_value_copy_def)) {
6970 if (A->getNumValues()) {
6971 StringRef bytes = A->getValue();
6972 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6973 } else
6974 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6975 }
6976
6977 if (Args.hasArg(options::OPT_relocatable_pch))
6978 CmdArgs.push_back("-relocatable-pch");
6979 Args.AddLastArg(CmdArgs, options::OPT_fpch_base_dir_is_cwd);
6980
6981 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6982 static const char *kCFABIs[] = {
6983 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6984 };
6985
6986 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6987 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6988 else
6989 A->render(Args, CmdArgs);
6990 }
6991
6992 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6993 CmdArgs.push_back("-fconstant-string-class");
6994 CmdArgs.push_back(A->getValue());
6995 }
6996
6997 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6998 CmdArgs.push_back("-fconstant-array-class");
6999 CmdArgs.push_back(A->getValue());
7000 }
7001 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
7002 CmdArgs.push_back("-fconstant-dictionary-class");
7003 CmdArgs.push_back(A->getValue());
7004 }
7005 if (Arg *A =
7006 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
7007 CmdArgs.push_back("-fconstant-integer-number-class");
7008 CmdArgs.push_back(A->getValue());
7009 }
7010 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
7011 CmdArgs.push_back("-fconstant-float-number-class");
7012 CmdArgs.push_back(A->getValue());
7013 }
7014 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
7015 CmdArgs.push_back("-fconstant-double-number-class");
7016 CmdArgs.push_back(A->getValue());
7017 }
7018
7019 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
7020 CmdArgs.push_back("-ftabstop");
7021 CmdArgs.push_back(A->getValue());
7022 }
7023
7024 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
7025 options::OPT_fno_experimental_call_graph_section, false))
7026 CmdArgs.push_back("-fexperimental-call-graph-section");
7027
7028 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
7029 options::OPT_fno_stack_size_section);
7030
7031 if (Args.hasArg(options::OPT_fstack_usage)) {
7032 CmdArgs.push_back("-stack-usage-file");
7033
7034 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7035 SmallString<128> OutputFilename(OutputOpt->getValue());
7036 llvm::sys::path::replace_extension(OutputFilename, "su");
7037 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7038 } else
7039 CmdArgs.push_back(
7040 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
7041 }
7042
7043 CmdArgs.push_back("-ferror-limit");
7044 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
7045 CmdArgs.push_back(A->getValue());
7046 else
7047 CmdArgs.push_back("19");
7048
7049 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
7050 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
7051 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
7052 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
7053 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
7054
7055 // Pass -fmessage-length=.
7056 unsigned MessageLength = 0;
7057 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
7058 StringRef V(A->getValue());
7059 if (V.getAsInteger(0, MessageLength))
7060 D.Diag(diag::err_drv_invalid_argument_to_option)
7061 << V << A->getOption().getName();
7062 } else {
7063 // If -fmessage-length=N was not specified, determine whether this is a
7064 // terminal and, if so, implicitly define -fmessage-length appropriately.
7065 MessageLength = llvm::sys::Process::StandardErrColumns();
7066 }
7067 if (MessageLength != 0)
7068 CmdArgs.push_back(
7069 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
7070
7071 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
7072 CmdArgs.push_back(
7073 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
7074
7075 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
7076 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
7077 Twine(A->getValue(0))));
7078
7079 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7080 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
7081 options::OPT_fvisibility_ms_compat)) {
7082 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
7083 A->render(Args, CmdArgs);
7084 } else {
7085 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7086 CmdArgs.push_back("-fvisibility=hidden");
7087 CmdArgs.push_back("-ftype-visibility=default");
7088 }
7089 } else if (IsOpenMPDevice) {
7090 // When compiling for the OpenMP device we want protected visibility by
7091 // default. This prevents the device from accidentally preempting code on
7092 // the host, makes the system more robust, and improves performance.
7093 CmdArgs.push_back("-fvisibility=protected");
7094 }
7095
7096 // PS4/PS5 process these options in addClangTargetOptions.
7097 if (!RawTriple.isPS()) {
7098 if (const Arg *A =
7099 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
7100 options::OPT_fno_visibility_from_dllstorageclass)) {
7101 if (A->getOption().matches(
7102 options::OPT_fvisibility_from_dllstorageclass)) {
7103 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
7104 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
7105 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
7106 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
7107 Args.AddLastArg(CmdArgs,
7108 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7109 }
7110 }
7111 }
7112
7113 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
7114 options::OPT_fno_visibility_inlines_hidden, false))
7115 CmdArgs.push_back("-fvisibility-inlines-hidden");
7116
7117 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
7118 options::OPT_fno_visibility_inlines_hidden_static_local_var);
7119
7120 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7121 // -fvisibility-global-new-delete=force-hidden.
7122 if (const Arg *A =
7123 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
7124 D.Diag(diag::warn_drv_deprecated_arg)
7125 << A->getAsString(Args) << /*hasReplacement=*/true
7126 << "-fvisibility-global-new-delete=force-hidden";
7127 }
7128
7129 if (const Arg *A =
7130 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7131 options::OPT_fvisibility_global_new_delete_hidden)) {
7132 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7133 A->render(Args, CmdArgs);
7134 } else {
7135 assert(A->getOption().matches(
7136 options::OPT_fvisibility_global_new_delete_hidden));
7137 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7138 }
7139 }
7140
7141 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7142
7143 if (Args.hasFlag(options::OPT_fnew_infallible,
7144 options::OPT_fno_new_infallible, false))
7145 CmdArgs.push_back("-fnew-infallible");
7146
7147 if (Args.hasFlag(options::OPT_fno_operator_names,
7148 options::OPT_foperator_names, false))
7149 CmdArgs.push_back("-fno-operator-names");
7150
7151 // Forward -f (flag) options which we can pass directly.
7152 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7153 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7154 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7155 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7156 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7157 options::OPT_fno_raw_string_literals);
7158
7159 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7160 Triple.hasDefaultEmulatedTLS()))
7161 CmdArgs.push_back("-femulated-tls");
7162
7163 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7164 options::OPT_fno_check_new);
7165
7166 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7167 // FIXME: There's no reason for this to be restricted to some backend.
7168 // The backend code needs to be changed to include the appropriate function
7169 // calls automatically.
7170 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7171 D.Diag(diag::err_drv_unsupported_opt_for_target)
7172 << A->getAsString(Args) << TripleStr;
7173 }
7174
7175 // AltiVec-like language extensions aren't relevant for assembling.
7176 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7177 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7178
7179 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7180 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7181
7182 // Forward flags for OpenMP. We don't do this if the current action is an
7183 // device offloading action other than OpenMP.
7184 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7185 options::OPT_fno_openmp, false) &&
7186 !Args.hasFlag(options::OPT_foffload_via_llvm,
7187 options::OPT_fno_offload_via_llvm, false) &&
7190
7191 // Determine if target-fast optimizations should be enabled
7192 bool TargetFastUsed =
7193 Args.hasFlag(options::OPT_fopenmp_target_fast,
7194 options::OPT_fno_openmp_target_fast, OFastEnabled);
7195 switch (D.getOpenMPRuntime(Args)) {
7196 case Driver::OMPRT_OMP:
7198 // Clang can generate useful OpenMP code for these two runtime libraries.
7199 CmdArgs.push_back("-fopenmp");
7200
7201 // If no option regarding the use of TLS in OpenMP codegeneration is
7202 // given, decide a default based on the target. Otherwise rely on the
7203 // options and pass the right information to the frontend.
7204 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7205 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7206 CmdArgs.push_back("-fnoopenmp-use-tls");
7207 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7208 options::OPT_fno_openmp_simd);
7209 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7210 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7211 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7212 options::OPT_fno_openmp_extensions, /*Default=*/true))
7213 CmdArgs.push_back("-fno-openmp-extensions");
7214 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7215 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7216 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7217 // effect: the teams reduction buffer is sized at kernel launch by the
7218 // offload plugin to match the actual number of teams. Honoring a
7219 // smaller user-supplied value would silently truncate the buffer for
7220 // larger launches.
7221 if (Arg *A = Args.getLastArg(
7222 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7223 D.Diag(diag::warn_drv_deprecated_custom)
7224 << A->getAsString(Args)
7225 << "the value is ignored; the teams reduction buffer is sized "
7226 "automatically at kernel launch";
7227 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7228 options::OPT_fno_openmp_optimistic_collapse,
7229 /*Default=*/false))
7230 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7231
7232 // When in OpenMP offloading mode with NVPTX target, forward
7233 // cuda-mode flag
7234 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7235 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7236 CmdArgs.push_back("-fopenmp-cuda-mode");
7237
7238 // When in OpenMP offloading mode, enable debugging on the device.
7239 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7240 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7241 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7242 CmdArgs.push_back("-fopenmp-target-debug");
7243
7244 // When in OpenMP offloading mode, forward assumptions information about
7245 // thread and team counts in the device.
7246 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7247 options::OPT_fno_openmp_assume_teams_oversubscription,
7248 /*Default=*/TargetFastUsed))
7249 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7250 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7251 options::OPT_fno_openmp_assume_threads_oversubscription,
7252 /*Default=*/TargetFastUsed))
7253 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7254
7255 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7256 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7257 options::OPT_fno_openmp_assume_no_thread_state,
7258 /*Default=*/TargetFastUsed))
7259 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7260
7261 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7262 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7263 options::OPT_fno_openmp_assume_no_nested_parallelism,
7264 /*Default=*/TargetFastUsed))
7265 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7266
7267 // Handle -fopenmp-target-atomic-reduction.
7268 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7269 options::OPT_fno_openmp_target_atomic_reduction,
7270 /*Default=*/false))
7271 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7272
7273 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7274 CmdArgs.push_back("-fopenmp-offload-mandatory");
7275 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7276 CmdArgs.push_back("-fopenmp-force-usm");
7277 break;
7278 default:
7279 // By default, if Clang doesn't know how to generate useful OpenMP code
7280 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7281 // down to the actual compilation.
7282 // FIXME: It would be better to have a mode which *only* omits IR
7283 // generation based on the OpenMP support so that we get consistent
7284 // semantic analysis, etc.
7285 break;
7286 }
7287 } else {
7288 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7289 options::OPT_fno_openmp_simd);
7290 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7291 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7292 options::OPT_fno_openmp_extensions);
7293 }
7294 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7295 // runtime.
7296 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7297 options::OPT_fno_offload_via_llvm, false))
7298 CmdArgs.push_back("-foffload-via-llvm");
7299
7300 const XRayArgs &XRay = TC.getXRayArgs(Args);
7301 XRay.addArgs(TC, Args, CmdArgs, InputType);
7302
7303 for (const auto &Filename :
7304 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7305 if (D.getVFS().exists(Filename))
7306 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7307 else
7308 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7309 }
7310
7311 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7312 StringRef S0 = A->getValue(), S = S0;
7313 unsigned Size, Offset = 0;
7314 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7315 !Triple.isX86() && !Triple.isSystemZ() &&
7316 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7317 Triple.getArch() == llvm::Triple::ppc64 ||
7318 Triple.getArch() == llvm::Triple::ppc64le)))
7319 D.Diag(diag::err_drv_unsupported_opt_for_target)
7320 << A->getAsString(Args) << TripleStr;
7321 else if (S.consumeInteger(10, Size) ||
7322 (!S.empty() &&
7323 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7324 (!S.empty() && (!S.consume_front(",") || S.empty())))
7325 D.Diag(diag::err_drv_invalid_argument_to_option)
7326 << S0 << A->getOption().getName();
7327 else if (Size < Offset)
7328 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7329 else {
7330 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7331 CmdArgs.push_back(Args.MakeArgString(
7332 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7333 if (!S.empty())
7334 CmdArgs.push_back(
7335 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7336 }
7337 }
7338
7339 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7340
7341 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7342 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7343
7344 for (const auto &A :
7345 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7346 CmdArgs.push_back(
7347 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7348
7349 if (TC.SupportsProfiling()) {
7350 Args.AddLastArg(CmdArgs, options::OPT_pg);
7351
7352 llvm::Triple::ArchType Arch = TC.getArch();
7353 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7354 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7355 A->render(Args, CmdArgs);
7356 else
7357 D.Diag(diag::err_drv_unsupported_opt_for_target)
7358 << A->getAsString(Args) << TripleStr;
7359 }
7360 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7361 if (Arch == llvm::Triple::systemz ||
7362 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7363 A->render(Args, CmdArgs);
7364 else
7365 D.Diag(diag::err_drv_unsupported_opt_for_target)
7366 << A->getAsString(Args) << TripleStr;
7367 }
7368 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7369 if (Arch == llvm::Triple::systemz ||
7370 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7371 A->render(Args, CmdArgs);
7372 else
7373 D.Diag(diag::err_drv_unsupported_opt_for_target)
7374 << A->getAsString(Args) << TripleStr;
7375 }
7376 }
7377
7378 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7379 if (TC.getTriple().isOSzOS()) {
7380 D.Diag(diag::err_drv_unsupported_opt_for_target)
7381 << A->getAsString(Args) << TripleStr;
7382 }
7383 }
7384 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7385 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7386 D.Diag(diag::err_drv_unsupported_opt_for_target)
7387 << A->getAsString(Args) << TripleStr;
7388 }
7389 }
7390 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7391 if (A->getOption().matches(options::OPT_p)) {
7392 A->claim();
7393 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7394 CmdArgs.push_back("-pg");
7395 }
7396 }
7397
7398 // Reject AIX-specific link options on other targets.
7399 if (!TC.getTriple().isOSAIX()) {
7400 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7401 options::OPT_mxcoff_build_id_EQ)) {
7402 D.Diag(diag::err_drv_unsupported_opt_for_target)
7403 << A->getSpelling() << TripleStr;
7404 }
7405 }
7406
7407 if (Args.getLastArg(options::OPT_fapple_kext) ||
7408 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7409 CmdArgs.push_back("-fapple-kext");
7410
7411 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7412 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7413 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7414 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7415 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7416 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7417 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7418 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7419 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7420 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7421 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7422
7423 if (const char *Name = C.getTimeTraceFile(&JA)) {
7424 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7425 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7426 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7427 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_compress_EQ);
7428 }
7429
7430 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7431 CmdArgs.push_back("-ftrapv-handler");
7432 CmdArgs.push_back(A->getValue());
7433 }
7434
7435 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7436
7437 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7438 options::OPT_fno_finite_loops);
7439
7440 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7441 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7442 options::OPT_fno_unroll_loops);
7443 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7444 options::OPT_fno_loop_interchange);
7445 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7446 options::OPT_fno_experimental_loop_fusion);
7447
7448 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7449
7450 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7451
7452 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7453 options::OPT_mno_speculative_load_hardening);
7454
7455 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7456 RenderSCPOptions(TC, Args, CmdArgs);
7457 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7458
7459 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7460
7461 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7462 options::OPT_mno_stackrealign);
7463
7464 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7465 StringRef Value = A->getValue();
7466 int64_t Alignment = 0;
7467 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7468 D.Diag(diag::err_drv_invalid_argument_to_option)
7469 << Value << A->getOption().getName();
7470 else if (Alignment & (Alignment - 1))
7471 D.Diag(diag::err_drv_alignment_not_power_of_two)
7472 << A->getAsString(Args) << Value;
7473 else
7474 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7475 }
7476
7477 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7478 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7479
7480 if (!Size.empty())
7481 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7482 else
7483 CmdArgs.push_back("-mstack-probe-size=0");
7484 }
7485
7486 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7487 options::OPT_mno_stack_arg_probe);
7488
7489 if (Arg *A = Args.getLastArg(options::OPT_msmall_int_abi_compat_EQ))
7490 A->render(Args, CmdArgs);
7491
7492 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7493 options::OPT_mno_restrict_it)) {
7494 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7495 CmdArgs.push_back("-mllvm");
7496 CmdArgs.push_back("-arm-restrict-it");
7497 } else {
7498 CmdArgs.push_back("-mllvm");
7499 CmdArgs.push_back("-arm-default-it");
7500 }
7501 }
7502
7503 // Forward -cl options to -cc1
7504 RenderOpenCLOptions(Args, CmdArgs, InputType);
7505
7506 // Forward hlsl options to -cc1
7507 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7508
7509 // Forward OpenACC options to -cc1
7510 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7511
7512 if (IsHIP) {
7513 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7514 options::OPT_fno_hip_new_launch_api, true))
7515 CmdArgs.push_back("-fhip-new-launch-api");
7516 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7517 options::OPT_fno_gpu_allow_device_init);
7518 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7519 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7520 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7521 options::OPT_fno_hip_kernel_arg_name);
7522 if (TC.getTriple().isSPIRV() &&
7523 TC.getTriple().getVendor() == llvm::Triple::VendorType::AMD)
7524 Args.addLastArg(CmdArgs, options::OPT_fenable_spirv_size_optimization);
7525 }
7526
7527 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7528 CmdArgs.push_back("-fgpu-rdc");
7529
7530 if (IsCuda || IsHIP) {
7531 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7532 options::OPT_fno_gpu_defer_diag);
7533 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7534 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7535 false)) {
7536 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7537 CmdArgs.push_back("-fgpu-defer-diag");
7538 }
7539 }
7540
7541 // Forward --no-offloadlib to -cc1.
7542 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7543 CmdArgs.push_back("--no-offloadlib");
7544
7545 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7546 CmdArgs.push_back(
7547 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7548
7549 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7550 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7551 SA->getValue()));
7552 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7553 // Emit IBT endbr64 instructions by default
7554 CmdArgs.push_back("-fcf-protection=branch");
7555 // jump-table can generate indirect jumps, which are not permitted
7556 CmdArgs.push_back("-fno-jump-tables");
7557 }
7558
7559 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7560 CmdArgs.push_back(
7561 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7562
7563 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7564
7565 // Forward -f options with positive and negative forms; we translate these by
7566 // hand. Do not propagate PGO options to the GPU-side compilations as the
7567 // profile info is for the host-side compilation only.
7568 if (!(IsCudaDevice || IsHIPDevice)) {
7569 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7570 auto *PGOArg = Args.getLastArg(
7571 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7572 options::OPT_fcs_profile_generate,
7573 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7574 options::OPT_fprofile_use_EQ);
7575 if (PGOArg)
7576 D.Diag(diag::err_drv_argument_not_allowed_with)
7577 << "SampleUse with PGO options";
7578
7579 StringRef fname = A->getValue();
7580 if (!llvm::sys::fs::exists(fname))
7581 D.Diag(diag::err_drv_no_such_file) << fname;
7582 else
7583 A->render(Args, CmdArgs);
7584 }
7585 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7586
7587 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7588 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7589 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7590 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7591 // off.
7592 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7593 options::OPT_fno_unique_internal_linkage_names, true))
7594 CmdArgs.push_back("-funique-internal-linkage-names");
7595 }
7596 }
7597 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7598
7599 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7600 options::OPT_fno_assume_sane_operator_new);
7601
7602 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7603 CmdArgs.push_back("-fapinotes");
7604 if (Args.hasFlag(options::OPT_fapinotes_modules,
7605 options::OPT_fno_apinotes_modules, false))
7606 CmdArgs.push_back("-fapinotes-modules");
7607 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7608
7609 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7610 options::OPT_fno_swift_version_independent_apinotes, false))
7611 CmdArgs.push_back("-fswift-version-independent-apinotes");
7612
7613 // -fblocks=0 is default.
7614 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7615 TC.IsBlocksDefault()) ||
7616 (Args.hasArg(options::OPT_fgnu_runtime) &&
7617 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7618 !Args.hasArg(options::OPT_fno_blocks))) {
7619 CmdArgs.push_back("-fblocks");
7620
7621 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7622 CmdArgs.push_back("-fblocks-runtime-optional");
7623 }
7624
7625 // -fencode-extended-block-signature=1 is default.
7627 CmdArgs.push_back("-fencode-extended-block-signature");
7628
7629 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7630 options::OPT_fno_coro_aligned_allocation, false) &&
7631 types::isCXX(InputType))
7632 CmdArgs.push_back("-fcoro-aligned-allocation");
7633
7634 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7635 /*Default=*/false))
7636 CmdArgs.push_back("-fdefer-ts");
7637
7638 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7639 options::OPT_fno_double_square_bracket_attributes);
7640
7641 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7642 options::OPT_fno_access_control);
7643 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7644 options::OPT_fno_elide_constructors);
7645
7646 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7647
7648 if (KernelOrKext || (types::isCXX(InputType) &&
7649 (RTTIMode == ToolChain::RM_Disabled)))
7650 CmdArgs.push_back("-fno-rtti");
7651
7652 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7653 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7654 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7655 CmdArgs.push_back("-fshort-enums");
7656
7657 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7658
7659 // -fuse-cxa-atexit is default.
7660 if (!Args.hasFlag(
7661 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7662 !RawTriple.isOSAIX() &&
7663 (!RawTriple.isOSWindows() ||
7664 RawTriple.isWindowsCygwinEnvironment()) &&
7665 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7666 RawTriple.hasEnvironment())) ||
7667 KernelOrKext)
7668 CmdArgs.push_back("-fno-use-cxa-atexit");
7669
7670 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7671 options::OPT_fno_register_global_dtors_with_atexit,
7672 RawTriple.isOSDarwin() && !KernelOrKext))
7673 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7674
7675 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7676 options::OPT_fno_use_line_directives);
7677
7678 // -fno-minimize-whitespace is default.
7679 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7680 options::OPT_fno_minimize_whitespace, false)) {
7681 types::ID InputType = Inputs[0].getType();
7682 if (!isDerivedFromC(InputType))
7683 D.Diag(diag::err_drv_opt_unsupported_input_type)
7684 << "-fminimize-whitespace" << types::getTypeName(InputType);
7685 CmdArgs.push_back("-fminimize-whitespace");
7686 }
7687
7688 // -fno-keep-system-includes is default.
7689 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7690 options::OPT_fno_keep_system_includes, false)) {
7691 types::ID InputType = Inputs[0].getType();
7692 if (!isDerivedFromC(InputType))
7693 D.Diag(diag::err_drv_opt_unsupported_input_type)
7694 << "-fkeep-system-includes" << types::getTypeName(InputType);
7695 CmdArgs.push_back("-fkeep-system-includes");
7696 }
7697
7698 // -fms-extensions=0 is default.
7699 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7700 IsWindowsMSVC || IsUEFI))
7701 CmdArgs.push_back("-fms-extensions");
7702
7703 // -fms-compatibility=0 is default.
7704 bool IsMSVCCompat = Args.hasFlag(
7705 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7706 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7707 options::OPT_fno_ms_extensions, true)));
7708 if (IsMSVCCompat) {
7709 CmdArgs.push_back("-fms-compatibility");
7710 if (!types::isCXX(Input.getType()) &&
7711 Args.hasArg(options::OPT_fms_define_stdc))
7712 CmdArgs.push_back("-fms-define-stdc");
7713 }
7714
7715 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7716 // clang and flang.
7717 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7718
7719 // -fms-anonymous-structs is disabled by default.
7720 // Determine whether to enable Microsoft named anonymous struct/union support.
7721 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7722 // where the feature can be:
7723 // - Explicitly enabled via -fms-anonymous-structs.
7724 // - Explicitly disabled via fno-ms-anonymous-structs
7725 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7726 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7727 //
7728 // When multiple relevent options are present, the last option on the command
7729 // line takes precedence. This allows users to selectively override implicit
7730 // enablement. Examples:
7731 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7732 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7733 auto MSAnonymousStructsOptionToUseOrNull =
7734 [](const ArgList &Args) -> const char * {
7735 const char *Option = nullptr;
7736 constexpr const char *Enable = "-fms-anonymous-structs";
7737 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7738
7739 // Iterate through all arguments in order to implement "last flag wins".
7740 for (const Arg *A : Args) {
7741 switch (A->getOption().getID()) {
7742 case options::OPT_fms_anonymous_structs:
7743 A->claim();
7744 Option = Enable;
7745 break;
7746 case options::OPT_fno_ms_anonymous_structs:
7747 A->claim();
7748 Option = Disable;
7749 break;
7750 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7751 // feature.
7752 case options::OPT_fms_extensions:
7753 case options::OPT_fms_compatibility:
7754 Option = Enable;
7755 break;
7756 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7757 // disables the feature.
7758 case options::OPT_fno_ms_extensions:
7759 case options::OPT_fno_ms_compatibility:
7760 Option = Disable;
7761 break;
7762 default:
7763 break;
7764 }
7765 }
7766 return Option;
7767 };
7768
7769 // Only pass a flag to CC1 if a relevant option was seen
7770 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7771 CmdArgs.push_back(MSAnonOpt);
7772
7773 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7774 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7775 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7776
7777 // Handle -fgcc-version, if present.
7778 VersionTuple GNUCVer;
7779 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7780 // Check that the version has 1 to 3 components and the minor and patch
7781 // versions fit in two decimal digits.
7782 StringRef Val = A->getValue();
7783 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7784 bool Invalid = GNUCVer.tryParse(Val);
7785 unsigned Minor = GNUCVer.getMinor().value_or(0);
7786 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7787 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7788 D.Diag(diag::err_drv_invalid_value)
7789 << A->getAsString(Args) << A->getValue();
7790 }
7791 } else if (!IsMSVCCompat) {
7792 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7793 GNUCVer = VersionTuple(4, 2, 1);
7794 }
7795 if (!GNUCVer.empty()) {
7796 CmdArgs.push_back(
7797 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7798 }
7799
7800 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7801 if (!MSVT.empty())
7802 CmdArgs.push_back(
7803 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7804
7805 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7806 if (ImplyVCPPCVer) {
7807 StringRef LanguageStandard;
7808 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7809 Std = StdArg;
7810 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7811 .Case("c11", "-std=c11")
7812 .Case("c17", "-std=c17")
7813 // If you add cases below for spellings that are
7814 // not in LangStandards.def, update
7815 // TransferableCommand::tryParseStdArg() in
7816 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7817 // to match.
7818 // TODO: add c23 when MSVC supports it.
7819 .Case("clatest", "-std=c23")
7820 .Default("");
7821 if (LanguageStandard.empty())
7822 D.Diag(clang::diag::warn_drv_unused_argument)
7823 << StdArg->getAsString(Args);
7824 }
7825 CmdArgs.push_back(LanguageStandard.data());
7826 }
7827 if (ImplyVCPPCXXVer) {
7828 StringRef LanguageStandard;
7829 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7830 Std = StdArg;
7831 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7832 .Case("c++14", "-std=c++14")
7833 .Case("c++17", "-std=c++17")
7834 .Case("c++20", "-std=c++20")
7835 .Case("c++23", "-std=c++23")
7836 // If you add cases below for spellings that are
7837 // not in LangStandards.def, update
7838 // TransferableCommand::tryParseStdArg() in
7839 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7840 // to match.
7841 // TODO add c++26, c++29 when MSVC supports
7842 // it.
7843 .Case("c++23preview", "-std=c++23")
7844 .Case("c++26preview", "-std=c++26")
7845 .Case("c++latest", "-std=c++2d")
7846 .Default("");
7847 if (IsSYCL) {
7848 const LangStandard *LangStd =
7849 LangStandard::getLangStandardForName(StdArg->getValue());
7850 if (LangStd) {
7851 // Use of /std: with 'C' is not supported for SYCL.
7852 if (LangStd->getLanguage() == Language::C)
7853 D.Diag(diag::err_drv_argument_not_allowed_with)
7854 << StdArg->getAsString(Args) << "-fsycl";
7855 // SYCL requires C++17 or later.
7856 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7857 D.Diag(diag::err_drv_sycl_requires_cxx17)
7858 << StdArg->getAsString(Args);
7859 }
7860 }
7861 if (LanguageStandard.empty())
7862 D.Diag(clang::diag::warn_drv_unused_argument)
7863 << StdArg->getAsString(Args);
7864 }
7865
7866 if (LanguageStandard.empty()) {
7867 if (IsSYCL)
7868 // For SYCL, C++17 is the default.
7869 LanguageStandard = "-std=c++17";
7870 else if (IsMSVC2015Compatible)
7871 LanguageStandard = "-std=c++14";
7872 else
7873 LanguageStandard = "-std=c++11";
7874 }
7875
7876 CmdArgs.push_back(LanguageStandard.data());
7877 }
7878
7879 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7880 options::OPT_fno_borland_extensions);
7881
7882 // -fno-declspec is default, except for PS4/PS5.
7883 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7884 RawTriple.isPS()))
7885 CmdArgs.push_back("-fdeclspec");
7886 else if (Args.hasArg(options::OPT_fno_declspec))
7887 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7888
7889 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7890 // than 19.
7891 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7892 options::OPT_fno_threadsafe_statics,
7893 !types::isOpenCL(InputType) &&
7894 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7895 CmdArgs.push_back("-fno-threadsafe-statics");
7896
7897 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7898 true))
7899 CmdArgs.push_back("-fno-ms-tls-guards");
7900
7901 // Add -fno-assumptions, if it was specified.
7902 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7903 true))
7904 CmdArgs.push_back("-fno-assumptions");
7905
7906 // -fgnu-keywords default varies depending on language; only pass if
7907 // specified.
7908 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7909 options::OPT_fno_gnu_keywords);
7910
7911 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7912 options::OPT_fno_gnu89_inline);
7913
7914 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7915 options::OPT_finline_hint_functions,
7916 options::OPT_fno_inline_functions);
7917 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7918 if (A->getOption().matches(options::OPT_fno_inline))
7919 A->render(Args, CmdArgs);
7920 } else if (InlineArg) {
7921 InlineArg->render(Args, CmdArgs);
7922 }
7923
7924 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7925
7926 // FIXME: Find a better way to determine whether we are in C++20.
7927 bool HaveCxx20 =
7928 Std &&
7929 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7930 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7931 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7932 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7933 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7934 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7935 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7936 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7937 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7938 bool HaveModules =
7939 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7940
7941 // -fdelayed-template-parsing is default when targeting MSVC.
7942 // Many old Windows SDK versions require this to parse.
7943 //
7944 // According to
7945 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7946 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7947 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7948 // not enable -fdelayed-template-parsing by default after C++20.
7949 //
7950 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7951 // able to disable this by default at some point.
7952 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7953 options::OPT_fno_delayed_template_parsing,
7954 IsWindowsMSVC && !HaveCxx20)) {
7955 if (HaveCxx20)
7956 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7957
7958 CmdArgs.push_back("-fdelayed-template-parsing");
7959 }
7960
7961 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7962 options::OPT_fno_pch_validate_input_files_content, false))
7963 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7964 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7965 options::OPT_fno_pch_instantiate_templates, false))
7966 CmdArgs.push_back("-fpch-instantiate-templates");
7967 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7968 false))
7969 CmdArgs.push_back("-fmodules-codegen");
7970 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7971 false))
7972 CmdArgs.push_back("-fmodules-debuginfo");
7973
7974 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7975 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7976 Input, CmdArgs);
7977
7978 if (types::isObjC(Input.getType()) &&
7979 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7980 options::OPT_fno_objc_encode_cxx_class_template_spec,
7981 !Runtime.isNeXTFamily()))
7982 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7983
7984 if (Args.hasFlag(options::OPT_fapplication_extension,
7985 options::OPT_fno_application_extension, false))
7986 CmdArgs.push_back("-fapplication-extension");
7987
7988 // Handle GCC-style exception args.
7989 bool EH = false;
7990 if (!C.getDriver().IsCLMode())
7991 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7992 IsDeviceOffloadAction, Runtime, CmdArgs);
7993
7994 // Handle exception personalities
7995 Arg *A = Args.getLastArg(
7996 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7997 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions,
7998 options::OPT_femscripten_exceptions);
7999 if (A) {
8000 const Option &Opt = A->getOption();
8001 if (Opt.matches(options::OPT_fsjlj_exceptions))
8002 CmdArgs.push_back("-exception-model=sjlj");
8003 if (Opt.matches(options::OPT_fseh_exceptions))
8004 CmdArgs.push_back("-exception-model=seh");
8005 if (Opt.matches(options::OPT_fdwarf_exceptions))
8006 CmdArgs.push_back("-exception-model=dwarf");
8007 if (Opt.matches(options::OPT_fwasm_exceptions))
8008 CmdArgs.push_back("-exception-model=wasm");
8009 if (Opt.matches(options::OPT_femscripten_exceptions))
8010 CmdArgs.push_back("-exception-model=emscripten");
8011 } else {
8012 switch (TC.GetExceptionModel(Args)) {
8013 default:
8014 break;
8015 case llvm::ExceptionHandling::DwarfCFI:
8016 CmdArgs.push_back("-exception-model=dwarf");
8017 break;
8018 case llvm::ExceptionHandling::SjLj:
8019 CmdArgs.push_back("-exception-model=sjlj");
8020 break;
8021 case llvm::ExceptionHandling::WinEH:
8022 CmdArgs.push_back("-exception-model=seh");
8023 break;
8024 }
8025 }
8026
8027 // Unwind information version for x64 Windows.
8028 // Forward the new unified flag if present, otherwise translate legacy flags.
8029 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
8030 A->claim();
8031 CmdArgs.push_back(
8032 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
8033 } else if (const Arg *A =
8034 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
8035 A->claim();
8036 StringRef Val = A->getValue();
8037 if (Val == "best-effort")
8038 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
8039 else if (Val == "required")
8040 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
8041 // "disabled" maps to v1 default, nothing to forward.
8042 else if (Val != "disabled")
8043 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
8044 }
8045
8046 // Control Flow Guard mechanism for Windows.
8047 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
8048
8049 // C++ "sane" operator new.
8050 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
8051 options::OPT_fno_assume_sane_operator_new);
8052
8053 // -fassume-unique-vtables is on by default.
8054 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
8055 options::OPT_fno_assume_unique_vtables);
8056
8057 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
8058 // by default.
8059 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
8060 options::OPT_fno_sized_deallocation);
8061
8062 // -faligned-allocation is on by default in C++17 onwards and otherwise off
8063 // by default.
8064 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
8065 options::OPT_fno_aligned_allocation,
8066 options::OPT_faligned_new_EQ)) {
8067 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
8068 CmdArgs.push_back("-fno-aligned-allocation");
8069 else
8070 CmdArgs.push_back("-faligned-allocation");
8071 }
8072
8073 // The default new alignment can be specified using a dedicated option or via
8074 // a GCC-compatible option that also turns on aligned allocation.
8075 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
8076 options::OPT_faligned_new_EQ))
8077 CmdArgs.push_back(
8078 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
8079
8080 // -fconstant-cfstrings is default, and may be subject to argument translation
8081 // on Darwin.
8082 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
8083 options::OPT_fno_constant_cfstrings, true) ||
8084 !Args.hasFlag(options::OPT_mconstant_cfstrings,
8085 options::OPT_mno_constant_cfstrings, true))
8086 CmdArgs.push_back("-fno-constant-cfstrings");
8087
8088 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
8089 options::OPT_fno_pascal_strings);
8090
8091 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8092 // -fno-pack-struct doesn't apply to -fpack-struct=.
8093 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
8094 CmdArgs.push_back(
8095 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
8096 } else if (Args.hasFlag(options::OPT_fpack_struct,
8097 options::OPT_fno_pack_struct, false)) {
8098 CmdArgs.push_back("-fpack-struct=1");
8099 }
8100
8101 // Handle -fmax-type-align=N and -fno-type-align
8102 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
8103 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
8104 if (!SkipMaxTypeAlign) {
8105 std::string MaxTypeAlignStr = "-fmax-type-align=";
8106 MaxTypeAlignStr += A->getValue();
8107 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8108 }
8109 } else if (RawTriple.isOSDarwin()) {
8110 if (!SkipMaxTypeAlign) {
8111 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8112 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8113 }
8114 }
8115
8116 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
8117 CmdArgs.push_back("-Qn");
8118
8119 // -fno-common is the default, set -fcommon only when that flag is set.
8120 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
8121
8122 // -fsigned-bitfields is default, and clang doesn't yet support
8123 // -funsigned-bitfields.
8124 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
8125 options::OPT_funsigned_bitfields, true))
8126 D.Diag(diag::warn_drv_clang_unsupported)
8127 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
8128
8129 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8130 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
8131 D.Diag(diag::err_drv_clang_unsupported)
8132 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
8133
8134 // -finput_charset=UTF-8 is default. Reject others
8135 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
8136 StringRef value = inputCharset->getValue();
8137 if (!value.equals_insensitive("utf-8"))
8138 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8139 << value;
8140 }
8141
8142 // -fexec_charset=UTF-8 is default. Reject others
8143 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8144 StringRef value = execCharset->getValue();
8145 if (!value.equals_insensitive("utf-8"))
8146 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8147 << value;
8148 }
8149
8150 RenderDiagnosticsOptions(D, Args, CmdArgs);
8151
8152 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8153 options::OPT_fno_asm_blocks);
8154
8155 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8156 options::OPT_fno_gnu_inline_asm);
8157
8158 handleVectorizeLoopsArgs(Args, CmdArgs);
8159 handleVectorizeSLPArgs(Args, CmdArgs);
8160
8161 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8162 if (!VecWidth.empty())
8163 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8164
8165 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8166 Args.AddLastArg(CmdArgs,
8167 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8168
8169 // -fdollars-in-identifiers default varies depending on platform and
8170 // language; only pass if specified.
8171 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8172 options::OPT_fno_dollars_in_identifiers)) {
8173 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8174 CmdArgs.push_back("-fdollars-in-identifiers");
8175 else
8176 CmdArgs.push_back("-fno-dollars-in-identifiers");
8177 }
8178
8179 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8180 options::OPT_fno_apple_pragma_pack);
8181
8182 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8183 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8184 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8185
8186 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8187 options::OPT_fno_rewrite_imports, false);
8188 if (RewriteImports)
8189 CmdArgs.push_back("-frewrite-imports");
8190
8191 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8192 options::OPT_fno_directives_only);
8193
8194 // Enable rewrite includes if the user's asked for it or if we're generating
8195 // diagnostics.
8196 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8197 // nice to enable this when doing a crashdump for modules as well.
8198 if (Args.hasFlag(options::OPT_frewrite_includes,
8199 options::OPT_fno_rewrite_includes, false) ||
8200 (C.isForDiagnostics() && !HaveModules))
8201 CmdArgs.push_back("-frewrite-includes");
8202
8203 if (Args.hasFlag(options::OPT_fzos_extensions,
8204 options::OPT_fno_zos_extensions, false))
8205 CmdArgs.push_back("-fzos-extensions");
8206 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8207 CmdArgs.push_back("-fno-zos-extensions");
8208
8209 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8210 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8211 options::OPT_traditional_cpp)) {
8213 CmdArgs.push_back("-traditional-cpp");
8214 else
8215 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8216 }
8217
8218 Args.AddLastArg(CmdArgs, options::OPT_dM);
8219 Args.AddLastArg(CmdArgs, options::OPT_dD);
8220 Args.AddLastArg(CmdArgs, options::OPT_dI);
8221
8222 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8223
8224 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8225 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8226 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8227 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8228 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8229 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8230 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8231 Args.AddLastArg(CmdArgs, options::OPT__ssaf_link_unit_id);
8232 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8233 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8234
8235 // Handle serialized diagnostics.
8236 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8237 CmdArgs.push_back("-serialize-diagnostic-file");
8238 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8239 }
8240
8241 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8242 CmdArgs.push_back("-fretain-comments-from-system-headers");
8243
8244 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8245 A->render(Args, CmdArgs);
8246 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8247 A && A->containsValue("g")) {
8248 // Set -fextend-variable-liveness=all by default at -Og.
8249 CmdArgs.push_back("-fextend-variable-liveness=all");
8250 }
8251
8252 // Forward -fcomment-block-commands to -cc1.
8253 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8254 // Forward -fparse-all-comments to -cc1.
8255 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8256 // Forward -fretain-comments to -cc1.
8257 Args.AddAllArgs(CmdArgs, options::OPT_fretain_comments);
8258
8259 // Turn -fplugin=name.so into -load name.so
8260 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8261 CmdArgs.push_back("-load");
8262 CmdArgs.push_back(A->getValue());
8263 A->claim();
8264 }
8265
8266 // Turn -fplugin-arg-pluginname-key=value into
8267 // -plugin-arg-pluginname key=value
8268 // GCC has an actual plugin_argument struct with key/value pairs that it
8269 // passes to its plugins, but we don't, so just pass it on as-is.
8270 //
8271 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8272 // argument key are allowed to contain dashes. GCC therefore only
8273 // allows dashes in the key. We do the same.
8274 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8275 auto ArgValue = StringRef(A->getValue());
8276 auto FirstDashIndex = ArgValue.find('-');
8277 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8278 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8279
8280 A->claim();
8281 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8282 if (PluginName.empty()) {
8283 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8284 } else {
8285 D.Diag(diag::warn_drv_missing_plugin_arg)
8286 << PluginName << A->getAsString(Args);
8287 }
8288 continue;
8289 }
8290
8291 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8292 CmdArgs.push_back(Args.MakeArgString(Arg));
8293 }
8294
8295 // Forward -fpass-plugin=name.so to -cc1.
8296 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8297 CmdArgs.push_back(
8298 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8299 A->claim();
8300 }
8301
8302 // Forward --vfsoverlay to -cc1.
8303 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8304 CmdArgs.push_back("--vfsoverlay");
8305 CmdArgs.push_back(A->getValue());
8306 A->claim();
8307 }
8308
8309 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8310 options::OPT_fno_safe_buffer_usage_suggestions);
8311
8312 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8313 options::OPT_fno_experimental_late_parse_attributes);
8314
8315 if (Args.hasFlag(options::OPT_funique_source_file_names,
8316 options::OPT_fno_unique_source_file_names, false)) {
8317 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8318 A->render(Args, CmdArgs);
8319 else
8320 CmdArgs.push_back(Args.MakeArgString(
8321 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8322 }
8323
8324 if (Args.hasFlag(
8325 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8326 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8327 false) ||
8328 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8329 options::OPT_fno_experimental_pointer_field_protection_abi,
8330 false))
8331 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8332
8333 if (!IsCudaDevice) {
8334 Args.addOptInFlag(
8335 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8336 options::OPT_fno_experimental_pointer_field_protection_abi);
8337 Args.addOptInFlag(
8338 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8339 options::OPT_fno_experimental_pointer_field_protection_tagged);
8340 }
8341
8342 // Setup statistics file output.
8343 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8344 if (!StatsFile.empty()) {
8345 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8347 CmdArgs.push_back("-stats-file-append");
8348 }
8349
8350 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8351 // parser.
8352 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8353 Arg->claim();
8354 // -finclude-default-header flag is for preprocessor,
8355 // do not pass it to other cc1 commands when save-temps is enabled
8356 if (C.getDriver().isSaveTempsEnabled() &&
8358 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8359 continue;
8360 }
8361 CmdArgs.push_back(Arg->getValue());
8362 }
8363 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8364 A->claim();
8365
8366 // We translate this by hand to the -cc1 argument, since nightly test uses
8367 // it and developers have been trained to spell it with -mllvm. Both
8368 // spellings are now deprecated and should be removed.
8369 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8370 CmdArgs.push_back("-disable-llvm-optzns");
8371 } else {
8372 A->render(Args, CmdArgs);
8373 }
8374 }
8375
8376 // This needs to run after -Xclang argument forwarding to pick up the target
8377 // features enabled through -Xclang -target-feature flags.
8378 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8379
8380 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8381
8382#if CLANG_ENABLE_CIR
8383 // Forward -mmlir arguments to to the MLIR option parser.
8384 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8385 A->claim();
8386 A->render(Args, CmdArgs);
8387 }
8388#endif // CLANG_ENABLE_CIR
8389
8390 // With -save-temps, we want to save the unoptimized bitcode output from the
8391 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8392 // by the frontend.
8393 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8394 // has slightly different breakdown between stages.
8395 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8396 // pristine IR generated by the frontend. Ideally, a new compile action should
8397 // be added so both IR can be captured.
8398 if ((C.getDriver().isSaveTempsEnabled() ||
8400 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8402 CmdArgs.push_back("-disable-llvm-passes");
8403
8404 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8405
8406 const char *Exec = D.getDriverProgramPath();
8407
8408 // Optionally embed the -cc1 level arguments into the debug info or a
8409 // section, for build analysis.
8410 // Also record command line arguments into the debug info if
8411 // -grecord-gcc-switches options is set on.
8412 // By default, -gno-record-gcc-switches is set on and no recording.
8413 auto GRecordSwitches = false;
8414 auto FRecordSwitches = false;
8415 bool DXRecordSwitches = false;
8416 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8417 DXRecordSwitches)) {
8418 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8419 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8420 CmdArgs.push_back("-dwarf-debug-flags");
8421 CmdArgs.push_back(FlagsArgString);
8422 }
8423 if (FRecordSwitches) {
8424 CmdArgs.push_back("-record-command-line");
8425 CmdArgs.push_back(FlagsArgString);
8426 }
8427 if (DXRecordSwitches) {
8428 CmdArgs.push_back("-fdx-record-command-line");
8429 CmdArgs.push_back(FlagsArgString);
8430 }
8431 }
8432
8433 // Host-side offloading compilation receives all device-side outputs. Include
8434 // them in the host compilation depending on the target.
8435 if (!HostOffloadingInputs.empty()) {
8436 bool UseOffloadIncludeBinary =
8437 (IsCuda || IsHIP) &&
8438 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi)) &&
8439 !UsesLLVMOffloading;
8440 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8441 if (UseOffloadIncludeBinary) {
8442 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8443 CmdArgs.push_back("-foffload-include-binary");
8444 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8445 } else {
8446 for (const InputInfo Input : HostOffloadingInputs)
8447 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8448 TC.getInputFilename(Input)));
8449 }
8450 }
8451
8452 if (IsCuda) {
8453 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8454 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8455 }
8456
8457 if (IsCuda || IsHIP) {
8458 // Determine the original source input.
8459 const Action *SourceAction = &JA;
8460 while (SourceAction->getKind() != Action::InputClass) {
8461 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8462 SourceAction = SourceAction->getInputs()[0];
8463 }
8464 auto CUID = cast<InputAction>(SourceAction)->getId();
8465 if (!CUID.empty())
8466 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8467
8468 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8469 // be overriden by -fno-gpu-approx-transcendentals.
8470 bool UseApproxTranscendentals = Args.hasFlag(
8471 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8472 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8473 options::OPT_fno_gpu_approx_transcendentals,
8474 UseApproxTranscendentals))
8475 CmdArgs.push_back("-fgpu-approx-transcendentals");
8476 } else {
8477 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8478 options::OPT_fno_gpu_approx_transcendentals);
8479 }
8480
8481 if (IsHIP) {
8482 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8483 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8484 }
8485
8486 Args.AddAllArgs(CmdArgs,
8487 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8488
8489 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8490 options::OPT_fno_offload_uniform_block);
8491
8492 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8493 options::OPT_fno_offload_implicit_host_device_templates);
8494
8495 if (IsCudaDevice || IsHIPDevice) {
8496 StringRef InlineThresh =
8497 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8498 if (!InlineThresh.empty()) {
8499 std::string ArgStr =
8500 std::string("-inline-threshold=") + InlineThresh.str();
8501 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8502 }
8503 }
8504
8505 if (IsHIPDevice)
8506 Args.addOptOutFlag(CmdArgs,
8507 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8508 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8509
8510 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8511 // to specify the result of the compile phase on the host, so the meaningful
8512 // device declarations can be identified. Also, -fopenmp-is-target-device is
8513 // passed along to tell the frontend that it is generating code for a device,
8514 // so that only the relevant declarations are emitted.
8515 if (IsOpenMPDevice) {
8516 CmdArgs.push_back("-fopenmp-is-target-device");
8517 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8518 if (Args.hasArg(options::OPT_foffload_via_llvm))
8519 CmdArgs.push_back("-fcuda-is-device");
8520
8521 if (OpenMPDeviceInput) {
8522 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8523 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8524 }
8525 }
8526
8527 if (Triple.isAMDGPU() ||
8528 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8529 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8530
8531 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8532 options::OPT_mno_unsafe_fp_atomics);
8533 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8534 options::OPT_mno_amdgpu_ieee);
8535 }
8536
8537 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8538
8539 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8540 options::OPT_fno_devirtualize_speculatively,
8541 /*Default value*/ false))
8542 CmdArgs.push_back("-fdevirtualize-speculatively");
8543
8544 bool VirtualFunctionElimination =
8545 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8546 options::OPT_fno_virtual_function_elimination, false);
8547 if (VirtualFunctionElimination) {
8548 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8549 // in the future).
8550 if (LTOMode != LTOK_Full)
8551 D.Diag(diag::err_drv_argument_only_allowed_with)
8552 << "-fvirtual-function-elimination"
8553 << "-flto=full";
8554
8555 CmdArgs.push_back("-fvirtual-function-elimination");
8556 }
8557
8558 // VFE requires whole-program-vtables, and enables it by default.
8559 bool WholeProgramVTables = Args.hasFlag(
8560 options::OPT_fwhole_program_vtables,
8561 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8562 if (VirtualFunctionElimination && !WholeProgramVTables) {
8563 D.Diag(diag::err_drv_argument_not_allowed_with)
8564 << "-fno-whole-program-vtables"
8565 << "-fvirtual-function-elimination";
8566 }
8567
8568 if (WholeProgramVTables) {
8569 // PS4 uses the legacy LTO API, which does not support this feature in
8570 // ThinLTO mode.
8571 bool IsPS4 = getToolChain().getTriple().isPS4();
8572
8573 // Check if we passed LTO options but they were suppressed because this is a
8574 // device offloading action, or we passed device offload LTO options which
8575 // were suppressed because this is not the device offload action.
8576 // Check if we are using PS4 in regular LTO mode.
8577 // Otherwise, issue an error.
8578
8579 auto OtherLTOMode = TC.getLTOMode(
8580 Args, IsDeviceOffloadAction ? Action::OFK_None
8581 : static_cast<Action::OffloadKind>(
8582 C.getActiveOffloadKinds()));
8583 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8584
8585 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8586 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8587 D.Diag(diag::err_drv_argument_only_allowed_with)
8588 << "-fwhole-program-vtables"
8589 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8590
8591 // Propagate -fwhole-program-vtables if this is an LTO compile.
8592 if (IsUsingLTO)
8593 CmdArgs.push_back("-fwhole-program-vtables");
8594 }
8595
8596 bool DefaultsSplitLTOUnit =
8597 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8598 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8599 (!Triple.isPS4() && UnifiedLTO);
8600 bool SplitLTOUnit =
8601 Args.hasFlag(options::OPT_fsplit_lto_unit,
8602 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8603 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8604 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8605 << "-fsanitize=cfi";
8606 if (SplitLTOUnit)
8607 CmdArgs.push_back("-fsplit-lto-unit");
8608
8609 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8610 options::OPT_fno_fat_lto_objects)) {
8611 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8612 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8613 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8614 D.Diag(diag::err_drv_unsupported_opt_for_target)
8615 << A->getAsString(Args) << TC.getTripleString();
8616 }
8617 CmdArgs.push_back(Args.MakeArgString(
8618 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8619 CmdArgs.push_back("-flto-unit");
8620 CmdArgs.push_back("-ffat-lto-objects");
8621 A->render(Args, CmdArgs);
8622 }
8623 }
8624
8625 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8626
8627 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8628 options::OPT_fno_force_enable_int128)) {
8629 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8630 CmdArgs.push_back("-fforce-enable-int128");
8631 }
8632
8633 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8634 options::OPT_fno_keep_static_consts);
8635 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8636 options::OPT_fno_keep_persistent_storage_variables);
8637 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_inline_functions,
8638 options::OPT_fno_keep_inline_functions);
8639 Args.addOptOutFlag(CmdArgs, options::OPT_fmodule_local_hints,
8640 options::OPT_fno_module_local_hints);
8641 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8642 options::OPT_fno_complete_member_pointers);
8643 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8644 A->render(Args, CmdArgs);
8645
8646 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8647
8648 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8649
8650 if (Triple.isAArch64() &&
8651 (Args.hasArg(options::OPT_mno_fmv) ||
8652 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8653 // Disable Function Multiversioning on AArch64 target.
8654 CmdArgs.push_back("-target-feature");
8655 CmdArgs.push_back("-fmv");
8656 }
8657
8658 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8659 (TC.getTriple().isOSBinFormatELF() ||
8660 TC.getTriple().isOSBinFormatCOFF()) &&
8661 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8662 !TC.getTriple().isOSNetBSD() &&
8663 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8664 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8665 CmdArgs.push_back("-faddrsig");
8666
8667 const bool HasDefaultDwarf2CFIASM =
8668 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8669 (EH || UnwindTables || AsyncUnwindTables ||
8670 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8671 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8672 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8673 CmdArgs.push_back("-fdwarf2-cfi-asm");
8674
8675 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8676 std::string Str = A->getAsString(Args);
8677 if (!TC.getTriple().isOSBinFormatELF())
8678 D.Diag(diag::err_drv_unsupported_opt_for_target)
8679 << Str << TC.getTripleString();
8680 CmdArgs.push_back(Args.MakeArgString(Str));
8681 }
8682
8683 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8684 // the -cc1 command easier to edit when reproducing compiler crashes.
8685 if (Output.getType() == types::TY_Dependencies) {
8686 // Handled with other dependency code.
8687 } else if (Output.isFilename()) {
8688 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8689 Output.getType() == clang::driver::types::TY_IFS) {
8690 SmallString<128> OutputFilename(Output.getFilename());
8691 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8692 CmdArgs.push_back("-o");
8693 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8694 } else {
8695 CmdArgs.push_back("-o");
8696 CmdArgs.push_back(Output.getFilename());
8697 }
8698 } else {
8699 assert(Output.isNothing() && "Invalid output.");
8700 }
8701
8702 addDashXForInput(Args, Input, CmdArgs);
8703
8704 ArrayRef<InputInfo> FrontendInputs = Input;
8705 if (IsExtractAPI)
8706 FrontendInputs = ExtractAPIInputs;
8707 else if (Input.isNothing())
8708 FrontendInputs = {};
8709
8710 for (const InputInfo &Input : FrontendInputs) {
8711 if (Input.isFilename())
8712 CmdArgs.push_back(Input.getFilename());
8713 else
8714 Input.getInputArg().renderAsInput(Args, CmdArgs);
8715 }
8716
8717 if (D.CC1Main && !D.CCGenDiagnostics) {
8718 // Invoke the CC1 directly in this process
8719 C.addCommand(std::make_unique<CC1Command>(
8720 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8721 Output, D.getPrependArg()));
8722 } else {
8723 C.addCommand(std::make_unique<Command>(
8724 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8725 Output, D.getPrependArg()));
8726 }
8727
8728 // Make the compile command echo its inputs for /showFilenames.
8729 if (Output.getType() == types::TY_Object &&
8730 Args.hasFlag(options::OPT__SLASH_showFilenames,
8731 options::OPT__SLASH_showFilenames_, false)) {
8732 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8733 }
8734
8735 if (Arg *A = Args.getLastArg(options::OPT_pg))
8736 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8737 !Args.hasArg(options::OPT_mfentry))
8738 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8739 << A->getAsString(Args);
8740
8741 // Claim some arguments which clang supports automatically.
8742
8743 // -fpch-preprocess is used with gcc to add a special marker in the output to
8744 // include the PCH file.
8745 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8746
8747 // Claim some arguments which clang doesn't support, but we don't
8748 // care to warn the user about.
8749 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8750 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8751
8752 // Disable warnings for clang -E -emit-llvm foo.c
8753 Args.ClaimAllArgs(options::OPT_emit_llvm);
8754}
8755
8756Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8757 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8758 // as it is for other tools. Some operations on a Tool actually test
8759 // whether that tool is Clang based on the Tool's Name as a string.
8760 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8761
8763
8764/// Add options related to the Objective-C runtime/ABI.
8765///
8766/// Returns true if the runtime is non-fragile.
8767ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8768 const InputInfoList &inputs,
8769 ArgStringList &cmdArgs,
8770 RewriteKind rewriteKind) const {
8771 // Look for the controlling runtime option.
8772 Arg *runtimeArg =
8773 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8774 options::OPT_fobjc_runtime_EQ);
8775
8776 // Just forward -fobjc-runtime= to the frontend. This supercedes
8777 // options about fragility.
8778 if (runtimeArg &&
8779 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8780 ObjCRuntime runtime;
8781 StringRef value = runtimeArg->getValue();
8782 if (runtime.tryParse(value)) {
8783 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8784 << value;
8785 }
8786 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8787 (runtime.getVersion() >= VersionTuple(2, 0)))
8788 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8789 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8790 !getToolChain().getTriple().isOSBinFormatWasm()) {
8792 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8793 << runtime.getVersion().getMajor();
8794 }
8795
8796 runtimeArg->render(args, cmdArgs);
8797 return runtime;
8798 }
8799
8800 // Otherwise, we'll need the ABI "version". Version numbers are
8801 // slightly confusing for historical reasons:
8802 // 1 - Traditional "fragile" ABI
8803 // 2 - Non-fragile ABI, version 1
8804 // 3 - Non-fragile ABI, version 2
8805 unsigned objcABIVersion = 1;
8806 // If -fobjc-abi-version= is present, use that to set the version.
8807 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8808 StringRef value = abiArg->getValue();
8809 if (value == "1")
8810 objcABIVersion = 1;
8811 else if (value == "2")
8812 objcABIVersion = 2;
8813 else if (value == "3")
8814 objcABIVersion = 3;
8815 else
8816 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8817 } else {
8818 // Otherwise, determine if we are using the non-fragile ABI.
8819 bool nonFragileABIIsDefault =
8820 (rewriteKind == RK_NonFragile ||
8821 (rewriteKind == RK_None &&
8823 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8824 options::OPT_fno_objc_nonfragile_abi,
8825 nonFragileABIIsDefault)) {
8826// Determine the non-fragile ABI version to use.
8827#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8828 unsigned nonFragileABIVersion = 1;
8829#else
8830 unsigned nonFragileABIVersion = 2;
8831#endif
8832
8833 if (Arg *abiArg =
8834 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8835 StringRef value = abiArg->getValue();
8836 if (value == "1")
8837 nonFragileABIVersion = 1;
8838 else if (value == "2")
8839 nonFragileABIVersion = 2;
8840 else
8841 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8842 << value;
8843 }
8844
8845 objcABIVersion = 1 + nonFragileABIVersion;
8846 } else {
8847 objcABIVersion = 1;
8848 }
8849 }
8850
8851 // We don't actually care about the ABI version other than whether
8852 // it's non-fragile.
8853 bool isNonFragile = objcABIVersion != 1;
8854
8855 // If we have no runtime argument, ask the toolchain for its default runtime.
8856 // However, the rewriter only really supports the Mac runtime, so assume that.
8857 ObjCRuntime runtime;
8858 if (!runtimeArg) {
8859 switch (rewriteKind) {
8860 case RK_None:
8861 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8862 break;
8863 case RK_Fragile:
8864 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8865 break;
8866 case RK_NonFragile:
8867 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8868 break;
8869 }
8870
8871 // -fnext-runtime
8872 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8873 // On Darwin, make this use the default behavior for the toolchain.
8874 if (getToolChain().getTriple().isOSDarwin()) {
8875 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8876
8877 // Otherwise, build for a generic macosx port.
8878 } else {
8879 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8880 }
8881
8882 // -fgnu-runtime
8883 } else {
8884 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8885 // Legacy behaviour is to target the gnustep runtime if we are in
8886 // non-fragile mode or the GCC runtime in fragile mode.
8887 if (isNonFragile)
8888 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8889 else
8890 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8891 }
8892
8893 if (llvm::any_of(inputs, [](const InputInfo &input) {
8894 return types::isObjC(input.getType());
8895 }))
8896 cmdArgs.push_back(
8897 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8898 return runtime;
8899}
8900
8901static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8902 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8903 I += HaveDash;
8904 return !HaveDash;
8905}
8906
8907namespace {
8908struct EHFlags {
8909 bool Synch = false;
8910 bool Asynch = false;
8911 bool NoUnwindC = false;
8912};
8913} // end anonymous namespace
8914
8915/// /EH controls whether to run destructor cleanups when exceptions are
8916/// thrown. There are three modifiers:
8917/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8918/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8919/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8920/// - c: Assume that extern "C" functions are implicitly nounwind.
8921/// The default is /EHs-c-, meaning cleanups are disabled.
8922static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8923 bool isWindowsMSVC) {
8924 EHFlags EH;
8925
8926 std::vector<std::string> EHArgs =
8927 Args.getAllArgValues(options::OPT__SLASH_EH);
8928 for (const auto &EHVal : EHArgs) {
8929 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8930 switch (EHVal[I]) {
8931 case 'a':
8932 EH.Asynch = maybeConsumeDash(EHVal, I);
8933 if (EH.Asynch) {
8934 // Async exceptions are Windows MSVC only.
8935 if (!isWindowsMSVC) {
8936 EH.Asynch = false;
8937 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8938 continue;
8939 }
8940 EH.Synch = false;
8941 }
8942 continue;
8943 case 'c':
8944 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8945 continue;
8946 case 's':
8947 EH.Synch = maybeConsumeDash(EHVal, I);
8948 if (EH.Synch)
8949 EH.Asynch = false;
8950 continue;
8951 default:
8952 break;
8953 }
8954 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8955 break;
8956 }
8957 }
8958 // The /GX, /GX- flags are only processed if there are not /EH flags.
8959 // The default is that /GX is not specified.
8960 if (EHArgs.empty() &&
8961 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8962 /*Default=*/false)) {
8963 EH.Synch = true;
8964 EH.NoUnwindC = true;
8965 }
8966
8967 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8968 EH.Synch = false;
8969 EH.NoUnwindC = false;
8970 EH.Asynch = false;
8971 }
8972
8973 return EH;
8974}
8975
8976void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8977 ArgStringList &CmdArgs) const {
8978 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8979
8980 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8981
8982 if (Arg *ShowIncludes =
8983 Args.getLastArg(options::OPT__SLASH_showIncludes,
8984 options::OPT__SLASH_showIncludes_user)) {
8985 CmdArgs.push_back("--show-includes");
8986 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8987 CmdArgs.push_back("-sys-header-deps");
8988 }
8989
8990 // This controls whether or not we emit RTTI data for polymorphic types.
8991 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8992 /*Default=*/false))
8993 CmdArgs.push_back("-fno-rtti-data");
8994
8995 // This controls whether or not we emit stack-protector instrumentation.
8996 // In MSVC, Buffer Security Check (/GS) is on by default.
8997 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8998 /*Default=*/true)) {
8999 CmdArgs.push_back("-stack-protector");
9000 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
9001 }
9002
9003 const Driver &D = getToolChain().getDriver();
9004
9005 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
9006 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
9007 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
9008 if (types::isCXX(InputType))
9009 CmdArgs.push_back("-fcxx-exceptions");
9010 CmdArgs.push_back("-fexceptions");
9011 if (EH.Asynch)
9012 CmdArgs.push_back("-fasync-exceptions");
9013 }
9014 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
9015 CmdArgs.push_back("-fexternc-nounwind");
9016
9017 // /EP should expand to -E -P.
9018 if (Args.hasArg(options::OPT__SLASH_EP)) {
9019 CmdArgs.push_back("-E");
9020 CmdArgs.push_back("-P");
9021 }
9022
9023 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
9024 options::OPT__SLASH_Zc_dllexportInlines,
9025 false)) {
9026 CmdArgs.push_back("-fno-dllexport-inlines");
9027 }
9028
9029 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
9030 options::OPT__SLASH_Zc_wchar_t, false)) {
9031 CmdArgs.push_back("-fno-wchar");
9032 }
9033
9034 if (Args.hasArg(options::OPT__SLASH_kernel)) {
9035 llvm::Triple::ArchType Arch = getToolChain().getArch();
9036 std::vector<std::string> Values =
9037 Args.getAllArgValues(options::OPT__SLASH_arch);
9038 if (!Values.empty()) {
9039 llvm::SmallSet<std::string, 4> SupportedArches;
9040 if (Arch == llvm::Triple::x86)
9041 SupportedArches.insert("IA32");
9042
9043 for (auto &V : Values)
9044 if (!SupportedArches.contains(V))
9045 D.Diag(diag::err_drv_argument_not_allowed_with)
9046 << std::string("/arch:").append(V) << "/kernel";
9047 }
9048
9049 CmdArgs.push_back("-fno-rtti");
9050 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
9051 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
9052 << "/kernel";
9053 }
9054
9055 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
9056 options::OPT__SLASH_vlen_EQ_256,
9057 options::OPT__SLASH_vlen_EQ_512)) {
9058 llvm::Triple::ArchType AT = getToolChain().getArch();
9059 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
9060 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
9061 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
9062 "AVX10.2"};
9063
9064 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
9065 if (Arch512.contains(Arch))
9066 CmdArgs.push_back("-mprefer-vector-width=512");
9067 else
9068 D.Diag(diag::warn_drv_argument_not_allowed_with)
9069 << "/vlen=512" << std::string("/arch:").append(Arch);
9070 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
9071 if (Arch512.contains(Arch))
9072 CmdArgs.push_back("-mprefer-vector-width=256");
9073 else if (Arch != "AVX" && Arch != "AVX2")
9074 D.Diag(diag::warn_drv_argument_not_allowed_with)
9075 << "/vlen=256" << std::string("/arch:").append(Arch);
9076 } else {
9077 if (Arch == "AVX10.1" || Arch == "AVX10.2")
9078 CmdArgs.push_back("-mprefer-vector-width=256");
9079 }
9080 } else {
9081 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
9082 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
9083 CmdArgs.push_back("-mprefer-vector-width=256");
9084 CmdArgs.push_back("-target-feature");
9085 CmdArgs.push_back("-amx-tile");
9086 }
9087 if (Arch == "AVX10.2") {
9088 CmdArgs.push_back("-target-feature");
9089 CmdArgs.push_back("+avx10.2");
9090 }
9091 }
9092
9093 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
9094 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
9095 if (MostGeneralArg && BestCaseArg)
9096 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9097 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9098
9099 if (MostGeneralArg) {
9100 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
9101 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
9102 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
9103
9104 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9105 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9106 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9107 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9108 << FirstConflict->getAsString(Args)
9109 << SecondConflict->getAsString(Args);
9110
9111 if (SingleArg)
9112 CmdArgs.push_back("-fms-memptr-rep=single");
9113 else if (MultipleArg)
9114 CmdArgs.push_back("-fms-memptr-rep=multiple");
9115 else
9116 CmdArgs.push_back("-fms-memptr-rep=virtual");
9117 }
9118
9119 if (Args.hasArg(options::OPT_regcall4))
9120 CmdArgs.push_back("-regcall4");
9121
9122 // Parse the default calling convention options.
9123 if (Arg *CCArg =
9124 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
9125 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
9126 options::OPT__SLASH_Gregcall)) {
9127 unsigned DCCOptId = CCArg->getOption().getID();
9128 const char *DCCFlag = nullptr;
9129 bool ArchSupported = !isNVPTX;
9130 llvm::Triple::ArchType Arch = getToolChain().getArch();
9131 switch (DCCOptId) {
9132 case options::OPT__SLASH_Gd:
9133 DCCFlag = "-fdefault-calling-conv=cdecl";
9134 break;
9135 case options::OPT__SLASH_Gr:
9136 ArchSupported = Arch == llvm::Triple::x86;
9137 DCCFlag = "-fdefault-calling-conv=fastcall";
9138 break;
9139 case options::OPT__SLASH_Gz:
9140 ArchSupported = Arch == llvm::Triple::x86;
9141 DCCFlag = "-fdefault-calling-conv=stdcall";
9142 break;
9143 case options::OPT__SLASH_Gv:
9144 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9145 DCCFlag = "-fdefault-calling-conv=vectorcall";
9146 break;
9147 case options::OPT__SLASH_Gregcall:
9148 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9149 DCCFlag = "-fdefault-calling-conv=regcall";
9150 break;
9151 }
9152
9153 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9154 if (ArchSupported && DCCFlag)
9155 CmdArgs.push_back(DCCFlag);
9156 }
9157
9158 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9159 CmdArgs.push_back("-regcall4");
9160
9161 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9162
9163 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9164 CmdArgs.push_back("-fdiagnostics-format");
9165 CmdArgs.push_back("msvc");
9166 }
9167
9168 if (Args.hasArg(options::OPT__SLASH_kernel))
9169 CmdArgs.push_back("-fms-kernel");
9170
9171 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9172 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9173 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9174 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9175 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9176 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9177
9178 // Handle the various /guard options. We don't immediately push back clang
9179 // args since there are /d2 args that can modify the behavior of /guard:cf.
9180 bool HasCFGuard = false;
9181 bool HasCFGuardNoChecks = false;
9182 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9183 StringRef GuardArgs = A->getValue();
9184 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9185 // "ehcont-".
9186 if (GuardArgs.equals_insensitive("cf")) {
9187 // Emit CFG instrumentation and the table of address-taken functions.
9188 HasCFGuard = true;
9189 HasCFGuardNoChecks = false;
9190 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9191 // Emit only the table of address-taken functions.
9192 HasCFGuard = false;
9193 HasCFGuardNoChecks = true;
9194 } else if (GuardArgs.equals_insensitive("ehcont")) {
9195 // Emit EH continuation table.
9196 CmdArgs.push_back("-ehcontguard");
9197 } else if (GuardArgs.equals_insensitive("cf-") ||
9198 GuardArgs.equals_insensitive("ehcont-")) {
9199 // Do nothing, but we might want to emit a security warning in future.
9200 } else {
9201 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9202 }
9203 A->claim();
9204 }
9205
9206 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9207 // If CFG is not enabled, it is a no-op.
9208 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9209 if (HasCFGuard) {
9210 HasCFGuard = false;
9211 HasCFGuardNoChecks = true;
9212 }
9213 }
9214
9215 if (HasCFGuard)
9216 CmdArgs.push_back("-cfguard");
9217 else if (HasCFGuardNoChecks)
9218 CmdArgs.push_back("-cfguard-no-checks");
9219
9220 // Control Flow Guard mechanism for Windows.
9221 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9222 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9223 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9224 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9225
9226 for (const auto &FuncOverride :
9227 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9228 CmdArgs.push_back(Args.MakeArgString(
9229 Twine("-loader-replaceable-function=") + FuncOverride));
9230 }
9231
9232 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9233 CmdArgs.push_back("-Wdate-time");
9234
9235 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9236 D.Diag(diag::err_drv_argument_not_allowed_with)
9237 << "/experimental:deterministic"
9238 << "/Brepro-";
9239 }
9240 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9241 // deterministic result, but we force this timestamp to 0, which also
9242 // produces deterministic result.
9243 CmdArgs.push_back("-mno-incremental-linker-compatible");
9244 }
9245
9246 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9247 options::OPT__SLASH_d1nodatetime_, false);
9248
9249 if (HasNoDateTime)
9250 CmdArgs.push_back("-init-datetime-macros=undefined");
9251
9252 // /Brepro is an alias for -mincremental-linker-compatible option.
9253 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9254 options::OPT_mno_incremental_linker_compatible,
9255 getToolChain()
9256 .getTriple()
9257 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9258 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9259 // This option does not allow the user redefinitions for these macros.
9260 if (!HasNoDateTime)
9261 CmdArgs.push_back("-init-datetime-macros=literalone");
9262 // Omit tool, current workdir and command line in COFF CV debug section.
9263 CmdArgs.push_back("-gno-codeview-command-line");
9264 CmdArgs.push_back("-gno-codeview-cwd");
9265 }
9266}
9267
9268const char *Clang::getBaseInputName(const ArgList &Args,
9269 const InputInfo &Input) {
9270 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9271}
9272
9273const char *Clang::getBaseInputStem(const ArgList &Args,
9274 const InputInfoList &Inputs) {
9275 const char *Str = getBaseInputName(Args, Inputs[0]);
9276
9277 if (const char *End = strrchr(Str, '.'))
9278 return Args.MakeArgString(std::string(Str, End));
9279
9280 return Str;
9281}
9282
9283const char *Clang::getDependencyFileName(const ArgList &Args,
9284 const InputInfoList &Inputs) {
9285 // FIXME: Think about this more.
9286
9287 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9288 SmallString<128> OutputFilename(OutputOpt->getValue());
9289 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9290 return Args.MakeArgString(OutputFilename);
9291 }
9292
9293 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9294}
9295
9296// Begin ClangAs
9297
9298void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9299 ArgStringList &CmdArgs) const {
9300 StringRef CPUName;
9301 StringRef ABIName;
9302 const llvm::Triple &Triple = getToolChain().getTriple();
9303 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9304
9305 CmdArgs.push_back("-target-abi");
9306 CmdArgs.push_back(ABIName.data());
9307}
9308
9309void ClangAs::AddX86TargetArgs(const ArgList &Args,
9310 ArgStringList &CmdArgs) const {
9311 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9312 /*IsLTO=*/false);
9313
9314 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9315 StringRef Value = A->getValue();
9316 if (Value == "intel" || Value == "att") {
9317 CmdArgs.push_back("-mllvm");
9318 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9319 } else {
9320 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9321 << A->getSpelling() << Value;
9322 }
9323 }
9324}
9325
9326void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9327 ArgStringList &CmdArgs) const {
9328 CmdArgs.push_back("-target-abi");
9329 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9331 .data());
9332}
9333
9334void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9335 ArgStringList &CmdArgs) const {
9336 const llvm::Triple &Triple = getToolChain().getTriple();
9337 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9338
9339 CmdArgs.push_back("-target-abi");
9340 CmdArgs.push_back(ABIName.data());
9341
9342 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9343 options::OPT_mno_default_build_attributes, true)) {
9344 CmdArgs.push_back("-mllvm");
9345 CmdArgs.push_back("-riscv-add-build-attributes");
9346 }
9347}
9348
9350 const InputInfo &Output, const InputInfoList &Inputs,
9351 const ArgList &Args,
9352 const char *LinkingOutput) const {
9353 ArgStringList CmdArgs;
9354
9355 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9356 const InputInfo &Input = Inputs[0];
9357
9358 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9359 const std::string &TripleStr = Triple.getTriple();
9360 const auto &D = getToolChain().getDriver();
9361
9362 // Don't warn about "clang -w -c foo.s"
9363 Args.ClaimAllArgs(options::OPT_w);
9364 // and "clang -emit-llvm -c foo.s"
9365 Args.ClaimAllArgs(options::OPT_emit_llvm);
9366
9367 claimNoWarnArgs(Args);
9368
9369 // Invoke ourselves in -cc1as mode.
9370 //
9371 // FIXME: Implement custom jobs for internal actions.
9372 CmdArgs.push_back("-cc1as");
9373
9374 // Add the "effective" target triple.
9375 CmdArgs.push_back("-triple");
9376 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9377
9379
9380 // Set the output mode, we currently only expect to be used as a real
9381 // assembler.
9382 CmdArgs.push_back("-filetype");
9383 CmdArgs.push_back("obj");
9384
9385 // Set the main file name, so that debug info works even with
9386 // -save-temps or preprocessed assembly.
9387 CmdArgs.push_back("-main-file-name");
9388 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9389
9390 // Add the target cpu
9391 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9392 if (!CPU.empty()) {
9393 CmdArgs.push_back("-target-cpu");
9394 CmdArgs.push_back(Args.MakeArgString(CPU));
9395 }
9396
9397 // Add the target features
9398 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9399
9400 // Ignore explicit -force_cpusubtype_ALL option.
9401 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9402
9403 // Pass along any -I options so we get proper .include search paths.
9404 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9405
9406 // Pass along any --embed-dir or similar options so we get proper embed paths.
9407 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9408
9409 // Determine the original source input.
9410 auto FindSource = [](const Action *S) -> const Action * {
9411 while (S->getKind() != Action::InputClass) {
9412 assert(!S->getInputs().empty() && "unexpected root action!");
9413 S = S->getInputs()[0];
9414 }
9415 return S;
9416 };
9417 const Action *SourceAction = FindSource(&JA);
9418
9419 // Forward -g and handle debug info related flags, assuming we are dealing
9420 // with an actual assembly file.
9421 bool WantDebug = false;
9422 Args.ClaimAllArgs(options::OPT_g_Group);
9423 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9424 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9425 !A->getOption().matches(options::OPT_ggdb0);
9426
9427 // If a -gdwarf argument appeared, remember it.
9428 bool EmitDwarf = false;
9429 if (const Arg *A = getDwarfNArg(Args))
9430 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9431
9432 bool EmitCodeView = false;
9433 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9434 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9435
9436 // If the user asked for debug info but did not explicitly specify -gcodeview
9437 // or -gdwarf, ask the toolchain for the default format.
9438 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9439 switch (getToolChain().getDefaultDebugFormat()) {
9440 case llvm::codegenoptions::DIF_CodeView:
9441 EmitCodeView = true;
9442 break;
9443 case llvm::codegenoptions::DIF_DWARF:
9444 EmitDwarf = true;
9445 break;
9446 }
9447 }
9448
9449 // If the arguments don't imply DWARF, don't emit any debug info here.
9450 if (!EmitDwarf)
9451 WantDebug = false;
9452
9453 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9454 llvm::codegenoptions::NoDebugInfo;
9455
9456 // Add the -fdebug-compilation-dir flag if needed.
9457 const char *DebugCompilationDir =
9458 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9459
9460 if (SourceAction->getType() == types::TY_Asm ||
9461 SourceAction->getType() == types::TY_PP_Asm) {
9462 // You might think that it would be ok to set DebugInfoKind outside of
9463 // the guard for source type, however there is a test which asserts
9464 // that some assembler invocation receives no -debug-info-kind,
9465 // and it's not clear whether that test is just overly restrictive.
9466 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9467 : llvm::codegenoptions::NoDebugInfo);
9468
9469 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9470 CmdArgs);
9471
9472 // Set the AT_producer to the clang version when using the integrated
9473 // assembler on assembly source files.
9474 CmdArgs.push_back("-dwarf-debug-producer");
9475 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9476
9477 // And pass along -I options
9478 Args.AddAllArgs(CmdArgs, options::OPT_I);
9479 }
9480 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9481 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9482 llvm::DebuggerKind::Default);
9483 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9484 if (useMachORelocatableDwarf(Triple, DwarfVersion))
9485 CmdArgs.push_back("-grelocatable-dwarf");
9486 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9487
9488 // Handle -fPIC et al -- the relocation-model affects the assembler
9489 // for some targets.
9490 llvm::Reloc::Model RelocationModel;
9491 unsigned PICLevel;
9492 bool IsPIE;
9493 std::tie(RelocationModel, PICLevel, IsPIE) =
9494 ParsePICArgs(getToolChain(), Args);
9495
9496 const char *RMName = RelocationModelName(RelocationModel);
9497 if (RMName) {
9498 CmdArgs.push_back("-mrelocation-model");
9499 CmdArgs.push_back(RMName);
9500 }
9501
9502 // Optionally embed the -cc1as level arguments into the debug info, for build
9503 // analysis.
9504 if (getToolChain().UseDwarfDebugFlags()) {
9505 ArgStringList OriginalArgs;
9506 for (const auto &Arg : Args)
9507 Arg->render(Args, OriginalArgs);
9508
9509 SmallString<256> Flags;
9510 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9511 escapeSpacesAndBackslashes(Exec, Flags);
9512 for (const char *OriginalArg : OriginalArgs) {
9513 SmallString<128> EscapedArg;
9514 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9515 Flags += " ";
9516 Flags += EscapedArg;
9517 }
9518 CmdArgs.push_back("-dwarf-debug-flags");
9519 CmdArgs.push_back(Args.MakeArgString(Flags));
9520 }
9521
9522 // FIXME: Add -static support, once we have it.
9523
9524 // Add target specific flags.
9525 switch (getToolChain().getArch()) {
9526 default:
9527 break;
9528
9529 case llvm::Triple::mips:
9530 case llvm::Triple::mipsel:
9531 case llvm::Triple::mips64:
9532 case llvm::Triple::mips64el:
9533 AddMIPSTargetArgs(Args, CmdArgs);
9534 break;
9535
9536 case llvm::Triple::x86:
9537 case llvm::Triple::x86_64:
9538 AddX86TargetArgs(Args, CmdArgs);
9539 break;
9540
9541 case llvm::Triple::arm:
9542 case llvm::Triple::armeb:
9543 case llvm::Triple::thumb:
9544 case llvm::Triple::thumbeb:
9545 // This isn't in AddARMTargetArgs because we want to do this for assembly
9546 // only, not C/C++.
9547 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9548 options::OPT_mno_default_build_attributes, true)) {
9549 CmdArgs.push_back("-mllvm");
9550 CmdArgs.push_back("-arm-add-build-attributes");
9551 }
9552 break;
9553
9554 case llvm::Triple::aarch64:
9555 case llvm::Triple::aarch64_32:
9556 case llvm::Triple::aarch64_be:
9557 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9558 CmdArgs.push_back("-mllvm");
9559 CmdArgs.push_back("-aarch64-mark-bti-property");
9560 }
9561 break;
9562
9563 case llvm::Triple::loongarch32:
9564 case llvm::Triple::loongarch64:
9565 AddLoongArchTargetArgs(Args, CmdArgs);
9566 break;
9567
9568 case llvm::Triple::riscv32:
9569 case llvm::Triple::riscv64:
9570 case llvm::Triple::riscv32be:
9571 case llvm::Triple::riscv64be:
9572 AddRISCVTargetArgs(Args, CmdArgs);
9573 break;
9574
9575 case llvm::Triple::hexagon:
9576 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9577 options::OPT_mno_default_build_attributes, true)) {
9578 CmdArgs.push_back("-mllvm");
9579 CmdArgs.push_back("-hexagon-add-build-attributes");
9580 }
9581 break;
9582 }
9583
9584 // Consume all the warning flags. Usually this would be handled more
9585 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9586 // doesn't handle that so rather than warning about unused flags that are
9587 // actually used, we'll lie by omission instead.
9588 // FIXME: Stop lying and consume only the appropriate driver flags
9589 Args.ClaimAllArgs(options::OPT_W_Group);
9590
9591 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9592 getToolChain().getDriver());
9593
9594 // Forward -Xclangas arguments to -cc1as
9595 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9596 Arg->claim();
9597 CmdArgs.push_back(Arg->getValue());
9598 }
9599
9600 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9601
9602 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9603 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9604 Output.getFilename());
9605
9606 // Fixup any previous commands that use -object-file-name because when we
9607 // generated them, the final .obj name wasn't yet known.
9608 for (Command &J : C.getJobs()) {
9609 if (SourceAction != FindSource(&J.getSource()))
9610 continue;
9611 auto &JArgs = J.getArguments();
9612 for (unsigned I = 0; I < JArgs.size(); ++I) {
9613 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9614 Output.isFilename()) {
9615 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9616 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9617 Output.getFilename());
9618 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9619 J.replaceArguments(NewArgs);
9620 break;
9621 }
9622 }
9623 }
9624
9625 assert(Output.isFilename() && "Unexpected lipo output.");
9626 CmdArgs.push_back("-o");
9627 CmdArgs.push_back(Output.getFilename());
9628
9629 const llvm::Triple &T = getToolChain().getTriple();
9630 Arg *A;
9631 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9632 T.isOSBinFormatELF()) {
9633 CmdArgs.push_back("-split-dwarf-output");
9634 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9635 }
9636
9637 if (Triple.isAMDGPU())
9638 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9639
9640 assert(Input.isFilename() && "Invalid input.");
9641 CmdArgs.push_back(Input.getFilename());
9642
9643 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9644 if (D.CC1Main && !D.CCGenDiagnostics) {
9645 // Invoke cc1as directly in this process.
9646 C.addCommand(std::make_unique<CC1Command>(
9647 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9648 Output, D.getPrependArg()));
9649 } else {
9650 C.addCommand(std::make_unique<Command>(
9651 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9652 Output, D.getPrependArg()));
9653 }
9654}
9655
9656// Begin OffloadBundler
9658 const InputInfo &Output,
9659 const InputInfoList &Inputs,
9660 const llvm::opt::ArgList &TCArgs,
9661 const char *LinkingOutput) const {
9662 // The version with only one output is expected to refer to a bundling job.
9663 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9664
9665 // The bundling command looks like this:
9666 // clang-offload-bundler -type=bc
9667 // -targets=host-triple,openmp-triple1,openmp-triple2
9668 // -output=output_file
9669 // -input=unbundle_file_host
9670 // -input=unbundle_file_tgt1
9671 // -input=unbundle_file_tgt2
9672
9673 ArgStringList CmdArgs;
9674
9675 // Get the type.
9676 CmdArgs.push_back(TCArgs.MakeArgString(
9677 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9678
9679 assert(JA.getInputs().size() == Inputs.size() &&
9680 "Not have inputs for all dependence actions??");
9681
9682 // Get the targets.
9683 SmallString<128> Triples;
9684 Triples += "-targets=";
9685 for (unsigned I = 0; I < Inputs.size(); ++I) {
9686 if (I)
9687 Triples += ',';
9688
9689 // Find ToolChain for this input.
9691 const ToolChain *CurTC = &getToolChain();
9692 const Action *CurDep = JA.getInputs()[I];
9693
9694 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9695 CurTC = nullptr;
9696 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9697 assert(CurTC == nullptr && "Expected one dependence!");
9698 CurKind = A->getOffloadingDeviceKind();
9699 CurTC = TC;
9700 });
9701 }
9702 Triples += Action::GetOffloadKindName(CurKind);
9703 Triples += '-';
9704 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9705 TCArgs, CurDep->getOffloadingArch()))
9706 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9707
9708 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9709 Triples += '-';
9710 Triples += CurDep->getOffloadingArch().ArchName;
9711 }
9712 }
9713 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9714
9715 // Get bundled file command.
9716 CmdArgs.push_back(
9717 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9718
9719 // Get unbundled files command.
9720 for (unsigned I = 0; I < Inputs.size(); ++I) {
9722 UB += "-input=";
9723
9724 // Find ToolChain for this input.
9725 const ToolChain *CurTC = &getToolChain();
9726 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9727 CurTC = nullptr;
9728 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9729 assert(CurTC == nullptr && "Expected one dependence!");
9730 CurTC = TC;
9731 });
9732 UB += C.addTempFile(
9733 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9734 } else {
9735 UB += CurTC->getInputFilename(Inputs[I]);
9736 }
9737 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9738 }
9739 addOffloadCompressArgs(TCArgs, CmdArgs);
9740 if (TCArgs.hasArg(options::OPT_v))
9741 CmdArgs.push_back("--verbose");
9742 // All the inputs are encoded as commands.
9743 C.addCommand(std::make_unique<Command>(
9744 JA, *this, ResponseFileSupport::None(),
9745 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9746 CmdArgs, ArrayRef<InputInfo>(), Output));
9747}
9748
9750 const InputInfo &Output,
9751 const InputInfoList &Inputs,
9752 const llvm::opt::ArgList &Args,
9753 const char *LinkingOutput) const {
9754 ArgStringList CmdArgs;
9755
9756 // Add the output file name.
9757 assert(Output.isFilename() && "Invalid output.");
9758 CmdArgs.push_back("-o");
9759 CmdArgs.push_back(Output.getFilename());
9760
9761 // Create the inputs to bundle the needed metadata.
9762 for (const InputInfo &Input : Inputs) {
9763 const Action *OffloadAction = Input.getAction();
9765 const ArgList &TCArgs =
9766 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9768 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9770 if (Arch.empty())
9771 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9772
9773 StringRef Kind =
9775
9776 ArgStringList Features;
9777 SmallVector<StringRef> FeatureArgs;
9778 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9779 false);
9780 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9781 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9782
9783 // TODO: We need to pass in the full target-id and handle it properly in the
9784 // linker wrapper.
9786 "file=" + File.str(),
9787 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9788 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9789 "kind=" + Kind.str(),
9790 };
9791
9793 for (StringRef Feature : FeatureArgs)
9794 Parts.emplace_back("feature=" + Feature.str());
9795
9796 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9797 }
9798
9799 // FIXME: --offload-compress is HIP only until the OpenMP runtime accepts it.
9801 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
9802 addOffloadCompressArgs(Args, CmdArgs, /*EmitCompressionFormat=*/true);
9803
9804 C.addCommand(std::make_unique<Command>(
9806 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9807 CmdArgs, Inputs, Output));
9808}
9809
9810// Options that need the profile compiler-rt library on the target toolchain.
9811// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9812// too.
9813static bool requiresProfileRT(unsigned ID) {
9814 switch (ID) {
9815 case options::OPT_fprofile_generate:
9816 case options::OPT_fprofile_generate_EQ:
9817 case options::OPT_fprofile_instr_generate:
9818 case options::OPT_fprofile_instr_generate_EQ:
9819 case options::OPT_fcoverage_mapping:
9820 case options::OPT_fno_coverage_mapping:
9821 case options::OPT_fcoverage_compilation_dir_EQ:
9822 case options::OPT_ffile_compilation_dir_EQ:
9823 case options::OPT_fcoverage_prefix_map_EQ:
9824 return true;
9825 default:
9826 return false;
9827 }
9828}
9829
9830// Options that need the ubsan compiler-rt library on the target toolchain.
9831static bool requiresUBSanRT(unsigned ID) {
9832 switch (ID) {
9833 case options::OPT_fsanitize_EQ:
9834 case options::OPT_fno_sanitize_EQ:
9835 case options::OPT_fsanitize_minimal_runtime:
9836 case options::OPT_fno_sanitize_minimal_runtime:
9837 return true;
9838 default:
9839 return false;
9840 }
9841}
9842
9844 const InputInfo &Output,
9845 const InputInfoList &Inputs,
9846 const ArgList &Args,
9847 const char *LinkingOutput) const {
9848 using namespace options;
9849
9850 // A list of permitted options that will be forwarded to the embedded device
9851 // compilation job.
9852 const llvm::DenseSet<unsigned> CompilerOptions{
9853 OPT_v,
9854 OPT_hip_path_EQ,
9855 OPT_O_Group,
9856 OPT_g_Group,
9857 OPT_g_flags_Group,
9858 OPT_R_value_Group,
9859 OPT_R_Group,
9860 OPT_Xcuda_ptxas,
9861 OPT_ptxas_path_EQ,
9862 OPT_ftime_report,
9863 OPT_ftime_trace,
9864 OPT_ftime_trace_EQ,
9865 OPT_ftime_trace_granularity_EQ,
9866 OPT_ftime_trace_verbose,
9867 OPT_ftime_trace_compress_EQ,
9868 OPT_opt_record_file,
9869 OPT_opt_record_format,
9870 OPT_opt_record_passes,
9871 OPT_fsave_optimization_record,
9872 OPT_fsave_optimization_record_EQ,
9873 OPT_fno_save_optimization_record,
9874 OPT_foptimization_record_file_EQ,
9875 OPT_foptimization_record_passes_EQ,
9876 OPT_save_temps,
9877 OPT_save_temps_EQ,
9878 OPT_mcode_object_version_EQ,
9879 OPT_load,
9880 OPT_no_canonical_prefixes,
9881 OPT_fno_lto,
9882 OPT_flto,
9883 OPT_flto_partitions_EQ,
9884 OPT_flto_EQ,
9885 OPT_hipspv_pass_plugin_EQ,
9886 OPT_use_spirv_backend,
9887 OPT_no_use_spirv_backend,
9888 OPT_fmultilib_flag,
9889 OPT_fprofile_generate,
9890 OPT_fprofile_generate_EQ,
9891 OPT_fprofile_instr_generate,
9892 OPT_fprofile_instr_generate_EQ,
9893 OPT_fcoverage_mapping,
9894 OPT_fno_coverage_mapping,
9895 OPT_fcoverage_compilation_dir_EQ,
9896 OPT_ffile_compilation_dir_EQ,
9897 OPT_fcoverage_prefix_map_EQ,
9898 OPT_fsanitize_EQ,
9899 OPT_fno_sanitize_EQ,
9900 OPT_fsanitize_minimal_runtime,
9901 OPT_fno_sanitize_minimal_runtime,
9902 OPT_fsanitize_trap_EQ,
9903 OPT_fno_sanitize_trap_EQ,
9904 OPT_fvectorize,
9905 OPT_fno_vectorize,
9906 OPT_fslp_vectorize,
9907 OPT_fno_slp_vectorize,
9908 OPT_hipstdpar,
9909 OPT_fenable_spirv_size_optimization};
9910 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9911 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9912 // CMake implicit linker argument parsing.
9913 bool SuppressHIPNoRDCVerbose =
9914 JA.getType() == types::TY_HIP_FATBIN &&
9915 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9916 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9917 return TC.getVFS().exists(
9918 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9919 };
9920 auto ToolChainHasSanitizerRT = [&](const ToolChain &TC, const ArgList &TCArgs,
9921 Action::OffloadKind Kind) {
9922 if (TC.getSanitizerArgs(TCArgs, /*BA=*/{}, Kind).needsCsanRt())
9923 return ToolChainHasRT(TC, "csan");
9924 return ToolChainHasRT(TC, "ubsan_minimal") ||
9925 ToolChainHasRT(TC, "ubsan_standalone");
9926 };
9927 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC,
9928 bool HasSanitizerRT) {
9929 unsigned ID = A->getOption().getID();
9930 // Don't forward profiling arguments if the toolchain doesn't support it.
9931 // Without this check using it on the host would result in linker errors.
9932 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9933 // together to avoid a device cc1 diagnostic.
9934 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9935 return false;
9936 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9937 // Without this check using it on the host would result in linker errors.
9938 if (requiresUBSanRT(ID) && !HasSanitizerRT)
9939 return false;
9940 // Don't forward -mllvm to toolchains that don't support LLVM.
9941 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9942 };
9943 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9944 const ToolChain &TC, bool HasSanitizerRT) {
9945 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9946 return false;
9947 return (Set.contains(A->getOption().getID()) ||
9948 (A->getOption().getGroup().isValid() &&
9949 Set.contains(A->getOption().getGroup().getID()))) &&
9950 ShouldForwardForToolChain(A, TC, HasSanitizerRT);
9951 };
9952
9953 ArgStringList CmdArgs;
9956 auto TCRange = C.getOffloadToolChains(Kind);
9957 for (auto &I : llvm::make_range(TCRange)) {
9958 const ToolChain *TC = I.second;
9959
9960 // We do not use a bound architecture here so options passed only to a
9961 // specific architecture via -Xarch_<cpu> will not be forwarded.
9962 ArgStringList CompilerArgs;
9963 ArgStringList LinkerArgs;
9964 const DerivedArgList &ToolChainArgs =
9965 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9966 const bool HasSanitizerRT =
9967 ToolChainHasSanitizerRT(*TC, ToolChainArgs, Kind);
9968 for (Arg *A : ToolChainArgs) {
9969 if (A->getOption().matches(OPT_Zlinker_input))
9970 LinkerArgs.emplace_back(A->getValue());
9971 else if (ShouldForward(CompilerOptions, A, *TC, HasSanitizerRT)) {
9972 A->claim();
9973 A->render(Args, CompilerArgs);
9974 } else if (ShouldForward(LinkerOptions, A, *TC, HasSanitizerRT)) {
9975 A->claim();
9976 A->render(Args, LinkerArgs);
9977 }
9978 }
9979
9980 // If the user explicitly requested it via `--offload-arch` we should
9981 // extract it from any static libraries if present. Device images are
9982 // labeled with the canonical target ID, so request that.
9983 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ)) {
9984 std::optional<std::string> TargetID =
9985 getCanonicalTargetID(TC->getTriple(), Arg);
9986 CmdArgs.emplace_back(Args.MakeArgString(
9987 "--should-extract=" + (TargetID ? StringRef(*TargetID) : Arg)));
9988 }
9989
9990 // If this is OpenMP the device linker will need `-lompdevice`.
9991 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9992 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9993 LinkerArgs.emplace_back("-lompdevice");
9994
9995 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9996 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9997 // flags to normal compilation.
9998 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9999 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
10000 if (TC->getTriple().isSPIRV() &&
10001 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
10002 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
10003 // For SPIR-V some functions will be defined by the runtime so allow
10004 // unresolved symbols in `spirv-link`.
10005 LinkerArgs.emplace_back("--allow-partial-linkage");
10006 // Don't optimize out exported symbols.
10007 LinkerArgs.emplace_back("--create-library");
10008 }
10009
10010 // Forward the SYCL device image split option to clang-sycl-linker.
10011 // The driver and clang-sycl-linker share the same value vocabulary, so
10012 // the value is passed through verbatim after validation.
10013 if (Kind == Action::OFK_SYCL) {
10014 if (Arg *A =
10015 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
10016 StringRef Mode = A->getValue();
10017 if (Mode != "kernel" && Mode != "translation_unit" &&
10018 Mode != "link_unit")
10019 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
10020 << A->getSpelling() << Mode;
10021 else
10022 LinkerArgs.emplace_back(
10023 Args.MakeArgString("--module-split-mode=" + Mode));
10024 }
10025 }
10026
10027 // Forward all of these to the appropriate toolchain.
10028 for (StringRef Arg : CompilerArgs)
10029 CmdArgs.push_back(Args.MakeArgString(
10030 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
10031 for (StringRef Arg : LinkerArgs)
10032 CmdArgs.push_back(Args.MakeArgString(
10033 "--device-linker=" + TC->getTripleString() + "=" + Arg));
10034
10035 // Forward the LTO mode for this toolchain.
10036 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
10037 if (DeviceLTOMode == LTOK_Full)
10038 CmdArgs.push_back(Args.MakeArgString(
10039 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
10040 else if (DeviceLTOMode == LTOK_Thin) {
10041 CmdArgs.push_back(Args.MakeArgString(
10042 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
10043 if (TC->getTriple().isAMDGPU()) {
10044 CmdArgs.push_back(
10045 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10046 "=-plugin-opt=-force-import-all"));
10047 CmdArgs.push_back(
10048 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10049 "=-plugin-opt=-avail-extern-to-local"));
10050 CmdArgs.push_back(Args.MakeArgString(
10051 "--device-linker=" + TC->getTripleString() +
10052 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
10053 if (Kind == Action::OFK_OpenMP) {
10054 CmdArgs.push_back(
10055 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10056 "=-plugin-opt=-amdgpu-internalize-symbols"));
10057 }
10058 }
10059 }
10060 }
10061 }
10062
10063 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
10064 CmdArgs.push_back(
10065 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
10066 else
10067 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
10068 getToolChain().getTripleString()));
10069
10070 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
10071 CmdArgs.push_back("--wrapper-verbose");
10072 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
10073 CmdArgs.push_back(
10074 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
10075 CmdArgs.push_back(Args.MakeArgString(
10076 Twine("--device-compiler=--cuda-path=") + A->getValue()));
10077 }
10078 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
10079 CmdArgs.push_back(Args.MakeArgString(
10080 Twine("--device-compiler=--rocm-path=") + A->getValue()));
10081 }
10082
10083 // Construct the link job so we can wrap around it.
10084 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
10085 const auto &LinkCommand = C.getJobs().getJobs().back();
10086
10087 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10088 // wrapper.
10089 for (Arg *A :
10090 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
10091 StringRef Val = A->getValue(0);
10092 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10093 auto WrapperOption =
10094 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10095 if (Val.empty())
10096 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
10097 else
10098 CmdArgs.push_back(Args.MakeArgString(
10099 WrapperOption +
10100 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
10101 A->getValue(1)));
10102 }
10103 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
10104 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
10105
10106 // Embed bitcode instead of an object in JIT mode.
10107 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10108 options::OPT_fno_openmp_target_jit, false))
10109 CmdArgs.push_back("--embed-bitcode");
10110
10111 // Save temporary files created by the linker wrapper.
10112 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10113 Args.hasArg(options::OPT_save_temps))
10114 CmdArgs.push_back("--save-temps");
10115
10116 // Pass in the C library for GPUs if present and not disabled.
10117 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10118 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10119 options::OPT_nodefaultlibs, options::OPT_nolibc,
10120 options::OPT_nogpulibc)) {
10121 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10122 // The device C library is only available for NVPTX and AMDGPU targets
10123 // and we only link it by default for OpenMP currently.
10124 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10126 return;
10127 bool HasLibC = TC.getStdlibIncludePath().has_value();
10128 if (HasLibC) {
10129 CmdArgs.push_back(Args.MakeArgString(
10130 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10131 CmdArgs.push_back(Args.MakeArgString(
10132 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10133 }
10134 auto HasCompilerRT = getToolChain().getVFS().exists(
10135 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10136 /*IsFortran=*/false));
10137 if (HasCompilerRT)
10138 CmdArgs.push_back(
10139 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10140 "-lclang_rt.builtins"));
10141
10142 bool HasFlangRT = getToolChain().getVFS().exists(
10143 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10144 /*IsFortran=*/true));
10145 if (HasFlangRT && C.getDriver().IsFlangMode())
10146 CmdArgs.push_back(
10147 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10148 "-lflang_rt.runtime"));
10149 });
10150 }
10151
10152 // Add the linker arguments to be forwarded by the wrapper.
10153 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10154 LinkCommand->getExecutable()));
10155
10156 // We use action type to differentiate two use cases of the linker wrapper.
10157 // TY_Image for normal linker wrapper work.
10158 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10159 // binary directly.
10160 assert(JA.getType() == types::TY_HIP_FATBIN ||
10161 JA.getType() == types::TY_SYCL_FATBIN ||
10162 JA.getType() == types::TY_Image);
10163 if (JA.getType() != types::TY_Image) {
10164 CmdArgs.push_back("--emit-fatbin-only");
10165 CmdArgs.append({"-o", Output.getFilename()});
10166 for (auto Input : Inputs)
10167 CmdArgs.push_back(Input.getFilename());
10168 } else {
10169 for (const char *LinkArg : LinkCommand->getArguments())
10170 CmdArgs.push_back(LinkArg);
10171 }
10172
10173 addOffloadCompressArgs(Args, CmdArgs);
10174
10175 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10176 if (OffloadJobs.A) {
10177 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10178 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10179 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10180 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10181 Twine(OffloadJobs.NumThreads)));
10182 } else if (!OffloadJobs.A->isClaimed()) {
10183 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10184 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10185 }
10186 }
10187
10188 // Propagate -no-canonical-prefixes.
10189 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10190 CmdArgs.push_back("--no-canonical-prefixes");
10191
10192 const char *Exec =
10193 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10194
10195 // Replace the executable and arguments of the link job with the
10196 // wrapper.
10197 LinkCommand->replaceExecutable(Exec);
10198 LinkCommand->replaceArguments(CmdArgs);
10199}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3984
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:119
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2359
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4413
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:729
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5180
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9813
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4594
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:778
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:72
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1373
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1225
static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args, bool isWindowsMSVC)
/EH controls whether to run destructor cleanups when exceptions are thrown.
Definition Clang.cpp:8922
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2338
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:795
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4086
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4728
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2617
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1263
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:755
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:339
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4705
static void RenderObjCOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, ObjCRuntime &Runtime, bool InferCovariantReturns, const InputInfo &Input, ArgStringList &CmdArgs)
Definition Clang.cpp:4449
static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the coverage file path prefix map.
Definition Clang.cpp:324
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2622
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1274
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2390
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2628
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2331
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4152
static void forAllAssociatedToolChains(Compilation &C, const JobAction &JA, const ToolChain &RegularToolChain, llvm::function_ref< void(const ToolChain &)> Work)
Apply Work on the current tool chain RegularToolChain and any other offloading tool chain that is ass...
Definition Clang.cpp:99
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3656
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the macro file path prefix map.
Definition Clang.cpp:309
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, bool IsDeviceOffloadAction, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition Clang.cpp:139
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1290
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:254
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1408
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3666
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4094
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3894
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3913
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8901
static const char * addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs, const llvm::vfs::FileSystem &VFS)
Add a CC1 option to specify the debug compilation directory.
Definition Clang.cpp:234
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:87
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:217
static void renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, types::ID InputType, ArgStringList &CmdArgs, const InputInfo &Output, llvm::codegenoptions::DebugInfoKind &DebugInfoKind, DwarfFissionKind &DwarfFission, bool IsUsingLTO)
Definition Clang.cpp:4745
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9831
static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the debug file path prefix map.
Definition Clang.cpp:288
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3587
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2365
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2995
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:373
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4029
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
TokenType getType() const
Returns the token's type, e.g.
Defines enums used when emitting included header information.
Defines the clang::LangOptions interface.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
Defines version macros and version-related utility functions for Clang.
static StringRef getWarningOptionForGroup(diag::Group)
Given a group ID, returns the flag that toggles the group.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:952
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Kind getKind() const
Definition ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
bool hasConstantLiteralClasses() const
Are Foundation backed constant literal classes supported?
const VersionTuple & getVersion() const
Definition ObjCRuntime.h:78
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
std::string getAsString() const
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
A processor an offloading action can target.
Definition OffloadArch.h:36
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
Definition Scope.h:263
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
types::ID getType() const
Definition Action.h:153
const ToolChain * getOffloadingToolChain() const
Definition Action.h:217
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition Action.cpp:143
BoundArch getOffloadingArch() const
Definition Action.h:216
ActionClass getKind() const
Definition Action.h:152
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:159
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:215
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:223
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:226
ActionList & getInputs()
Definition Action.h:155
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:211
bool isOffloading(OffloadKind OKind) const
Definition Action.h:229
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
Distro - Helper class for detecting and classifying Linux distributions.
Definition Distro.h:23
bool IsGentoo() const
Definition Distro.h:135
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
llvm::SmallVector< BoundArch > getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, Action::OffloadKind Kind, const ToolChain &TC) const
Returns the set of bound architectures active for this offload kind.
Definition Driver.cpp:4043
std::string SysRoot
sysroot, if present
Definition Driver.h:193
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
const char * getPrependArg() const
Definition Driver.h:419
CC1ToolFunc CC1Main
Definition Driver.h:289
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:920
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:267
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4118
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:271
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:281
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:6152
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2546
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:430
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:217
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:214
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:177
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:168
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:250
std::string getTargetTriple() const
Definition Driver.h:427
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:256
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:171
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:223
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
bool getProbePrecompiled() const
Definition Driver.h:416
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getBaseInput() const
Definition InputInfo.h:78
const llvm::opt::Arg & getInputArg() const
Definition InputInfo.h:87
const char * getFilename() const
Definition InputInfo.h:83
bool isNothing() const
Definition InputInfo.h:74
const Action * getAction() const
The action for which this InputInfo was created. May be null.
Definition InputInfo.h:80
bool isFilename() const
Definition InputInfo.h:75
types::ID getType() const
Definition InputInfo.h:77
An offload action combines host or/and device actions according to the programming model implementati...
Definition Action.h:273
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:907
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:656
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual unsigned getMaxDwarfVersion() const
Definition ToolChain.h:665
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:689
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
virtual llvm::DenormalMode getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs, const JobAction &JA, const llvm::fltSemantics *FPType=nullptr) const
Returns the output denormal handling type in the default floating point environment for the given FPT...
Definition ToolChain.h:899
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
virtual llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const
Get the default debug info format. Typically, this is DWARF.
Definition ToolChain.h:647
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:519
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
RTTIMode getRTTIMode() const
Definition ToolChain.h:365
llvm::vfs::FileSystem & getVFS() const
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
virtual llvm::DebuggerKind getDefaultDebuggerTuning() const
Definition ToolChain.h:678
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:540
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
virtual bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition ToolChain.h:511
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:700
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:671
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual bool getDefaultDebugSimpleTemplateNames() const
Returns true if this toolchain adds '-gsimple-template-names=simple' by default when generating debug...
Definition ToolChain.h:675
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
StringRef getTripleString() const
Definition ToolChain.h:307
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:534
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:740
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:653
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:641
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
virtual bool canSplitThinLTOUnit() const
Returns true when it's possible to split LTO unit to use whole program devirtualization and CFI santi...
Definition ToolChain.h:894
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition ToolChain.h:523
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
std::optional< std::string > getStdlibIncludePath() const
virtual void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const
Add options that need to be passed to cc1as for this target.
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition ToolChain.h:486
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
virtual void CheckObjCARC() const
Complain if this tool chain doesn't support Objective-C ARC.
Definition ToolChain.h:644
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
virtual bool IsEncodeExtendedBlockSignatureDefault() const
IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable -fencode-extended-block-signature...
Definition ToolChain.h:515
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:482
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
virtual const llvm::Triple * getAuxTriple() const
Get the toolchain's aux triple, if it has one.
Definition ToolChain.h:291
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:508
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:51
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:13
const char * getShortName() const
Definition Tool.h:49
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition XRayArgs.cpp:181
static std::optional< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1064
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:674
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9326
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9309
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9334
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9349
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9298
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9268
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8756
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9283
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9273
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:5280
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9843
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9657
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Clang.cpp:9749
void addSanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addProfileRTArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
std::optional< std::string > getAArch64TargetTuneCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition AArch64.cpp:117
bool isHardTPSupported(const llvm::Triple &Triple)
Definition ARM.cpp:210
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::string postProcessTargetCPUString(const std::string &CPU, const llvm::Triple &Triple)
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasCompactBranches(StringRef &CPU)
Definition Mips.cpp:479
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:313
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:441
FloatABI getSparcFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
FloatABI getSystemZFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO, const StringRef PluginOptPrefix="")
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO, const StringRef PluginOptPrefix="")
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void handleVectorizeSLPArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fslp-vectorize based on the optimization level selected.
OffloadJobsOpt parseOffloadJobs(const llvm::opt::ArgList &Args)
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs, bool EmitCompressionFormat=false)
void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
std::string complexRangeKindToStr(LangOptions::ComplexRangeKind Range)
void handleColorDiagnosticsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Handle the -f{no}-color-diagnostics and -f{no}-diagnostics-colors options.
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
bool useMachORelocatableDwarf(const llvm::Triple &T, unsigned DwarfVersion)
Whether Mach-O objects for T with DWARF DwarfVersion relocate offsets between DWARF sections.
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
llvm::SmallString< 256 > getCXX20NamedModuleOutputPath(const llvm::opt::ArgList &Args, const char *BaseInput)
void setComplexRange(const Driver &D, StringRef NewOpt, LangOptions::ComplexRangeKind NewRange, StringRef &LastOpt, LangOptions::ComplexRangeKind &Range)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
std::string renderComplexRangeOption(LangOptions::ComplexRangeKind Range)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
void addSplitMachineFunctionsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
void handleVectorizeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fvectorize based on the optimization level selected.
void escapeSpacesAndBackslashes(const char *Arg, llvm::SmallVectorImpl< char > &Res)
Add backslashes to escape spaces and other backslashes.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition Types.cpp:329
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition Types.cpp:53
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition Types.cpp:292
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition Types.cpp:49
bool isOpenCL(ID Id)
isOpenCL - Is this an "OpenCL" input.
Definition Types.cpp:253
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:331
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:265
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:49
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
unsigned CudaArchToID(OffloadArch Arch)
Get the numeric ID (e.g. 700) of a CUDA architecture.
Definition Cuda.cpp:133
StringRef parseMPreferVectorWidthOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
@ C
Languages that the frontend can parse and compile.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:60
std::string getCanonicalTargetID(llvm::StringRef Processor, const llvm::StringMap< bool > &Features)
Returns canonical target ID, assuming Processor is canonical and all entries in Features are valid.
Definition TargetID.cpp:146
U cast(CodeGen::Address addr)
Definition Address.h:327
StringRef parseMRecipOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition Version.cpp:96
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:39
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
bool empty() const
LangStandard - Information about the properties of a particular language standard.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
static const LangStandard * getLangStandardForName(StringRef Name)
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
clang::Language getLanguage() const
Get the language that this standard describes.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:79
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:86