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