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#include <iterator>
65
66using namespace clang::driver;
67using namespace clang::driver::tools;
68using namespace clang;
69using namespace llvm::opt;
70
71static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,
73 options::OPT_fminimize_whitespace,
74 options::OPT_fno_minimize_whitespace,
75 options::OPT_fkeep_system_includes,
76 options::OPT_fno_keep_system_includes)) {
77 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
78 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
79 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
80 << A->getBaseArg().getAsString(Args)
81 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 }
83 }
84}
85
86static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
87 // In gcc, only ARM checks this, but it seems reasonable to check universally.
88 if (Args.hasArg(options::OPT_static))
89 if (const Arg *A =
90 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
91 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
92 << "-static";
93}
94
95/// Apply \a Work on the current tool chain \a RegularToolChain and any other
96/// offloading tool chain that is associated with the current action \a JA.
97static void
99 const ToolChain &RegularToolChain,
100 llvm::function_ref<void(const ToolChain &)> Work) {
101 // Apply Work on the current/regular tool chain.
102 Work(RegularToolChain);
103
104 // Apply Work on all the offloading tool chains associated with the current
105 // action.
108 if (JA.isHostOffloading(Kind)) {
109 auto TCs = C.getOffloadToolChains(Kind);
110 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
111 Work(*II->second);
112 } else if (JA.isDeviceOffloading(Kind))
113 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
114 }
115}
116
117static bool
119 const llvm::Triple &Triple) {
120 // We use the zero-cost exception tables for Objective-C if the non-fragile
121 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
122 // later.
123 if (runtime.isNonFragile())
124 return true;
125
126 if (!Triple.isMacOSX())
127 return false;
128
129 return (!Triple.isMacOSXVersionLT(10, 5) &&
130 (Triple.getArch() == llvm::Triple::x86_64 ||
131 Triple.getArch() == llvm::Triple::arm));
132}
133
134/// Adds exception related arguments to the driver command arguments. There's a
135/// main flag, -fexceptions and also language specific flags to enable/disable
136/// C++ and Objective-C exceptions. This makes it possible to for example
137/// disable C++ exceptions but enable Objective-C exceptions.
138static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
139 const ToolChain &TC, bool KernelOrKext,
140 bool IsDeviceOffloadAction,
141 const ObjCRuntime &objcRuntime,
142 ArgStringList &CmdArgs) {
143 const llvm::Triple &Triple = TC.getTriple();
144
145 if (KernelOrKext) {
146 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
147 // arguments now to avoid warnings about unused arguments.
148 Args.ClaimAllArgs(options::OPT_fexceptions);
149 Args.ClaimAllArgs(options::OPT_fno_exceptions);
150 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
151 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
152 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
153 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
154 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
155 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
156 return false;
157 }
158
159 // See if the user explicitly enabled exceptions.
160 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
161 false);
162
163 // Async exceptions are Windows MSVC only.
164 if (Triple.isWindowsMSVCEnvironment()) {
165 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
166 options::OPT_fno_async_exceptions, false);
167 if (EHa) {
168 CmdArgs.push_back("-fasync-exceptions");
169 EH = true;
170 }
171 }
172
173 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
174 // is not necessarily sensible, but follows GCC.
175 if (types::isObjC(InputType) &&
176 Args.hasFlag(options::OPT_fobjc_exceptions,
177 options::OPT_fno_objc_exceptions, true)) {
178 CmdArgs.push_back("-fobjc-exceptions");
179
180 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
181 }
182
183 if (types::isCXX(InputType)) {
184 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
186 !Triple.isPS() && !Triple.isDriverKit() &&
187 !(Triple.isGPU() && !IsDeviceOffloadAction);
188 Arg *ExceptionArg = Args.getLastArg(
189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
190 options::OPT_fexceptions, options::OPT_fno_exceptions);
191 if (ExceptionArg)
192 CXXExceptionsEnabled =
193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
195
196 if (CXXExceptionsEnabled) {
197 CmdArgs.push_back("-fcxx-exceptions");
198
199 EH = true;
200 }
201 }
202
203 // OPT_fignore_exceptions means exception could still be thrown,
204 // but no clean up or catch would happen in current module.
205 // So we do not set EH to false.
206 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
207
208 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
209 options::OPT_fno_assume_nothrow_exception_dtor);
210
211 if (EH)
212 CmdArgs.push_back("-fexceptions");
213 return EH;
214}
215
216static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
217 const JobAction &JA) {
218 bool Default = true;
219 if (TC.getTriple().isOSDarwin()) {
220 // The native darwin assembler doesn't support the linker_option directives,
221 // so we disable them if we think the .s file will be passed to it.
223 }
224 // The linker_option directives are intended for host compilation.
227 Default = false;
228 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
229 Default);
230}
231
232/// Add a CC1 option to specify the debug compilation directory.
233static const char *addDebugCompDirArg(const ArgList &Args,
234 ArgStringList &CmdArgs,
235 const llvm::vfs::FileSystem &VFS) {
236 std::string DebugCompDir;
237 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
238 options::OPT_fdebug_compilation_dir_EQ))
239 DebugCompDir = A->getValue();
240
241 if (DebugCompDir.empty()) {
242 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
243 DebugCompDir = std::move(*CWD);
244 else
245 return nullptr;
246 }
247 CmdArgs.push_back(
248 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
249 StringRef Path(CmdArgs.back());
250 return Path.substr(Path.find('=') + 1).data();
251}
252
253static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
254 const char *DebugCompilationDir,
255 const char *OutputFileName) {
256 // No need to generate a value for -object-file-name if it was provided.
257 for (auto *Arg : Args.filtered(options::OPT_Xclang))
258 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
259 return;
260
261 if (Args.hasArg(options::OPT_object_file_name_EQ))
262 return;
263
264 SmallString<128> ObjFileNameForDebug(OutputFileName);
265 if (ObjFileNameForDebug != "-" &&
266 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
267 (!DebugCompilationDir ||
268 llvm::sys::path::is_absolute(DebugCompilationDir))) {
269 // Make the path absolute in the debug infos like MSVC does.
270 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
271 }
272 // If the object file name is a relative path, then always use Windows
273 // backslash style as -object-file-name is used for embedding object file path
274 // in codeview and it can only be generated when targeting on Windows.
275 // Otherwise, just use native absolute path.
276 llvm::sys::path::Style Style =
277 llvm::sys::path::is_absolute(ObjFileNameForDebug)
278 ? llvm::sys::path::Style::native
279 : llvm::sys::path::Style::windows_backslash;
280 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
281 Style);
282 CmdArgs.push_back(
283 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
284}
285
286/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
287static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
288 const ArgList &Args, ArgStringList &CmdArgs) {
289 auto AddOneArg = [&](StringRef Map, StringRef Name) {
290 if (!Map.contains('='))
291 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
292 else
293 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
294 };
295
296 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
297 options::OPT_fdebug_prefix_map_EQ)) {
298 AddOneArg(A->getValue(), A->getOption().getName());
299 A->claim();
300 }
301 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
302 if (GlobalRemapEntry.empty())
303 return;
304 AddOneArg(GlobalRemapEntry, "environment");
305}
306
307/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
308static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
309 ArgStringList &CmdArgs) {
310 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
311 options::OPT_fmacro_prefix_map_EQ)) {
312 StringRef Map = A->getValue();
313 if (!Map.contains('='))
314 D.Diag(diag::err_drv_invalid_argument_to_option)
315 << Map << A->getOption().getName();
316 else
317 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
318 A->claim();
319 }
320}
321
322/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
323static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
324 ArgStringList &CmdArgs) {
325 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
326 options::OPT_fcoverage_prefix_map_EQ)) {
327 StringRef Map = A->getValue();
328 if (!Map.contains('='))
329 D.Diag(diag::err_drv_invalid_argument_to_option)
330 << Map << A->getOption().getName();
331 else
332 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
333 A->claim();
334 }
335}
336
337/// Add -x lang to \p CmdArgs for \p Input.
338static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
339 ArgStringList &CmdArgs) {
340 // When using -verify-pch, we don't want to provide the type
341 // 'precompiled-header' if it was inferred from the file extension
342 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
343 return;
344
345 CmdArgs.push_back("-x");
346 if (Args.hasArg(options::OPT_rewrite_objc))
347 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
348 else {
349 // Map the driver type to the frontend type. This is mostly an identity
350 // mapping, except that the distinction between module interface units
351 // and other source files does not exist at the frontend layer.
352 const char *ClangType;
353 switch (Input.getType()) {
354 case types::TY_CXXModule:
355 case types::TY_CXXStdModule:
356 ClangType = "c++";
357 break;
358 case types::TY_PP_CXXModule:
359 ClangType = "c++-cpp-output";
360 break;
361 default:
362 ClangType = types::getTypeName(Input.getType());
363 break;
364 }
365 CmdArgs.push_back(ClangType);
366 }
367}
368
370 const JobAction &JA, const InputInfo &Output,
371 const ArgList &Args, SanitizerArgs &SanArgs,
372 ArgStringList &CmdArgs) {
373 const Driver &D = TC.getDriver();
374 const llvm::Triple &T = TC.getTriple();
375 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
376 options::OPT_fprofile_generate_EQ,
377 options::OPT_fno_profile_generate);
378 if (PGOGenerateArg &&
379 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
380 PGOGenerateArg = nullptr;
381
382 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
383
384 auto *ProfileGenerateArg = Args.getLastArg(
385 options::OPT_fprofile_instr_generate,
386 options::OPT_fprofile_instr_generate_EQ,
387 options::OPT_fno_profile_instr_generate);
388 if (ProfileGenerateArg &&
389 ProfileGenerateArg->getOption().matches(
390 options::OPT_fno_profile_instr_generate))
391 ProfileGenerateArg = nullptr;
392
393 if (PGOGenerateArg && ProfileGenerateArg)
394 D.Diag(diag::err_drv_argument_not_allowed_with)
395 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
396
397 auto *ProfileUseArg = getLastProfileUseArg(Args);
398
399 if (PGOGenerateArg && ProfileUseArg)
400 D.Diag(diag::err_drv_argument_not_allowed_with)
401 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
402
403 if (ProfileGenerateArg && ProfileUseArg)
404 D.Diag(diag::err_drv_argument_not_allowed_with)
405 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
406
407 if (CSPGOGenerateArg && PGOGenerateArg) {
408 D.Diag(diag::err_drv_argument_not_allowed_with)
409 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
410 PGOGenerateArg = nullptr;
411 }
412
413 if (TC.getTriple().isOSAIX()) {
414 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
415 D.Diag(diag::err_drv_unsupported_opt_for_target)
416 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
417 }
418
419 if (ProfileGenerateArg) {
420 if (ProfileGenerateArg->getOption().matches(
421 options::OPT_fprofile_instr_generate_EQ))
422 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
423 ProfileGenerateArg->getValue()));
424 // The default is to use Clang Instrumentation.
425 CmdArgs.push_back("-fprofile-instrument=clang");
426 if (TC.getTriple().isWindowsMSVCEnvironment() &&
427 Args.hasFlag(options::OPT_frtlib_defaultlib,
428 options::OPT_fno_rtlib_defaultlib, true)) {
429 // Add dependent lib for clang_rt.profile
430 CmdArgs.push_back(Args.MakeArgString(
431 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
432 }
433 }
434
435 if (auto *ColdFuncCoverageArg = Args.getLastArg(
436 options::OPT_fprofile_generate_cold_function_coverage,
437 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
438 SmallString<128> Path(
439 ColdFuncCoverageArg->getOption().matches(
440 options::OPT_fprofile_generate_cold_function_coverage_EQ)
441 ? ColdFuncCoverageArg->getValue()
442 : "");
443 llvm::sys::path::append(Path, "default_%m.profraw");
444 // FIXME: Idealy the file path should be passed through
445 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
446 // shared with other profile use path(see PGOOptions), we need to refactor
447 // PGOOptions to make it work.
448 CmdArgs.push_back("-mllvm");
449 CmdArgs.push_back(Args.MakeArgString(
450 Twine("--instrument-cold-function-only-path=") + Path));
451 CmdArgs.push_back("-mllvm");
452 CmdArgs.push_back("--pgo-instrument-cold-function-only");
453 CmdArgs.push_back("-mllvm");
454 CmdArgs.push_back("--pgo-function-entry-coverage");
455 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
456 }
457
458 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
459 if (!PGOGenerateArg && !CSPGOGenerateArg)
460 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
461 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
462 CmdArgs.push_back("-mllvm");
463 CmdArgs.push_back("--pgo-temporal-instrumentation");
464 }
465
466 Arg *PGOGenArg = nullptr;
467 if (PGOGenerateArg) {
468 assert(!CSPGOGenerateArg);
469 PGOGenArg = PGOGenerateArg;
470 CmdArgs.push_back("-fprofile-instrument=llvm");
471 }
472 if (CSPGOGenerateArg) {
473 assert(!PGOGenerateArg);
474 PGOGenArg = CSPGOGenerateArg;
475 CmdArgs.push_back("-fprofile-instrument=csllvm");
476 }
477 if (PGOGenArg) {
478 if (TC.getTriple().isWindowsMSVCEnvironment() &&
479 Args.hasFlag(options::OPT_frtlib_defaultlib,
480 options::OPT_fno_rtlib_defaultlib, true)) {
481 // Add dependent lib for clang_rt.profile
482 CmdArgs.push_back(Args.MakeArgString(
483 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
484 }
485 if (PGOGenArg->getOption().matches(
486 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
487 : options::OPT_fcs_profile_generate_EQ)) {
488 SmallString<128> Path(PGOGenArg->getValue());
489 llvm::sys::path::append(Path, "default_%m.profraw");
490 CmdArgs.push_back(
491 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
492 }
493 }
494
495 if (ProfileUseArg) {
496 SmallString<128> UsePathBuf;
497 StringRef UsePath;
498 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
499 UsePath = ProfileUseArg->getValue();
500 else if ((ProfileUseArg->getOption().matches(
501 options::OPT_fprofile_use_EQ) ||
502 ProfileUseArg->getOption().matches(
503 options::OPT_fprofile_instr_use))) {
504 UsePathBuf =
505 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
506 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
507 llvm::sys::path::append(UsePathBuf, "default.profdata");
508 UsePath = UsePathBuf;
509 }
510 auto ReaderOrErr =
511 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
512 if (auto E = ReaderOrErr.takeError()) {
513 auto DiagID = D.getDiags().getCustomDiagID(
514 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
515 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
516 D.Diag(DiagID) << UsePath.str() << EI.message();
517 });
518 } else {
519 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
520 std::move(ReaderOrErr.get());
521 StringRef UseKind;
522 // Currently memprof profiles are only added at the IR level. Mark the
523 // profile type as IR in that case as well and the subsequent matching
524 // needs to detect which is available (might be one or both).
525 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
526 if (PGOReader->hasCSIRLevelProfile())
527 UseKind = "csllvm";
528 else
529 UseKind = "llvm";
530 } else
531 UseKind = "clang";
532
533 CmdArgs.push_back(
534 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
535 CmdArgs.push_back(
536 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
537 }
538 }
539
540 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
541 options::OPT_fno_test_coverage, false) ||
542 Args.hasArg(options::OPT_coverage);
543 bool EmitCovData = TC.needsGCovInstrumentation(Args);
544
545 if (Args.hasFlag(options::OPT_fcoverage_mapping,
546 options::OPT_fno_coverage_mapping, false)) {
547 if (!ProfileGenerateArg)
548 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
549 << "-fcoverage-mapping"
550 << "-fprofile-instr-generate";
551
552 CmdArgs.push_back("-fcoverage-mapping");
553 }
554
555 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
556 false)) {
557 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
558 options::OPT_fno_coverage_mapping, false))
559 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
560 << "-fcoverage-mcdc"
561 << "-fcoverage-mapping";
562
563 CmdArgs.push_back("-fcoverage-mcdc");
564 }
565
566 StringRef CoverageCompDir;
567 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
568 options::OPT_fcoverage_compilation_dir_EQ))
569 CoverageCompDir = A->getValue();
570 if (CoverageCompDir.empty()) {
571 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
572 CmdArgs.push_back(
573 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
574 } else
575 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
576 CoverageCompDir));
577
578 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
579 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
580 if (!Args.hasArg(options::OPT_coverage))
581 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
582 << "-fprofile-exclude-files="
583 << "--coverage";
584
585 StringRef v = Arg->getValue();
586 CmdArgs.push_back(
587 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
588 }
589
590 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
591 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
592 if (!Args.hasArg(options::OPT_coverage))
593 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
594 << "-fprofile-filter-files="
595 << "--coverage";
596
597 StringRef v = Arg->getValue();
598 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
599 }
600
601 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
602 StringRef Val = A->getValue();
603 if (Val == "atomic" || Val == "prefer-atomic")
604 CmdArgs.push_back("-fprofile-update=atomic");
605 else if (Val != "single")
606 D.Diag(diag::err_drv_unsupported_option_argument)
607 << A->getSpelling() << Val;
608 }
609 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
610 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
611 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
612 << A->getSpelling()
613 << "-fprofile-generate, -fprofile-instr-generate, or "
614 "-fcs-profile-generate";
615 else {
616 CmdArgs.push_back("-fprofile-continuous");
617 // Platforms that require a bias variable:
618 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
619 CmdArgs.push_back("-mllvm");
620 CmdArgs.push_back("-runtime-counter-relocation");
621 }
622 // -fprofile-instr-generate does not decide the profile file name in the
623 // FE, and so it does not define the filename symbol
624 // (__llvm_profile_filename). Instead, the runtime uses the name
625 // "default.profraw" for the profile file. When continuous mode is ON, we
626 // will create the filename symbol so that we can insert the "%c"
627 // modifier.
628 if (ProfileGenerateArg &&
629 (ProfileGenerateArg->getOption().matches(
630 options::OPT_fprofile_instr_generate) ||
631 (ProfileGenerateArg->getOption().matches(
632 options::OPT_fprofile_instr_generate_EQ) &&
633 strlen(ProfileGenerateArg->getValue()) == 0)))
634 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
635 }
636 }
637
638 int FunctionGroups = 1;
639 int SelectedFunctionGroup = 0;
640 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
641 StringRef Val = A->getValue();
642 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
643 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
644 }
645 if (const auto *A =
646 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
647 StringRef Val = A->getValue();
648 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
649 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
650 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
651 }
652 if (FunctionGroups != 1)
653 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
654 Twine(FunctionGroups)));
655 if (SelectedFunctionGroup != 0)
656 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
657 Twine(SelectedFunctionGroup)));
658
659 // Leave -fprofile-dir= an unused argument unless .gcda emission is
660 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
661 // the flag used. There is no -fno-profile-dir, so the user has no
662 // targeted way to suppress the warning.
663 Arg *FProfileDir = nullptr;
664 if (Args.hasArg(options::OPT_fprofile_arcs) ||
665 Args.hasArg(options::OPT_coverage))
666 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
667
668 // Put the .gcno and .gcda files (if needed) next to the primary output file,
669 // or fall back to a file in the current directory for `clang -c --coverage
670 // d/a.c` in the absence of -o.
671 if (EmitCovNotes || EmitCovData) {
672 SmallString<128> CoverageFilename;
673 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
674 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
675 // path separator.
676 CoverageFilename = DumpDir->getValue();
677 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
678 } else if (Arg *FinalOutput =
679 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
680 CoverageFilename = FinalOutput->getValue();
681 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
682 CoverageFilename = FinalOutput->getValue();
683 } else {
684 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
685 }
686 if (llvm::sys::path::is_relative(CoverageFilename))
687 (void)D.getVFS().makeAbsolute(CoverageFilename);
688 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
689 if (EmitCovNotes) {
690 CmdArgs.push_back(
691 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
692 }
693
694 if (EmitCovData) {
695 if (FProfileDir) {
696 SmallString<128> Gcno = std::move(CoverageFilename);
697 CoverageFilename = FProfileDir->getValue();
698 llvm::sys::path::append(CoverageFilename, Gcno);
699 }
700 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
701 CmdArgs.push_back(
702 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
703 }
704 }
705}
706
707static void
708RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
709 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
710 unsigned DwarfVersion,
711 llvm::DebuggerKind DebuggerTuning) {
712 addDebugInfoKind(CmdArgs, DebugInfoKind);
713 if (DwarfVersion > 0)
714 CmdArgs.push_back(
715 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
716 switch (DebuggerTuning) {
717 case llvm::DebuggerKind::GDB:
718 CmdArgs.push_back("-debugger-tuning=gdb");
719 break;
720 case llvm::DebuggerKind::LLDB:
721 CmdArgs.push_back("-debugger-tuning=lldb");
722 break;
723 case llvm::DebuggerKind::SCE:
724 CmdArgs.push_back("-debugger-tuning=sce");
725 break;
726 case llvm::DebuggerKind::DBX:
727 CmdArgs.push_back("-debugger-tuning=dbx");
728 break;
729 default:
730 break;
731 }
732}
733
734static void RenderDebugInfoCompressionArgs(const ArgList &Args,
735 ArgStringList &CmdArgs,
736 const Driver &D,
737 const ToolChain &TC) {
738 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
739 if (!A)
740 return;
741 if (checkDebugInfoOption(A, Args, D, TC)) {
742 StringRef Value = A->getValue();
743 if (Value == "none") {
744 CmdArgs.push_back("--compress-debug-sections=none");
745 } else if (Value == "zlib") {
746 if (llvm::compression::zlib::isAvailable()) {
747 CmdArgs.push_back(
748 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
749 } else {
750 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
751 }
752 } else if (Value == "zstd") {
753 if (llvm::compression::zstd::isAvailable()) {
754 CmdArgs.push_back(
755 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
756 } else {
757 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
758 }
759 } else {
760 D.Diag(diag::err_drv_unsupported_option_argument)
761 << A->getSpelling() << Value;
762 }
763 }
764}
765
767 const ArgList &Args,
768 ArgStringList &CmdArgs,
769 bool IsCC1As = false) {
770 // If no version was requested by the user, use the default value from the
771 // back end. This is consistent with the value returned from
772 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
773 // requiring the corresponding llvm to have the AMDGPU target enabled,
774 // provided the user (e.g. front end tests) can use the default.
776 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
777 CmdArgs.insert(CmdArgs.begin() + 1,
778 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
779 Twine(CodeObjVer)));
780 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
781 // -cc1as does not accept -mcode-object-version option.
782 if (!IsCC1As)
783 CmdArgs.insert(CmdArgs.begin() + 1,
784 Args.MakeArgString(Twine("-mcode-object-version=") +
785 Twine(CodeObjVer)));
786 }
787}
788
789static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
790 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
791 D.getVFS().getBufferForFile(Path);
792 if (!MemBuf)
793 return false;
794 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
795 if (Magic == llvm::file_magic::unknown)
796 return false;
797 // Return true for both raw Clang AST files and object files which may
798 // contain a __clangast section.
799 if (Magic == llvm::file_magic::clang_ast)
800 return true;
802 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
803 return !Obj.takeError();
804}
805
806static bool gchProbe(const Driver &D, StringRef Path) {
807 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
808 if (!Status)
809 return false;
810
811 if (Status->isDirectory()) {
812 std::error_code EC;
813 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
814 !EC && DI != DE; DI = DI.increment(EC)) {
815 if (maybeHasClangPchSignature(D, DI->path()))
816 return true;
817 }
818 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
819 return false;
820 }
821
822 if (maybeHasClangPchSignature(D, Path))
823 return true;
824 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
825 return false;
826}
827
828void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
829 const Driver &D, const ArgList &Args,
830 ArgStringList &CmdArgs,
831 const InputInfo &Output,
832 const InputInfoList &Inputs) const {
833 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
834
836
837 Args.AddLastArg(CmdArgs, options::OPT_C);
838 Args.AddLastArg(CmdArgs, options::OPT_CC);
839
840 // Handle dependency file generation.
841 Arg *ArgM = Args.getLastArg(options::OPT_MM);
842 if (!ArgM)
843 ArgM = Args.getLastArg(options::OPT_M);
844 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
845 if (!ArgMD)
846 ArgMD = Args.getLastArg(options::OPT_MD);
847
848 // -M and -MM imply -w.
849 if (ArgM)
850 CmdArgs.push_back("-w");
851 else
852 ArgM = ArgMD;
853
854 if (ArgM) {
856 // Determine the output location.
857 const char *DepFile;
858 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
859 DepFile = MF->getValue();
860 C.addFailureResultFile(DepFile, &JA);
861 } else if (Output.getType() == types::TY_Dependencies) {
862 DepFile = Output.getFilename();
863 } else if (!ArgMD) {
864 DepFile = "-";
865 } else {
866 DepFile = getDependencyFileName(Args, Inputs);
867 C.addFailureResultFile(DepFile, &JA);
868 }
869 CmdArgs.push_back("-dependency-file");
870 CmdArgs.push_back(DepFile);
871 }
872 // Cmake generates dependency files using all compilation options specified
873 // by users. Claim those not used for dependency files.
875 Args.ClaimAllArgs(options::OPT_offload_compress);
876 Args.ClaimAllArgs(options::OPT_no_offload_compress);
877 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
878 }
879
880 bool HasTarget = false;
881 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
882 HasTarget = true;
883 A->claim();
884 if (A->getOption().matches(options::OPT_MT)) {
885 A->render(Args, CmdArgs);
886 } else {
887 CmdArgs.push_back("-MT");
888 SmallString<128> Quoted;
889 quoteMakeTarget(A->getValue(), Quoted);
890 CmdArgs.push_back(Args.MakeArgString(Quoted));
891 }
892 }
893
894 // Add a default target if one wasn't specified.
895 if (!HasTarget) {
896 const char *DepTarget;
897
898 // If user provided -o, that is the dependency target, except
899 // when we are only generating a dependency file.
900 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
901 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
902 DepTarget = OutputOpt->getValue();
903 } else {
904 // Otherwise derive from the base input.
905 //
906 // FIXME: This should use the computed output file location.
907 SmallString<128> P(Inputs[0].getBaseInput());
908 llvm::sys::path::replace_extension(P, "o");
909 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
910 }
911
912 CmdArgs.push_back("-MT");
913 SmallString<128> Quoted;
914 quoteMakeTarget(DepTarget, Quoted);
915 CmdArgs.push_back(Args.MakeArgString(Quoted));
916 }
917
918 if (ArgM->getOption().matches(options::OPT_M) ||
919 ArgM->getOption().matches(options::OPT_MD))
920 CmdArgs.push_back("-sys-header-deps");
921
922 // Determine module file deps mode.
923 StringRef ModuleFileDepsVal;
924 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
925 options::OPT_fmodule_file_deps,
926 options::OPT_fno_module_file_deps)) {
927 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
928 ModuleFileDepsVal = A->getValue();
929 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
930 ModuleFileDepsVal = "all";
931 else
932 ModuleFileDepsVal = "none";
933 } else if (isa<PrecompileJobAction>(JA)) {
934 ModuleFileDepsVal = "all";
935 }
936 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
937 CmdArgs.push_back(
938 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
939 }
940
941 if (Args.hasArg(options::OPT_MG)) {
942 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
943 ArgM->getOption().matches(options::OPT_MMD))
944 D.Diag(diag::err_drv_mg_requires_m_or_mm);
945 CmdArgs.push_back("-MG");
946 }
947
948 Args.AddLastArg(CmdArgs, options::OPT_MP);
949 Args.AddLastArg(CmdArgs, options::OPT_MV);
950
951 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
952 // before we -I or -include anything else, because we must pick up the
953 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
954 // rather than from e.g. /usr/local/include.
956 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
958 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
960 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
961
962 // If we are offloading to a target via OpenMP we need to include the
963 // openmp_wrappers folder which contains alternative system headers.
965 !Args.hasArg(options::OPT_nostdinc) &&
966 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
967 true) &&
968 getToolChain().getTriple().isGPU()) {
969 if (!Args.hasArg(options::OPT_nobuiltininc)) {
970 // Add openmp_wrappers/* to our system include path. This lets us wrap
971 // standard library headers.
972 SmallString<128> P(D.ResourceDir);
973 llvm::sys::path::append(P, "include");
974 llvm::sys::path::append(P, "openmp_wrappers");
975 CmdArgs.push_back("-internal-isystem");
976 CmdArgs.push_back(Args.MakeArgString(P));
977 }
978
979 CmdArgs.push_back("-include");
980 CmdArgs.push_back("__clang_openmp_device_functions.h");
981 }
982
983 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
984 // Add llvm_wrappers/* to our system include path. This lets us wrap
985 // standard library headers and other headers.
986 SmallString<128> P(D.ResourceDir);
987 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
988 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
990 CmdArgs.push_back("__llvm_offload_device.h");
991 else
992 CmdArgs.push_back("__llvm_offload_host.h");
993 }
994
995 // Add -i* options, and automatically translate to
996 // -include-pch/-include-pth for transparent PCH support. It's
997 // wonky, but we include looking for .gch so we can support seamless
998 // replacement into a build system already set up to be generating
999 // .gch files.
1000
1001 if (getToolChain().getDriver().IsCLMode()) {
1002 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1003 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1004 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1006 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1007 // -fpch-instantiate-templates is the default when creating
1008 // precomp using /Yc
1009 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1010 options::OPT_fno_pch_instantiate_templates, true))
1011 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1012 }
1013 if (YcArg || YuArg) {
1014 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1015 if (!isa<PrecompileJobAction>(JA)) {
1016 CmdArgs.push_back("-include-pch");
1017 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1018 C, !ThroughHeader.empty()
1019 ? ThroughHeader
1020 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1021 }
1022
1023 if (ThroughHeader.empty()) {
1024 CmdArgs.push_back(Args.MakeArgString(
1025 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1026 } else {
1027 CmdArgs.push_back(
1028 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1029 }
1030 }
1031 }
1032
1033 bool RenderedImplicitInclude = false;
1034 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1035 if (A->getOption().matches(options::OPT_include) &&
1036 D.getProbePrecompiled()) {
1037 // Handling of gcc-style gch precompiled headers.
1038 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1039 RenderedImplicitInclude = true;
1040
1041 bool FoundPCH = false;
1042 SmallString<128> P(A->getValue());
1043 // We want the files to have a name like foo.h.pch. Add a dummy extension
1044 // so that replace_extension does the right thing.
1045 P += ".dummy";
1046 llvm::sys::path::replace_extension(P, "pch");
1047 if (D.getVFS().exists(P))
1048 FoundPCH = true;
1049
1050 if (!FoundPCH) {
1051 // For GCC compat, probe for a file or directory ending in .gch instead.
1052 llvm::sys::path::replace_extension(P, "gch");
1053 FoundPCH = gchProbe(D, P.str());
1054 }
1055
1056 if (FoundPCH) {
1057 if (IsFirstImplicitInclude) {
1058 A->claim();
1059 CmdArgs.push_back("-include-pch");
1060 CmdArgs.push_back(Args.MakeArgString(P));
1061 continue;
1062 } else {
1063 // Ignore the PCH if not first on command line and emit warning.
1064 D.Diag(diag::warn_drv_pch_not_first_include) << P
1065 << A->getAsString(Args);
1066 }
1067 }
1068 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1069 // Handling of paths which must come late. These entries are handled by
1070 // the toolchain itself after the resource dir is inserted in the right
1071 // search order.
1072 // Do not claim the argument so that the use of the argument does not
1073 // silently go unnoticed on toolchains which do not honour the option.
1074 continue;
1075 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1076 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1077 continue;
1078 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1079 // This is used only by the driver. No need to pass to cc1.
1080 continue;
1081 }
1082
1083 // Not translated, render as usual.
1084 A->claim();
1085 A->render(Args, CmdArgs);
1086 }
1087
1088 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1090 // Collect all enabled NVPTX architectures.
1091 std::set<unsigned> ArchIDs;
1092 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1093 const ToolChain *TC = I.second;
1094 for (BoundArch Arch :
1095 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1096 if (IsNVIDIAOffloadArch(Arch.Arch))
1097 ArchIDs.insert(CudaArchToID(Arch.Arch));
1098 }
1099 }
1100
1101 if (!ArchIDs.empty()) {
1102 SmallString<128> List;
1103 llvm::raw_svector_ostream OS(List);
1104 llvm::interleave(ArchIDs, OS, ",");
1105 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1106 }
1107 }
1108
1109 Args.addAllArgs(CmdArgs,
1110 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1111 options::OPT_F, options::OPT_embed_dir_EQ});
1112
1113 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1114
1115 // FIXME: There is a very unfortunate problem here, some troubled
1116 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1117 // really support that we would have to parse and then translate
1118 // those options. :(
1119 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1120 options::OPT_Xpreprocessor);
1121
1122 // -I- is a deprecated GCC feature, reject it.
1123 if (Arg *A = Args.getLastArg(options::OPT_I_))
1124 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1125
1126 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1127 // -isysroot to the CC1 invocation.
1128 StringRef sysroot = C.getSysRoot();
1129 if (sysroot != "") {
1130 if (!Args.hasArg(options::OPT_isysroot)) {
1131 CmdArgs.push_back("-isysroot");
1132 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1133 }
1134 }
1135
1136 // Parse additional include paths from environment variables.
1137 // FIXME: We should probably sink the logic for handling these from the
1138 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1139 // CPATH - included following the user specified includes (but prior to
1140 // builtin and standard includes).
1141 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1142 // C_INCLUDE_PATH - system includes enabled when compiling C.
1143 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1144 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1145 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1146 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1147 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1148 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1149 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1150
1151 // While adding the include arguments, we also attempt to retrieve the
1152 // arguments of related offloading toolchains or arguments that are specific
1153 // of an offloading programming model.
1154
1155 // Add C++ include arguments, if needed.
1156 if (types::isCXX(Inputs[0].getType())) {
1157 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1159 C, JA, getToolChain(),
1160 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1161 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1162 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1163 });
1164 }
1165
1166 // If we are compiling for a GPU target we want to override the system headers
1167 // with ones created by the 'libc' project if present.
1168 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1169 // OffloadKind as an argument.
1170 if (!Args.hasArg(options::OPT_nostdinc) &&
1171 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1172 true) &&
1173 !Args.hasArg(options::OPT_nobuiltininc) &&
1174 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1175 // TODO: CUDA / HIP include their own headers for some common functions
1176 // implemented here. We'll need to clean those up so they do not conflict.
1177 SmallString<128> P(D.ResourceDir);
1178 llvm::sys::path::append(P, "include");
1179 llvm::sys::path::append(P, "llvm_libc_wrappers");
1180 CmdArgs.push_back("-internal-isystem");
1181 CmdArgs.push_back(Args.MakeArgString(P));
1182 }
1183
1184 // Add system include arguments for all targets but IAMCU.
1185 if (!IsIAMCU)
1187 [&Args, &CmdArgs](const ToolChain &TC) {
1188 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1189 });
1190 else {
1191 // For IAMCU add special include arguments.
1192 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1193 }
1194
1195 addMacroPrefixMapArg(D, Args, CmdArgs);
1196 addCoveragePrefixMapArg(D, Args, CmdArgs);
1197
1198 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1199 options::OPT_fno_file_reproducible);
1200
1201 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1202 CmdArgs.push_back("-source-date-epoch");
1203 CmdArgs.push_back(Args.MakeArgString(Epoch));
1204 }
1205
1206 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1207 options::OPT_fno_define_target_os_macros);
1208}
1209
1210// FIXME: Move to target hook.
1211static bool isSignedCharDefault(const llvm::Triple &Triple) {
1212 switch (Triple.getArch()) {
1213 default:
1214 return true;
1215
1216 case llvm::Triple::aarch64:
1217 case llvm::Triple::aarch64_32:
1218 case llvm::Triple::aarch64_be:
1219 case llvm::Triple::arm:
1220 case llvm::Triple::armeb:
1221 case llvm::Triple::thumb:
1222 case llvm::Triple::thumbeb:
1223 if (Triple.isOSDarwin() || Triple.isOSWindows())
1224 return true;
1225 return false;
1226
1227 case llvm::Triple::ppc:
1228 case llvm::Triple::ppc64:
1229 if (Triple.isOSDarwin())
1230 return true;
1231 return false;
1232
1233 case llvm::Triple::csky:
1234 case llvm::Triple::hexagon:
1235 case llvm::Triple::msp430:
1236 case llvm::Triple::ppcle:
1237 case llvm::Triple::ppc64le:
1238 case llvm::Triple::riscv32:
1239 case llvm::Triple::riscv64:
1240 case llvm::Triple::riscv32be:
1241 case llvm::Triple::riscv64be:
1242 case llvm::Triple::systemz:
1243 case llvm::Triple::xcore:
1244 case llvm::Triple::xtensa:
1245 return false;
1246 }
1247}
1248
1249static bool hasMultipleInvocations(const llvm::Triple &Triple,
1250 const ArgList &Args) {
1251 // Supported only on Darwin where we invoke the compiler multiple times
1252 // followed by an invocation to lipo.
1253 if (!Triple.isOSDarwin())
1254 return false;
1255 // If more than one "-arch <arch>" is specified, we're targeting multiple
1256 // architectures resulting in a fat binary.
1257 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1258}
1259
1260static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1261 const llvm::Triple &Triple) {
1262 // When enabling remarks, we need to error if:
1263 // * The remark file is specified but we're targeting multiple architectures,
1264 // which means more than one remark file is being generated.
1266 bool hasExplicitOutputFile =
1267 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1268 if (hasMultipleInvocations && hasExplicitOutputFile) {
1269 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1270 << "-foptimization-record-file";
1271 return false;
1272 }
1273 return true;
1274}
1275
1276static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1277 const llvm::Triple &Triple,
1278 const InputInfo &Input,
1279 const InputInfo &Output, const JobAction &JA) {
1280 StringRef Format = "yaml";
1281 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1282 Format = A->getValue();
1283
1284 CmdArgs.push_back("-opt-record-file");
1285
1286 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1287 if (A) {
1288 CmdArgs.push_back(A->getValue());
1289 } else {
1290 bool hasMultipleArchs =
1291 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1292 Args.getAllArgValues(options::OPT_arch).size() > 1;
1293
1295
1296 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1297 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1298 F = FinalOutput->getValue();
1299 } else {
1300 if (Format != "yaml" && // For YAML, keep the original behavior.
1301 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1302 Output.isFilename())
1303 F = Output.getFilename();
1304 }
1305
1306 if (F.empty()) {
1307 // Use the input filename.
1308 F = llvm::sys::path::stem(Input.getBaseInput());
1309
1310 // If we're compiling for an offload architecture (i.e. a CUDA device),
1311 // we need to make the file name for the device compilation different
1312 // from the host compilation.
1315 llvm::sys::path::replace_extension(F, "");
1317 Triple.str());
1318 F += "-";
1319 F += JA.getOffloadingArch().ArchName;
1320 }
1321 }
1322
1323 // If we're having more than one "-arch", we should name the files
1324 // differently so that every cc1 invocation writes to a different file.
1325 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1326 // name from the triple.
1327 if (hasMultipleArchs) {
1328 // First, remember the extension.
1329 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1330 // then, remove it.
1331 llvm::sys::path::replace_extension(F, "");
1332 // attach -<arch> to it.
1333 F += "-";
1334 F += Triple.getArchName();
1335 // put back the extension.
1336 llvm::sys::path::replace_extension(F, OldExtension);
1337 }
1338
1339 SmallString<32> Extension;
1340 Extension += "opt.";
1341 Extension += Format;
1342
1343 llvm::sys::path::replace_extension(F, Extension);
1344 CmdArgs.push_back(Args.MakeArgString(F));
1345 }
1346
1347 if (const Arg *A =
1348 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1349 CmdArgs.push_back("-opt-record-passes");
1350 CmdArgs.push_back(A->getValue());
1351 }
1352
1353 if (!Format.empty()) {
1354 CmdArgs.push_back("-opt-record-format");
1355 CmdArgs.push_back(Format.data());
1356 }
1357}
1358
1359void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1360 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1361 options::OPT_fno_aapcs_bitfield_width, true))
1362 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1363
1364 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1365 CmdArgs.push_back("-faapcs-bitfield-load");
1366}
1367
1368namespace {
1369void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1370 const ArgList &Args, ArgStringList &CmdArgs) {
1371 // Select the ABI to use.
1372 // FIXME: Support -meabi.
1373 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1374 const char *ABIName = nullptr;
1375 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1376 ABIName = A->getValue();
1377 else
1378 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1379
1380 CmdArgs.push_back("-target-abi");
1381 CmdArgs.push_back(ABIName);
1382}
1383
1384void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1385 auto StrictAlignIter =
1386 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1387 return Arg == "+strict-align" || Arg == "-strict-align";
1388 });
1389 if (StrictAlignIter != CmdArgs.rend() &&
1390 StringRef(*StrictAlignIter) == "+strict-align")
1391 CmdArgs.push_back("-Wunaligned-access");
1392}
1393}
1394
1395static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1396 ArgStringList &CmdArgs, bool isAArch64) {
1397 const llvm::Triple &Triple = TC.getEffectiveTriple();
1398 const Arg *A = isAArch64
1399 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1400 options::OPT_mbranch_protection_EQ)
1401 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1402 if (!A) {
1403 if (Triple.isOSOpenBSD() && isAArch64) {
1404 CmdArgs.push_back("-msign-return-address=non-leaf");
1405 CmdArgs.push_back("-msign-return-address-key=a_key");
1406 CmdArgs.push_back("-mbranch-target-enforce");
1407 }
1408 return;
1409 }
1410
1411 const Driver &D = TC.getDriver();
1412 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1413 D.Diag(diag::warn_incompatible_branch_protection_option)
1414 << Triple.getArchName();
1415
1416 StringRef Scope, Key;
1417 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1418
1419 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1420 Scope = A->getValue();
1421 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1422 D.Diag(diag::err_drv_unsupported_option_argument)
1423 << A->getSpelling() << Scope;
1424 Key = "a_key";
1425 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1426 BranchProtectionPAuthLR = false;
1427 GuardedControlStack = false;
1428 } else {
1429 StringRef DiagMsg;
1430 llvm::ARM::ParsedBranchProtection PBP;
1431 bool EnablePAuthLR = false;
1432
1433 // To know if we need to enable PAuth-LR As part of the standard branch
1434 // protection option, it needs to be determined if the feature has been
1435 // activated in the `march` argument. This information is stored within the
1436 // CmdArgs variable and can be found using a search.
1437 if (isAArch64) {
1438 auto isPAuthLR = [](const char *member) {
1439 llvm::AArch64::ExtensionInfo pauthlr_extension =
1440 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1441 return pauthlr_extension.PosTargetFeature == member;
1442 };
1443
1444 if (llvm::any_of(CmdArgs, isPAuthLR))
1445 EnablePAuthLR = true;
1446 }
1447 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1448 EnablePAuthLR))
1449 D.Diag(diag::err_drv_unsupported_option_argument)
1450 << A->getSpelling() << DiagMsg;
1451 if (!isAArch64 && PBP.Key == "b_key")
1452 D.Diag(diag::warn_unsupported_branch_protection)
1453 << "b-key" << A->getAsString(Args);
1454 Scope = PBP.Scope;
1455 Key = PBP.Key;
1456 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1457 IndirectBranches = PBP.BranchTargetEnforcement;
1458 GuardedControlStack = PBP.GuardedControlStack;
1459 }
1460
1461 Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,
1462 options::OPT_fno_ptrauth_returns);
1463 bool HasPtrauthReturns =
1464 PtrauthReturnsArg &&
1465 PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);
1466 // GCS is currently untested with ptrauth-returns, but enabling this could be
1467 // allowed in future after testing with a suitable system.
1468 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1469 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1470 D.Diag(diag::err_drv_unsupported_opt_for_target)
1471 << A->getAsString(Args) << Triple.getTriple();
1472 else if (HasPtrauthReturns)
1473 D.Diag(diag::err_drv_incompatible_options)
1474 << A->getAsString(Args) << "-fptrauth-returns";
1475 }
1476
1477 CmdArgs.push_back(
1478 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1479 if (Scope != "none")
1480 CmdArgs.push_back(
1481 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1482 if (BranchProtectionPAuthLR)
1483 CmdArgs.push_back(
1484 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1485 if (IndirectBranches)
1486 CmdArgs.push_back("-mbranch-target-enforce");
1487
1488 if (GuardedControlStack)
1489 CmdArgs.push_back("-mguarded-control-stack");
1490}
1491
1492void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1493 ArgStringList &CmdArgs, bool KernelOrKext) const {
1494 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1495
1496 // Determine floating point ABI from the options & target defaults.
1498 if (ABI == arm::FloatABI::Soft) {
1499 // Floating point operations and argument passing are soft.
1500 // FIXME: This changes CPP defines, we need -target-soft-float.
1501 CmdArgs.push_back("-msoft-float");
1502 CmdArgs.push_back("-mfloat-abi");
1503 CmdArgs.push_back("soft");
1504 } else if (ABI == arm::FloatABI::SoftFP) {
1505 // Floating point operations are hard, but argument passing is soft.
1506 CmdArgs.push_back("-mfloat-abi");
1507 CmdArgs.push_back("soft");
1508 } else {
1509 // Floating point operations and argument passing are hard.
1510 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1511 CmdArgs.push_back("-mfloat-abi");
1512 CmdArgs.push_back("hard");
1513 }
1514
1515 // Forward the -mglobal-merge option for explicit control over the pass.
1516 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1517 options::OPT_mno_global_merge)) {
1518 CmdArgs.push_back("-mllvm");
1519 if (A->getOption().matches(options::OPT_mno_global_merge))
1520 CmdArgs.push_back("-arm-global-merge=false");
1521 else
1522 CmdArgs.push_back("-arm-global-merge=true");
1523 }
1524
1525 if (!Args.hasFlag(options::OPT_mimplicit_float,
1526 options::OPT_mno_implicit_float, true))
1527 CmdArgs.push_back("-no-implicit-float");
1528
1529 if (Args.getLastArg(options::OPT_mcmse))
1530 CmdArgs.push_back("-mcmse");
1531
1532 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1533
1534 // Enable/disable return address signing and indirect branch targets.
1535 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1536
1537 AddUnalignedAccessWarning(CmdArgs);
1538}
1539
1540void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1541 const ArgList &Args, bool KernelOrKext,
1542 ArgStringList &CmdArgs) const {
1543 const ToolChain &TC = getToolChain();
1544
1545 // Add the target features
1546 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1547
1548 // Add target specific flags.
1549 switch (TC.getArch()) {
1550 default:
1551 break;
1552
1553 case llvm::Triple::arm:
1554 case llvm::Triple::armeb:
1555 case llvm::Triple::thumb:
1556 case llvm::Triple::thumbeb:
1557 // Use the effective triple, which takes into account the deployment target.
1558 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1559 break;
1560
1561 case llvm::Triple::aarch64:
1562 case llvm::Triple::aarch64_32:
1563 case llvm::Triple::aarch64_be:
1564 AddAArch64TargetArgs(Args, CmdArgs);
1565 break;
1566
1567 case llvm::Triple::loongarch32:
1568 case llvm::Triple::loongarch64:
1569 AddLoongArchTargetArgs(Args, CmdArgs);
1570 break;
1571
1572 case llvm::Triple::mips:
1573 case llvm::Triple::mipsel:
1574 case llvm::Triple::mips64:
1575 case llvm::Triple::mips64el:
1576 AddMIPSTargetArgs(Args, CmdArgs);
1577 break;
1578
1579 case llvm::Triple::ppc:
1580 case llvm::Triple::ppcle:
1581 case llvm::Triple::ppc64:
1582 case llvm::Triple::ppc64le:
1583 AddPPCTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::riscv32:
1587 case llvm::Triple::riscv64:
1588 case llvm::Triple::riscv32be:
1589 case llvm::Triple::riscv64be:
1590 AddRISCVTargetArgs(Args, CmdArgs);
1591 break;
1592
1593 case llvm::Triple::sparc:
1594 case llvm::Triple::sparcel:
1595 case llvm::Triple::sparcv9:
1596 AddSparcTargetArgs(Args, CmdArgs);
1597 break;
1598
1599 case llvm::Triple::systemz:
1600 AddSystemZTargetArgs(Args, CmdArgs);
1601 break;
1602
1603 case llvm::Triple::x86:
1604 case llvm::Triple::x86_64:
1605 AddX86TargetArgs(Args, CmdArgs);
1606 break;
1607
1608 case llvm::Triple::lanai:
1609 AddLanaiTargetArgs(Args, CmdArgs);
1610 break;
1611
1612 case llvm::Triple::hexagon:
1613 AddHexagonTargetArgs(Args, CmdArgs);
1614 break;
1615
1616 case llvm::Triple::wasm32:
1617 case llvm::Triple::wasm64:
1618 AddWebAssemblyTargetArgs(Args, CmdArgs);
1619 break;
1620
1621 case llvm::Triple::ve:
1622 AddVETargetArgs(Args, CmdArgs);
1623 break;
1624 }
1625}
1626
1627namespace {
1628void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1629 ArgStringList &CmdArgs) {
1630 const char *ABIName = nullptr;
1631 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1632 ABIName = A->getValue();
1633 else if (Triple.isOSDarwin())
1634 ABIName = "darwinpcs";
1635 // TODO: we probably want to have some target hook here.
1636 else if (Triple.isOSLinux() &&
1637 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1638 ABIName = "pauthtest";
1639 else
1640 ABIName = "aapcs";
1641
1642 CmdArgs.push_back("-target-abi");
1643 CmdArgs.push_back(ABIName);
1644}
1645}
1646
1647void Clang::AddAArch64TargetArgs(const ArgList &Args,
1648 ArgStringList &CmdArgs) const {
1649 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1650
1651 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1652 Args.hasArg(options::OPT_mkernel) ||
1653 Args.hasArg(options::OPT_fapple_kext))
1654 CmdArgs.push_back("-disable-red-zone");
1655
1656 if (!Args.hasFlag(options::OPT_mimplicit_float,
1657 options::OPT_mno_implicit_float, true))
1658 CmdArgs.push_back("-no-implicit-float");
1659
1660 RenderAArch64ABI(Triple, Args, CmdArgs);
1661
1662 // Forward the -mglobal-merge option for explicit control over the pass.
1663 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1664 options::OPT_mno_global_merge)) {
1665 CmdArgs.push_back("-mllvm");
1666 if (A->getOption().matches(options::OPT_mno_global_merge))
1667 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1668 else
1669 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1670 }
1671
1672 // Handle -msve_vector_bits=<bits>
1673 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1674 StringRef VScaleMax) {
1675 StringRef Val = A->getValue();
1676 const Driver &D = getToolChain().getDriver();
1677 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1678 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1679 Val == "1024+" || Val == "2048+") {
1680 unsigned Bits = 0;
1681 if (!Val.consume_back("+")) {
1682 bool Invalid = Val.getAsInteger(10, Bits);
1683 (void)Invalid;
1684 assert(!Invalid && "Failed to parse value");
1685 CmdArgs.push_back(
1686 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1687 }
1688
1689 bool Invalid = Val.getAsInteger(10, Bits);
1690 (void)Invalid;
1691 assert(!Invalid && "Failed to parse value");
1692
1693 CmdArgs.push_back(
1694 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1695 } else if (Val == "scalable") {
1696 // Silently drop requests for vector-length agnostic code as it's implied.
1697 } else {
1698 // Handle the unsupported values passed to msve-vector-bits.
1699 D.Diag(diag::err_drv_unsupported_option_argument)
1700 << A->getSpelling() << Val;
1701 }
1702 };
1703 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1704 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1705 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1706 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1707
1708 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1709
1710 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1711 CmdArgs.push_back("-tune-cpu");
1712 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1713 }
1714
1715 AddUnalignedAccessWarning(CmdArgs);
1716
1717 if (Triple.isOSDarwin() ||
1718 (Triple.isOSLinux() &&
1719 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1720 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1721 options::OPT_fno_ptrauth_intrinsics);
1722 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1723 options::OPT_fno_ptrauth_calls);
1724 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1725 options::OPT_fno_ptrauth_returns);
1726 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1727 options::OPT_fno_ptrauth_auth_traps);
1728 Args.addOptInFlag(
1729 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1730 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1731 Args.addOptInFlag(
1732 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1733 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1734 Args.addOptInFlag(
1735 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1736 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1737 Args.addOptInFlag(
1738 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1739 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1740 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1741 options::OPT_fno_ptrauth_indirect_gotos);
1742 }
1743 if (Triple.isOSLinux() &&
1744 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1745 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1746 options::OPT_fno_ptrauth_init_fini);
1747 Args.addOptInFlag(
1748 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1749 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1750 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1751 options::OPT_fno_ptrauth_elf_got);
1752 }
1753 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1754 options::OPT_fno_aarch64_jump_table_hardening);
1755
1756 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1757 options::OPT_fno_ptrauth_objc_isa);
1758 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1759 options::OPT_fno_ptrauth_objc_interface_sel);
1760 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1761 options::OPT_fno_ptrauth_objc_class_ro);
1762
1763 // Enable/disable return address signing and indirect branch targets.
1764 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1765}
1766
1767void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1768 ArgStringList &CmdArgs) const {
1769 const llvm::Triple &Triple = getToolChain().getTriple();
1770
1771 CmdArgs.push_back("-target-abi");
1772 CmdArgs.push_back(
1773 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1774 .data());
1775
1776 // Handle -mtune.
1777 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1778 std::string TuneCPU = A->getValue();
1779 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1780 CmdArgs.push_back("-tune-cpu");
1781 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1782 }
1783
1784 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1785 options::OPT_mno_annotate_tablejump)) {
1786 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1787 CmdArgs.push_back("-mllvm");
1788 CmdArgs.push_back("-loongarch-annotate-tablejump");
1789 }
1790 }
1791}
1792
1793void Clang::AddMIPSTargetArgs(const ArgList &Args,
1794 ArgStringList &CmdArgs) const {
1795 const Driver &D = getToolChain().getDriver();
1796 StringRef CPUName;
1797 StringRef ABIName;
1798 const llvm::Triple &Triple = getToolChain().getTriple();
1799 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1800
1801 CmdArgs.push_back("-target-abi");
1802 CmdArgs.push_back(ABIName.data());
1803
1804 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1805 if (ABI == mips::FloatABI::Soft) {
1806 // Floating point operations and argument passing are soft.
1807 CmdArgs.push_back("-msoft-float");
1808 CmdArgs.push_back("-mfloat-abi");
1809 CmdArgs.push_back("soft");
1810 } else {
1811 // Floating point operations and argument passing are hard.
1812 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1813 CmdArgs.push_back("-mfloat-abi");
1814 CmdArgs.push_back("hard");
1815 }
1816
1817 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1818 options::OPT_mno_ldc1_sdc1)) {
1819 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1820 CmdArgs.push_back("-mllvm");
1821 CmdArgs.push_back("-mno-ldc1-sdc1");
1822 }
1823 }
1824
1825 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1826 options::OPT_mno_check_zero_division)) {
1827 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1828 CmdArgs.push_back("-mllvm");
1829 CmdArgs.push_back("-mno-check-zero-division");
1830 }
1831 }
1832
1833 if (Args.getLastArg(options::OPT_mfix4300)) {
1834 CmdArgs.push_back("-mllvm");
1835 CmdArgs.push_back("-mfix4300");
1836 }
1837
1838 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1839 StringRef v = A->getValue();
1840 CmdArgs.push_back("-mllvm");
1841 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1842 A->claim();
1843 }
1844
1845 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1846 Arg *ABICalls =
1847 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1848
1849 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1850 // -mgpopt is the default for static, -fno-pic environments but these two
1851 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1852 // the only case where -mllvm -mgpopt is passed.
1853 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1854 // passed explicitly when compiling something with -mabicalls
1855 // (implictly) in affect. Currently the warning is in the backend.
1856 //
1857 // When the ABI in use is N64, we also need to determine the PIC mode that
1858 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1859 bool NoABICalls =
1860 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1861
1862 llvm::Reloc::Model RelocationModel;
1863 unsigned PICLevel;
1864 bool IsPIE;
1865 std::tie(RelocationModel, PICLevel, IsPIE) =
1866 ParsePICArgs(getToolChain(), Args);
1867
1868 NoABICalls = NoABICalls ||
1869 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1870
1871 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1872 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1873 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1874 CmdArgs.push_back("-mllvm");
1875 CmdArgs.push_back("-mgpopt");
1876
1877 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1878 options::OPT_mno_local_sdata);
1879 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1880 options::OPT_mno_extern_sdata);
1881 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1882 options::OPT_mno_embedded_data);
1883 if (LocalSData) {
1884 CmdArgs.push_back("-mllvm");
1885 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1886 CmdArgs.push_back("-mlocal-sdata=1");
1887 } else {
1888 CmdArgs.push_back("-mlocal-sdata=0");
1889 }
1890 LocalSData->claim();
1891 }
1892
1893 if (ExternSData) {
1894 CmdArgs.push_back("-mllvm");
1895 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1896 CmdArgs.push_back("-mextern-sdata=1");
1897 } else {
1898 CmdArgs.push_back("-mextern-sdata=0");
1899 }
1900 ExternSData->claim();
1901 }
1902
1903 if (EmbeddedData) {
1904 CmdArgs.push_back("-mllvm");
1905 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1906 CmdArgs.push_back("-membedded-data=1");
1907 } else {
1908 CmdArgs.push_back("-membedded-data=0");
1909 }
1910 EmbeddedData->claim();
1911 }
1912
1913 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1914 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1915
1916 if (GPOpt)
1917 GPOpt->claim();
1918
1919 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1920 StringRef Val = StringRef(A->getValue());
1921 if (mips::hasCompactBranches(CPUName)) {
1922 if (Val == "never" || Val == "always" || Val == "optimal") {
1923 CmdArgs.push_back("-mllvm");
1924 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1925 } else
1926 D.Diag(diag::err_drv_unsupported_option_argument)
1927 << A->getSpelling() << Val;
1928 } else
1929 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1930 }
1931
1932 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1933 options::OPT_mno_relax_pic_calls)) {
1934 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1935 CmdArgs.push_back("-mllvm");
1936 CmdArgs.push_back("-mips-jalr-reloc=0");
1937 }
1938 }
1939}
1940
1941void Clang::AddPPCTargetArgs(const ArgList &Args,
1942 ArgStringList &CmdArgs) const {
1943 const Driver &D = getToolChain().getDriver();
1944 const llvm::Triple &T = getToolChain().getTriple();
1945 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1946 CmdArgs.push_back("-tune-cpu");
1947 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1948 CmdArgs.push_back(Args.MakeArgString(CPU));
1949 }
1950
1951 // Select the ABI to use.
1952 const char *ABIName = nullptr;
1953 if (T.isOSBinFormatELF()) {
1954 switch (getToolChain().getArch()) {
1955 case llvm::Triple::ppc64: {
1956 if (T.isPPC64ELFv2ABI())
1957 ABIName = "elfv2";
1958 else
1959 ABIName = "elfv1";
1960 break;
1961 }
1962 case llvm::Triple::ppc64le:
1963 ABIName = "elfv2";
1964 break;
1965 default:
1966 break;
1967 }
1968 }
1969
1970 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1971 bool VecExtabi = false;
1972 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1973 StringRef V = A->getValue();
1974 if (V == "ieeelongdouble") {
1975 IEEELongDouble = true;
1976 A->claim();
1977 } else if (V == "ibmlongdouble") {
1978 IEEELongDouble = false;
1979 A->claim();
1980 } else if (V == "vec-default") {
1981 VecExtabi = false;
1982 A->claim();
1983 } else if (V == "vec-extabi") {
1984 VecExtabi = true;
1985 A->claim();
1986 } else if (V == "elfv1") {
1987 ABIName = "elfv1";
1988 A->claim();
1989 } else if (V == "elfv2") {
1990 ABIName = "elfv2";
1991 A->claim();
1992 } else if (V != "altivec")
1993 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1994 // the option if given as we don't have backend support for any targets
1995 // that don't use the altivec abi.
1996 ABIName = A->getValue();
1997 }
1998 if (IEEELongDouble)
1999 CmdArgs.push_back("-mabi=ieeelongdouble");
2000 if (VecExtabi) {
2001 if (!T.isOSAIX())
2002 D.Diag(diag::err_drv_unsupported_opt_for_target)
2003 << "-mabi=vec-extabi" << T.str();
2004 CmdArgs.push_back("-mabi=vec-extabi");
2005 }
2006
2007 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2008 CmdArgs.push_back("-disable-red-zone");
2009
2011 if (FloatABI == ppc::FloatABI::Soft) {
2012 // Floating point operations and argument passing are soft.
2013 CmdArgs.push_back("-msoft-float");
2014 CmdArgs.push_back("-mfloat-abi");
2015 CmdArgs.push_back("soft");
2016 } else {
2017 // Floating point operations and argument passing are hard.
2018 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2019 CmdArgs.push_back("-mfloat-abi");
2020 CmdArgs.push_back("hard");
2021 }
2022
2023 if (ABIName) {
2024 CmdArgs.push_back("-target-abi");
2025 CmdArgs.push_back(ABIName);
2026 }
2027}
2028
2029void Clang::AddRISCVTargetArgs(const ArgList &Args,
2030 ArgStringList &CmdArgs) const {
2031 const llvm::Triple &Triple = getToolChain().getTriple();
2032 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2033
2034 CmdArgs.push_back("-target-abi");
2035 CmdArgs.push_back(ABIName.data());
2036
2037 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2038 CmdArgs.push_back("-msmall-data-limit");
2039 CmdArgs.push_back(A->getValue());
2040 }
2041
2042 if (!Args.hasFlag(options::OPT_mimplicit_float,
2043 options::OPT_mno_implicit_float, true))
2044 CmdArgs.push_back("-no-implicit-float");
2045
2046 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2047 if (!TuneCPU)
2048 return;
2049 if (!TuneCPU->empty()) {
2050 CmdArgs.push_back("-tune-cpu");
2051 if (*TuneCPU == "native")
2052 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2053 else
2054 // TuneCPU might or might not be the original -mtune string, so we
2055 // have to create a new copy here.
2056 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2057 }
2058
2059 // Handle -mrvv-vector-bits=<bits>
2060 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2061 StringRef Val = A->getValue();
2062 const Driver &D = getToolChain().getDriver();
2063
2064 // Get minimum VLen from march.
2065 unsigned MinVLen = 0;
2066 std::string Arch = riscv::getRISCVArch(Args, Triple);
2067 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2068 Arch, /*EnableExperimentalExtensions*/ true);
2069 // Ignore parsing error.
2070 if (!errorToBool(ISAInfo.takeError()))
2071 MinVLen = (*ISAInfo)->getMinVLen();
2072
2073 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2074 // as integer as long as we have a MinVLen.
2075 unsigned Bits = 0;
2076 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2077 Bits = MinVLen;
2078 } else if (!Val.getAsInteger(10, Bits)) {
2079 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2080 // at least MinVLen.
2081 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2082 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2083 Bits = 0;
2084 }
2085
2086 // If we got a valid value try to use it.
2087 if (Bits != 0) {
2088 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2089 CmdArgs.push_back(
2090 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2091 CmdArgs.push_back(
2092 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2093 } else if (Val != "scalable") {
2094 // Handle the unsupported values passed to mrvv-vector-bits.
2095 D.Diag(diag::err_drv_unsupported_option_argument)
2096 << A->getSpelling() << Val;
2097 }
2098 }
2099}
2100
2101void Clang::AddSparcTargetArgs(const ArgList &Args,
2102 ArgStringList &CmdArgs) const {
2104 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2105
2106 if (FloatABI == sparc::FloatABI::Soft) {
2107 // Floating point operations and argument passing are soft.
2108 CmdArgs.push_back("-msoft-float");
2109 CmdArgs.push_back("-mfloat-abi");
2110 CmdArgs.push_back("soft");
2111 } else {
2112 // Floating point operations and argument passing are hard.
2113 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2114 CmdArgs.push_back("-mfloat-abi");
2115 CmdArgs.push_back("hard");
2116 }
2117
2118 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2119 StringRef Name = A->getValue();
2120 std::string TuneCPU;
2121 if (Name == "native")
2122 TuneCPU = std::string(llvm::sys::getHostCPUName());
2123 else
2124 TuneCPU = std::string(Name);
2125
2126 CmdArgs.push_back("-tune-cpu");
2127 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2128 }
2129}
2130
2131void Clang::AddSystemZTargetArgs(const ArgList &Args,
2132 ArgStringList &CmdArgs) const {
2133 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2134 CmdArgs.push_back("-tune-cpu");
2135 if (strcmp(A->getValue(), "native") == 0)
2136 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2137 else
2138 CmdArgs.push_back(A->getValue());
2139 }
2140
2141 bool HasBackchain =
2142 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2143 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2144 options::OPT_mno_packed_stack, false);
2146 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2147 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2148
2149 // Only hard float ABI (-mhard-float) is supported on z/OS.
2150 const Driver &D = getToolChain().getDriver();
2151 const llvm::Triple &Triple = getToolChain().getTriple();
2152 if (HasSoftFloat && Triple.isOSzOS()) {
2153 D.Diag(diag::err_drv_unsupported_opt_for_target)
2154 << "-msoft-float" << Triple.str();
2155 }
2156 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2157 D.Diag(diag::err_drv_unsupported_opt)
2158 << "-mpacked-stack -mbackchain -mhard-float";
2159 }
2160 if (HasBackchain)
2161 CmdArgs.push_back("-mbackchain");
2162 if (HasPackedStack)
2163 CmdArgs.push_back("-mpacked-stack");
2164 if (HasSoftFloat) {
2165 // Floating point operations and argument passing are soft.
2166 CmdArgs.push_back("-msoft-float");
2167 CmdArgs.push_back("-mfloat-abi");
2168 CmdArgs.push_back("soft");
2169 }
2170}
2171
2172void Clang::AddX86TargetArgs(const ArgList &Args,
2173 ArgStringList &CmdArgs) const {
2174 const Driver &D = getToolChain().getDriver();
2175 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2176
2177 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2178 Args.hasArg(options::OPT_mkernel) ||
2179 Args.hasArg(options::OPT_fapple_kext))
2180 CmdArgs.push_back("-disable-red-zone");
2181
2182 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2183 options::OPT_mno_tls_direct_seg_refs, true))
2184 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2185
2186 // Default to avoid implicit floating-point for kernel/kext code, but allow
2187 // that to be overridden with -mno-soft-float.
2188 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2189 Args.hasArg(options::OPT_fapple_kext));
2190 if (Arg *A = Args.getLastArg(
2191 options::OPT_msoft_float, options::OPT_mno_soft_float,
2192 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2193 const Option &O = A->getOption();
2194 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2195 O.matches(options::OPT_msoft_float));
2196 }
2197 if (NoImplicitFloat)
2198 CmdArgs.push_back("-no-implicit-float");
2199
2200 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2201 StringRef Value = A->getValue();
2202 if (Value == "intel" || Value == "att") {
2203 CmdArgs.push_back("-mllvm");
2204 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2205 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2206 } else {
2207 D.Diag(diag::err_drv_unsupported_option_argument)
2208 << A->getSpelling() << Value;
2209 }
2210 } else if (D.IsCLMode()) {
2211 CmdArgs.push_back("-mllvm");
2212 CmdArgs.push_back("-x86-asm-syntax=intel");
2213 }
2214
2215 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2216 options::OPT_mno_skip_rax_setup))
2217 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2218 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2219
2220 // Set flags to support MCU ABI.
2221 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2222 CmdArgs.push_back("-mfloat-abi");
2223 CmdArgs.push_back("soft");
2224 CmdArgs.push_back("-mstack-alignment=4");
2225 }
2226
2227 // Handle -mtune.
2228
2229 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2230 std::string TuneCPU;
2231 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2232 TuneCPU = "generic";
2233
2234 // Override based on -mtune.
2235 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2236 StringRef Name = A->getValue();
2237
2238 if (Name == "native") {
2239 Name = llvm::sys::getHostCPUName();
2240 if (!Name.empty())
2241 TuneCPU = std::string(Name);
2242 } else
2243 TuneCPU = std::string(Name);
2244 }
2245
2246 if (!TuneCPU.empty()) {
2247 CmdArgs.push_back("-tune-cpu");
2248 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2249 }
2250}
2251
2252static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2253 size_t Index = Option.find(Delimiter);
2254 if (Index != StringRef::npos)
2255 Option = Option.substr(0, Index);
2256 return Option;
2257}
2258
2259static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2260 Opt = getOptionName(Opt);
2261 if (CmdArgs.size() < 2)
2262 return;
2263
2264 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2265 StringRef Option = *It;
2266 if (!Option.starts_with(Opt))
2267 continue;
2268 Option = getOptionName(Option);
2269 if (Option != Opt)
2270 continue;
2271 if (StringRef(*(It - 1)) != "-mllvm")
2272 continue;
2273
2274 It = CmdArgs.erase(It);
2275 CmdArgs.erase(It - 1);
2276 return;
2277 }
2278}
2279
2280static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2281 checkAndRemoveLLVMArg(CmdArgs, A);
2282 CmdArgs.push_back("-mllvm");
2283 CmdArgs.push_back(A);
2284}
2285
2286static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2287 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2288 StringRef Option = *It;
2289 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2290 It = CmdArgs.erase(It);
2291 Ie = CmdArgs.end();
2292 } else {
2293 ++It;
2294 }
2295 }
2296
2297 CmdArgs.push_back("-menable-no-infs");
2298 CmdArgs.push_back("-menable-no-nans");
2299 CmdArgs.push_back("-fapprox-func");
2300 CmdArgs.push_back("-funsafe-math-optimizations");
2301 CmdArgs.push_back("-fno-signed-zeros");
2302 CmdArgs.push_back("-mreassociate");
2303 CmdArgs.push_back("-freciprocal-math");
2304 CmdArgs.push_back("-ffp-contract=fast");
2305 CmdArgs.push_back("-ffast-math");
2306 CmdArgs.push_back("-ffinite-math-only");
2307 CmdArgs.push_back("-D__FAST_MATH__");
2308 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2309}
2310
2311static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2312 ArgStringList &CmdArgs) {
2313 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2314 bool HasHVX = HvxVerOpt.has_value();
2315 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2316 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2317 options::OPT_mhexagon_hvx_ieee_fp) ||
2318 !HasHVX)
2319 return;
2320 unsigned HvxVerNum = 0;
2321 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2322 HvxVerNum = 0;
2323
2324 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2325 options::OPT_mhexagon_hvx_qfloat_EQ,
2326 options::OPT_mhexagon_hvx_ieee_fp)) {
2327 if (HvxVerNum >= 79) {
2328 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2329 const char *Mode =
2330 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2331 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2332 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2333 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2334 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2335 .Default(nullptr);
2336 if (!Mode) {
2337 D.Diag(diag::err_drv_invalid_value)
2338 << A->getAsString(Args) << A->getValue();
2339 return;
2340 }
2341 pushBackLLVMArg(CmdArgs, Mode);
2342 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2344 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2345 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2347 } else {
2348 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2349 }
2350 } else {
2351 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2352 options::OPT_mhexagon_hvx_qfloat_EQ,
2353 options::OPT_mno_hexagon_hvx_qfloat);
2354 QFloatArg &&
2355 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2356 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2357 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2358 << (std::string("HVX ") + HvxVer +
2359 "; falling back to legacy qfloat mode");
2360 }
2361 }
2362 }
2363}
2364
2365void Clang::AddHexagonTargetArgs(const ArgList &Args,
2366 ArgStringList &CmdArgs) const {
2367 CmdArgs.push_back("-mqdsp6-compat");
2368 CmdArgs.push_back("-Wreturn-type");
2369
2371 CmdArgs.push_back("-mllvm");
2372 CmdArgs.push_back(
2373 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2374 }
2375
2376 if (!Args.hasArg(options::OPT_fno_short_enums))
2377 CmdArgs.push_back("-fshort-enums");
2378 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2379 CmdArgs.push_back("-mllvm");
2380 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2381 }
2382 CmdArgs.push_back("-mllvm");
2383 CmdArgs.push_back("-machine-sink-split=0");
2384
2385 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2386}
2387
2388void Clang::AddLanaiTargetArgs(const ArgList &Args,
2389 ArgStringList &CmdArgs) const {
2390 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2391 StringRef CPUName = A->getValue();
2392
2393 CmdArgs.push_back("-target-cpu");
2394 CmdArgs.push_back(Args.MakeArgString(CPUName));
2395 }
2396 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2397 StringRef Value = A->getValue();
2398 // Only support mregparm=4 to support old usage. Report error for all other
2399 // cases.
2400 int Mregparm;
2401 if (Value.getAsInteger(10, Mregparm)) {
2402 if (Mregparm != 4) {
2404 diag::err_drv_unsupported_option_argument)
2405 << A->getSpelling() << Value;
2406 }
2407 }
2408 }
2409}
2410
2411void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2412 ArgStringList &CmdArgs) const {
2413 // Default to "hidden" visibility.
2414 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2415 options::OPT_fvisibility_ms_compat))
2416 CmdArgs.push_back("-fvisibility=hidden");
2417}
2418
2419void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2420 // Floating point operations and argument passing are hard.
2421 CmdArgs.push_back("-mfloat-abi");
2422 CmdArgs.push_back("hard");
2423}
2424
2425void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2426 StringRef Target, const InputInfo &Output,
2427 const InputInfo &Input, const ArgList &Args) const {
2428 // If this is a dry run, do not create the compilation database file.
2429 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2430 return;
2431
2432 using llvm::yaml::escape;
2433 const Driver &D = getToolChain().getDriver();
2434
2435 if (!CompilationDatabase) {
2436 std::error_code EC;
2437 auto File = std::make_unique<llvm::raw_fd_ostream>(
2438 Filename, EC,
2439 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2440 if (EC) {
2441 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2442 << EC.message();
2443 return;
2444 }
2445 CompilationDatabase = std::move(File);
2446 }
2447 auto &CDB = *CompilationDatabase;
2448 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2449 if (!CWD)
2450 CWD = ".";
2451 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2452 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2453 if (Output.isFilename())
2454 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2455 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2456 SmallString<128> Buf;
2457 Buf = "-x";
2458 Buf += types::getTypeName(Input.getType());
2459 CDB << ", \"" << escape(Buf) << "\"";
2460 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2461 Buf = "--sysroot=";
2462 Buf += D.SysRoot;
2463 CDB << ", \"" << escape(Buf) << "\"";
2464 }
2465 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2466 if (Output.isFilename())
2467 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2468 for (auto &A: Args) {
2469 auto &O = A->getOption();
2470 // Skip language selection, which is positional.
2471 if (O.getID() == options::OPT_x)
2472 continue;
2473 // Skip writing dependency output and the compilation database itself.
2474 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2475 continue;
2476 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2477 continue;
2478 // Skip inputs.
2479 if (O.getKind() == Option::InputClass)
2480 continue;
2481 // Skip output.
2482 if (O.getID() == options::OPT_o)
2483 continue;
2484 // All other arguments are quoted and appended.
2485 ArgStringList ASL;
2486 A->render(Args, ASL);
2487 for (auto &it: ASL)
2488 CDB << ", \"" << escape(it) << "\"";
2489 }
2490 Buf = "--target=";
2491 Buf += Target;
2492 CDB << ", \"" << escape(Buf) << "\"]},\n";
2493}
2494
2495void Clang::DumpCompilationDatabaseFragmentToDir(
2496 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2497 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2498 // If this is a dry run, do not create the compilation database file.
2499 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2500 return;
2501
2502 if (CompilationDatabase)
2503 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2504
2505 SmallString<256> Path = Dir;
2506 const auto &Driver = C.getDriver();
2507 Driver.getVFS().makeAbsolute(Path);
2508 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2509 if (Err) {
2510 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2511 return;
2512 }
2513
2514 llvm::sys::path::append(
2515 Path,
2516 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2517 int FD;
2518 SmallString<256> TempPath;
2519 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2520 llvm::sys::fs::OF_Text);
2521 if (Err) {
2522 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2523 return;
2524 }
2525 CompilationDatabase =
2526 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2527 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2528}
2529
2530static bool CheckARMImplicitITArg(StringRef Value) {
2531 return Value == "always" || Value == "never" || Value == "arm" ||
2532 Value == "thumb";
2533}
2534
2535static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2536 StringRef Value) {
2537 CmdArgs.push_back("-mllvm");
2538 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2539}
2540
2542 const ArgList &Args,
2543 ArgStringList &CmdArgs,
2544 const Driver &D) {
2545 // Default to -mno-relax-all.
2546 //
2547 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2548 // cannot be done by assembler branch relaxation as it needs a free temporary
2549 // register. Because of this, branch relaxation is handled by a MachineIR pass
2550 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2551 // MachineIR branch relaxation inaccurate and it will miss cases where an
2552 // indirect branch is necessary.
2553 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2554 options::OPT_mno_relax_all);
2555
2556 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2557 options::OPT_mno_incremental_linker_compatible);
2558
2559 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2560
2561 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2562 options::OPT_fno_emit_compact_unwind_non_canonical);
2563
2564 // If you add more args here, also add them to the block below that
2565 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2566
2567 // When passing -I arguments to the assembler we sometimes need to
2568 // unconditionally take the next argument. For example, when parsing
2569 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2570 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2571 // arg after parsing the '-I' arg.
2572 bool TakeNextArg = false;
2573
2574 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2575 bool IsELF = Triple.isOSBinFormatELF();
2576 bool Crel = false, ExperimentalCrel = false;
2577 StringRef RelocSectionSym;
2578 bool SFrame = false, ExperimentalSFrame = false;
2579 bool ImplicitMapSyms = false;
2580 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2581 bool UseNoExecStack = false;
2582 bool Msa = false;
2583 const char *MipsTargetFeature = nullptr;
2584 llvm::SmallVector<const char *> SparcTargetFeatures;
2585 StringRef ImplicitIt;
2586 for (const Arg *A :
2587 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2588 options::OPT_mimplicit_it_EQ)) {
2589 A->claim();
2590
2591 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2592 switch (C.getDefaultToolChain().getArch()) {
2593 case llvm::Triple::arm:
2594 case llvm::Triple::armeb:
2595 case llvm::Triple::thumb:
2596 case llvm::Triple::thumbeb:
2597 // Only store the value; the last value set takes effect.
2598 ImplicitIt = A->getValue();
2599 if (!CheckARMImplicitITArg(ImplicitIt))
2600 D.Diag(diag::err_drv_unsupported_option_argument)
2601 << A->getSpelling() << ImplicitIt;
2602 continue;
2603 default:
2604 break;
2605 }
2606 }
2607
2608 for (StringRef Value : A->getValues()) {
2609 if (TakeNextArg) {
2610 CmdArgs.push_back(Value.data());
2611 TakeNextArg = false;
2612 continue;
2613 }
2614
2615 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2616 Value == "-mbig-obj")
2617 continue; // LLVM handles bigobj automatically
2618
2619 auto Equal = Value.split('=');
2620 auto checkArg = [&](bool ValidTarget,
2621 std::initializer_list<const char *> Set) {
2622 if (!ValidTarget) {
2623 D.Diag(diag::err_drv_unsupported_opt_for_target)
2624 << (Twine("-Wa,") + Equal.first + "=").str()
2625 << Triple.getTriple();
2626 } else if (!llvm::is_contained(Set, Equal.second)) {
2627 D.Diag(diag::err_drv_unsupported_option_argument)
2628 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2629 }
2630 };
2631 switch (C.getDefaultToolChain().getArch()) {
2632 default:
2633 break;
2634 case llvm::Triple::x86:
2635 case llvm::Triple::x86_64:
2636 if (Equal.first == "-mrelax-relocations" ||
2637 Equal.first == "--mrelax-relocations") {
2638 UseRelaxRelocations = Equal.second == "yes";
2639 checkArg(IsELF, {"yes", "no"});
2640 continue;
2641 }
2642 if (Value == "-msse2avx") {
2643 CmdArgs.push_back("-msse2avx");
2644 continue;
2645 }
2646 break;
2647 case llvm::Triple::wasm32:
2648 case llvm::Triple::wasm64:
2649 if (Value == "--no-type-check") {
2650 CmdArgs.push_back("-mno-type-check");
2651 continue;
2652 }
2653 break;
2654 case llvm::Triple::thumb:
2655 case llvm::Triple::thumbeb:
2656 case llvm::Triple::arm:
2657 case llvm::Triple::armeb:
2658 if (Equal.first == "-mimplicit-it") {
2659 // Only store the value; the last value set takes effect.
2660 ImplicitIt = Equal.second;
2661 checkArg(true, {"always", "never", "arm", "thumb"});
2662 continue;
2663 }
2664 if (Value == "-mthumb")
2665 // -mthumb has already been processed in ComputeLLVMTriple()
2666 // recognize but skip over here.
2667 continue;
2668 break;
2669 case llvm::Triple::aarch64:
2670 case llvm::Triple::aarch64_be:
2671 case llvm::Triple::aarch64_32:
2672 if (Equal.first == "-mmapsyms") {
2673 ImplicitMapSyms = Equal.second == "implicit";
2674 checkArg(IsELF, {"default", "implicit"});
2675 continue;
2676 }
2677 break;
2678 case llvm::Triple::mips:
2679 case llvm::Triple::mipsel:
2680 case llvm::Triple::mips64:
2681 case llvm::Triple::mips64el:
2682 if (Value == "--trap") {
2683 CmdArgs.push_back("-target-feature");
2684 CmdArgs.push_back("+use-tcc-in-div");
2685 continue;
2686 }
2687 if (Value == "--break") {
2688 CmdArgs.push_back("-target-feature");
2689 CmdArgs.push_back("-use-tcc-in-div");
2690 continue;
2691 }
2692 if (Value.starts_with("-msoft-float")) {
2693 CmdArgs.push_back("-target-feature");
2694 CmdArgs.push_back("+soft-float");
2695 continue;
2696 }
2697 if (Value.starts_with("-mhard-float")) {
2698 CmdArgs.push_back("-target-feature");
2699 CmdArgs.push_back("-soft-float");
2700 continue;
2701 }
2702 if (Value == "-mmsa") {
2703 Msa = true;
2704 continue;
2705 }
2706 if (Value == "-mno-msa") {
2707 Msa = false;
2708 continue;
2709 }
2710 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2711 .Case("-mips1", "+mips1")
2712 .Case("-mips2", "+mips2")
2713 .Case("-mips3", "+mips3")
2714 .Case("-mips4", "+mips4")
2715 .Case("-mips5", "+mips5")
2716 .Case("-mips32", "+mips32")
2717 .Case("-mips32r2", "+mips32r2")
2718 .Case("-mips32r3", "+mips32r3")
2719 .Case("-mips32r5", "+mips32r5")
2720 .Case("-mips32r6", "+mips32r6")
2721 .Case("-mips64", "+mips64")
2722 .Case("-mips64r2", "+mips64r2")
2723 .Case("-mips64r3", "+mips64r3")
2724 .Case("-mips64r5", "+mips64r5")
2725 .Case("-mips64r6", "+mips64r6")
2726 .Default(nullptr);
2727 if (MipsTargetFeature)
2728 continue;
2729 break;
2730
2731 case llvm::Triple::sparc:
2732 case llvm::Triple::sparcel:
2733 case llvm::Triple::sparcv9:
2734 if (Value == "--undeclared-regs") {
2735 // LLVM already allows undeclared use of G registers, so this option
2736 // becomes a no-op. This solely exists for GNU compatibility.
2737 // TODO implement --no-undeclared-regs
2738 continue;
2739 }
2740 SparcTargetFeatures =
2741 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2742 .Case("-Av8", {"-v8plus"})
2743 .Case("-Av8plus", {"+v8plus", "+v9"})
2744 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2745 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2746 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2747 .Case("-Av9", {"+v9"})
2748 .Case("-Av9a", {"+v9", "+vis"})
2749 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2750 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2751 .Default({});
2752 if (!SparcTargetFeatures.empty())
2753 continue;
2754 break;
2755 }
2756
2757 if (Value == "-force_cpusubtype_ALL") {
2758 // Do nothing, this is the default and we don't support anything else.
2759 } else if (Value == "-L") {
2760 CmdArgs.push_back("-msave-temp-labels");
2761 } else if (Value == "--fatal-warnings") {
2762 CmdArgs.push_back("-massembler-fatal-warnings");
2763 } else if (Value == "--no-warn" || Value == "-W") {
2764 CmdArgs.push_back("-massembler-no-warn");
2765 } else if (Value == "--noexecstack") {
2766 UseNoExecStack = true;
2767 } else if (Value.starts_with("-compress-debug-sections") ||
2768 Value.starts_with("--compress-debug-sections") ||
2769 Value == "-nocompress-debug-sections" ||
2770 Value == "--nocompress-debug-sections") {
2771 CmdArgs.push_back(Value.data());
2772 } else if (Value == "--crel") {
2773 Crel = true;
2774 } else if (Value == "--no-crel") {
2775 Crel = false;
2776 } else if (Value == "--allow-experimental-crel") {
2777 ExperimentalCrel = true;
2778 } else if (Value.starts_with("--reloc-section-sym=")) {
2779 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2780 } else if (Value.starts_with("-I")) {
2781 CmdArgs.push_back(Value.data());
2782 // We need to consume the next argument if the current arg is a plain
2783 // -I. The next arg will be the include directory.
2784 if (Value == "-I")
2785 TakeNextArg = true;
2786 } else if (Value.starts_with("-gdwarf-")) {
2787 // "-gdwarf-N" options are not cc1as options.
2788 unsigned DwarfVersion = DwarfVersionNum(Value);
2789 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2790 CmdArgs.push_back(Value.data());
2791 } else {
2792 RenderDebugEnablingArgs(Args, CmdArgs,
2793 llvm::codegenoptions::DebugInfoConstructor,
2794 DwarfVersion, llvm::DebuggerKind::Default);
2795 }
2796 } else if (Value == "--gsframe") {
2797 SFrame = true;
2798 } else if (Value == "--allow-experimental-sframe") {
2799 ExperimentalSFrame = true;
2800 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2801 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2802 // Do nothing, we'll validate it later.
2803 } else if (Value == "-defsym" || Value == "--defsym") {
2804 if (A->getNumValues() != 2) {
2805 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2806 break;
2807 }
2808 const char *S = A->getValue(1);
2809 auto Pair = StringRef(S).split('=');
2810 auto Sym = Pair.first;
2811 auto SVal = Pair.second;
2812
2813 if (Sym.empty() || SVal.empty()) {
2814 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2815 break;
2816 }
2817 int64_t IVal;
2818 if (SVal.getAsInteger(0, IVal)) {
2819 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2820 break;
2821 }
2822 CmdArgs.push_back("--defsym");
2823 TakeNextArg = true;
2824 } else if (Value == "-fdebug-compilation-dir") {
2825 CmdArgs.push_back("-fdebug-compilation-dir");
2826 TakeNextArg = true;
2827 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2828 // The flag is a -Wa / -Xassembler argument and Options doesn't
2829 // parse the argument, so this isn't automatically aliased to
2830 // -fdebug-compilation-dir (without '=') here.
2831 CmdArgs.push_back("-fdebug-compilation-dir");
2832 CmdArgs.push_back(Value.data());
2833 } else if (Value == "--version") {
2834 D.PrintVersion(C, llvm::outs());
2835 } else {
2836 D.Diag(diag::err_drv_unsupported_option_argument)
2837 << A->getSpelling() << Value;
2838 }
2839 }
2840 }
2841 if (ImplicitIt.size())
2842 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2843 if (Crel) {
2844 if (!ExperimentalCrel)
2845 D.Diag(diag::err_drv_experimental_crel);
2846 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2847 CmdArgs.push_back("--crel");
2848 } else {
2849 D.Diag(diag::err_drv_unsupported_opt_for_target)
2850 << "-Wa,--crel" << D.getTargetTriple();
2851 }
2852 }
2853 if (!RelocSectionSym.empty()) {
2854 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2855 RelocSectionSym != "none")
2856 D.Diag(diag::err_drv_invalid_value)
2857 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2858 << RelocSectionSym;
2859 else if (Triple.isOSBinFormatELF())
2860 CmdArgs.push_back(
2861 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2862 else
2863 D.Diag(diag::err_drv_unsupported_opt_for_target)
2864 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2865 }
2866 if (SFrame) {
2867 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2868 if (!ExperimentalSFrame)
2869 D.Diag(diag::err_drv_experimental_sframe);
2870 else
2871 CmdArgs.push_back("--gsframe");
2872 } else {
2873 D.Diag(diag::err_drv_unsupported_opt_for_target)
2874 << "-Wa,--gsframe" << D.getTargetTriple();
2875 }
2876 }
2877 if (ImplicitMapSyms)
2878 CmdArgs.push_back("-mmapsyms=implicit");
2879 if (Msa)
2880 CmdArgs.push_back("-mmsa");
2881 if (!UseRelaxRelocations)
2882 CmdArgs.push_back("-mrelax-relocations=no");
2883 if (UseNoExecStack)
2884 CmdArgs.push_back("-mnoexecstack");
2885 if (MipsTargetFeature != nullptr) {
2886 CmdArgs.push_back("-target-feature");
2887 CmdArgs.push_back(MipsTargetFeature);
2888 }
2889
2890 for (const char *Feature : SparcTargetFeatures) {
2891 CmdArgs.push_back("-target-feature");
2892 CmdArgs.push_back(Feature);
2893 }
2894
2895 // forward -fembed-bitcode to assmebler
2896 if (C.getDriver().embedBitcodeEnabled() ||
2897 C.getDriver().embedBitcodeMarkerOnly())
2898 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2899
2900 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2901 CmdArgs.push_back("-as-secure-log-file");
2902 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2903 }
2904}
2905
2906static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2907 bool OFastEnabled, const ArgList &Args,
2908 ArgStringList &CmdArgs,
2909 const JobAction &JA) {
2910 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2911 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2912 llvm::StringLiteral("SLEEF")};
2913 bool NoMathErrnoWasImpliedByVecLib = false;
2914 const Arg *VecLibArg = nullptr;
2915 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2916 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2917
2918 // Handle various floating point optimization flags, mapping them to the
2919 // appropriate LLVM code generation flags. This is complicated by several
2920 // "umbrella" flags, so we do this by stepping through the flags incrementally
2921 // adjusting what we think is enabled/disabled, then at the end setting the
2922 // LLVM flags based on the final state.
2923 bool HonorINFs = true;
2924 bool HonorNaNs = true;
2925 bool ApproxFunc = false;
2926 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2927 bool MathErrno = TC.IsMathErrnoDefault();
2928 bool AssociativeMath = false;
2929 bool ReciprocalMath = false;
2930 bool SignedZeros = true;
2931 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2932 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2933 // overriden by ffp-exception-behavior?
2934 bool RoundingFPMath = false;
2935 // -ffp-model values: strict, fast, precise
2936 StringRef FPModel = "";
2937 // -ffp-exception-behavior options: strict, maytrap, ignore
2938 StringRef FPExceptionBehavior = "";
2939 // -ffp-eval-method options: double, extended, source
2940 StringRef FPEvalMethod = "";
2941 llvm::DenormalMode DenormalFPMath =
2942 TC.getDefaultDenormalModeForType(Args, JA);
2943 llvm::DenormalMode DenormalFP32Math =
2944 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2945
2946 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2947 // If one wasn't given by the user, don't pass it here.
2948 StringRef FPContract;
2949 StringRef LastSeenFfpContractOption;
2950 StringRef LastFpContractOverrideOption;
2951 bool SeenUnsafeMathModeOption = false;
2954 FPContract = "on";
2955 bool StrictFPModel = false;
2956 StringRef Float16ExcessPrecision = "";
2957 StringRef BFloat16ExcessPrecision = "";
2959 std::string ComplexRangeStr;
2960 StringRef LastComplexRangeOption;
2961
2962 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2963 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2964 if (Aggressive) {
2965 HonorINFs = false;
2966 HonorNaNs = false;
2968 LastComplexRangeOption, Range);
2969 } else {
2970 HonorINFs = true;
2971 HonorNaNs = true;
2972 setComplexRange(D, CallerOption,
2974 LastComplexRangeOption, Range);
2975 }
2976 MathErrno = false;
2977 AssociativeMath = true;
2978 ReciprocalMath = true;
2979 ApproxFunc = true;
2980 SignedZeros = false;
2981 TrappingMath = false;
2982 RoundingFPMath = false;
2983 FPExceptionBehavior = "";
2984 FPContract = "fast";
2985 SeenUnsafeMathModeOption = true;
2986 };
2987
2988 // Lambda to consolidate common handling for fp-contract
2989 auto restoreFPContractState = [&]() {
2990 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2991 // For other targets, if the state has been changed by one of the
2992 // unsafe-math umbrella options a subsequent -fno-fast-math or
2993 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2994 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2995 // option. If we have not seen an unsafe-math option or -ffp-contract,
2996 // we leave the FPContract state unchanged.
2999 if (LastSeenFfpContractOption != "")
3000 FPContract = LastSeenFfpContractOption;
3001 else if (SeenUnsafeMathModeOption)
3002 FPContract = "on";
3003 }
3004 // In this case, we're reverting to the last explicit fp-contract option
3005 // or the platform default
3006 LastFpContractOverrideOption = "";
3007 };
3008
3009 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3010 CmdArgs.push_back("-mlimit-float-precision");
3011 CmdArgs.push_back(A->getValue());
3012 }
3013
3014 for (const Arg *A : Args) {
3015 llvm::scope_exit CheckMathErrnoForVecLib(
3016 [&, MathErrnoBeforeArg = MathErrno] {
3017 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3018 ArgThatEnabledMathErrnoAfterVecLib = A;
3019 });
3020
3021 switch (A->getOption().getID()) {
3022 // If this isn't an FP option skip the claim below
3023 default: continue;
3024
3025 case options::OPT_fcx_limited_range:
3026 setComplexRange(D, A->getSpelling(),
3028 LastComplexRangeOption, Range);
3029 break;
3030 case options::OPT_fno_cx_limited_range:
3031 setComplexRange(D, A->getSpelling(),
3033 LastComplexRangeOption, Range);
3034 break;
3035 case options::OPT_fcx_fortran_rules:
3036 setComplexRange(D, A->getSpelling(),
3038 LastComplexRangeOption, Range);
3039 break;
3040 case options::OPT_fno_cx_fortran_rules:
3041 setComplexRange(D, A->getSpelling(),
3043 LastComplexRangeOption, Range);
3044 break;
3045 case options::OPT_fcomplex_arithmetic_EQ: {
3047 StringRef Val = A->getValue();
3048 if (Val == "full")
3050 else if (Val == "improved")
3052 else if (Val == "promoted")
3054 else if (Val == "basic")
3056 else {
3057 D.Diag(diag::err_drv_unsupported_option_argument)
3058 << A->getSpelling() << Val;
3059 break;
3060 }
3061 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3062 LastComplexRangeOption, Range);
3063 break;
3064 }
3065 case options::OPT_ffp_model_EQ: {
3066 // If -ffp-model= is seen, reset to fno-fast-math
3067 HonorINFs = true;
3068 HonorNaNs = true;
3069 ApproxFunc = false;
3070 // Turning *off* -ffast-math restores the toolchain default.
3071 MathErrno = TC.IsMathErrnoDefault();
3072 AssociativeMath = false;
3073 ReciprocalMath = false;
3074 SignedZeros = true;
3075
3076 StringRef Val = A->getValue();
3077 if (OFastEnabled && Val != "aggressive") {
3078 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3079 D.Diag(clang::diag::warn_drv_overriding_option)
3080 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3081 break;
3082 }
3083 StrictFPModel = false;
3084 if (!FPModel.empty() && FPModel != Val)
3085 D.Diag(clang::diag::warn_drv_overriding_option)
3086 << Args.MakeArgString("-ffp-model=" + FPModel)
3087 << Args.MakeArgString("-ffp-model=" + Val);
3088 if (Val == "fast") {
3089 FPModel = Val;
3090 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3091 // applyFastMath sets fp-contract="fast"
3092 LastFpContractOverrideOption = "-ffp-model=fast";
3093 } else if (Val == "aggressive") {
3094 FPModel = Val;
3095 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3096 // applyFastMath sets fp-contract="fast"
3097 LastFpContractOverrideOption = "-ffp-model=aggressive";
3098 } else if (Val == "precise") {
3099 FPModel = Val;
3100 FPContract = "on";
3101 LastFpContractOverrideOption = "-ffp-model=precise";
3102 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3104 LastComplexRangeOption, Range);
3105 } else if (Val == "strict") {
3106 StrictFPModel = true;
3107 FPExceptionBehavior = "strict";
3108 FPModel = Val;
3109 FPContract = "off";
3110 LastFpContractOverrideOption = "-ffp-model=strict";
3111 TrappingMath = true;
3112 RoundingFPMath = true;
3113 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3115 LastComplexRangeOption, Range);
3116 } else
3117 D.Diag(diag::err_drv_unsupported_option_argument)
3118 << A->getSpelling() << Val;
3119 break;
3120 }
3121
3122 // Options controlling individual features
3123 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3124 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3125 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3126 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3127 case options::OPT_fapprox_func: ApproxFunc = true; break;
3128 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3129 case options::OPT_fmath_errno: MathErrno = true; break;
3130 case options::OPT_fno_math_errno: MathErrno = false; break;
3131 case options::OPT_fassociative_math: AssociativeMath = true; break;
3132 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3133 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3134 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3135 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3136 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3137 case options::OPT_ftrapping_math:
3138 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3139 FPExceptionBehavior != "strict")
3140 // Warn that previous value of option is overridden.
3141 D.Diag(clang::diag::warn_drv_overriding_option)
3142 << Args.MakeArgString("-ffp-exception-behavior=" +
3143 FPExceptionBehavior)
3144 << "-ftrapping-math";
3145 TrappingMath = true;
3146 TrappingMathPresent = true;
3147 FPExceptionBehavior = "strict";
3148 break;
3149 case options::OPT_fveclib:
3150 VecLibArg = A;
3151 NoMathErrnoWasImpliedByVecLib =
3152 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3153 if (NoMathErrnoWasImpliedByVecLib)
3154 MathErrno = false;
3155 break;
3156 case options::OPT_fno_trapping_math:
3157 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3158 FPExceptionBehavior != "ignore")
3159 // Warn that previous value of option is overridden.
3160 D.Diag(clang::diag::warn_drv_overriding_option)
3161 << Args.MakeArgString("-ffp-exception-behavior=" +
3162 FPExceptionBehavior)
3163 << "-fno-trapping-math";
3164 TrappingMath = false;
3165 TrappingMathPresent = true;
3166 FPExceptionBehavior = "ignore";
3167 break;
3168
3169 case options::OPT_frounding_math:
3170 RoundingFPMath = true;
3171 break;
3172
3173 case options::OPT_fno_rounding_math:
3174 RoundingFPMath = false;
3175 break;
3176
3177 case options::OPT_fdenormal_fp_math_EQ:
3178 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3179 DenormalFP32Math = DenormalFPMath;
3180 if (!DenormalFPMath.isValid()) {
3181 D.Diag(diag::err_drv_invalid_value)
3182 << A->getAsString(Args) << A->getValue();
3183 }
3184 break;
3185
3186 case options::OPT_fdenormal_fp_math_f32_EQ:
3187 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3188 if (!DenormalFP32Math.isValid()) {
3189 D.Diag(diag::err_drv_invalid_value)
3190 << A->getAsString(Args) << A->getValue();
3191 }
3192 break;
3193
3194 // Validate and pass through -ffp-contract option.
3195 case options::OPT_ffp_contract: {
3196 StringRef Val = A->getValue();
3197 if (Val == "fast" || Val == "on" || Val == "off" ||
3198 Val == "fast-honor-pragmas") {
3199 if (Val != FPContract && LastFpContractOverrideOption != "") {
3200 D.Diag(clang::diag::warn_drv_overriding_option)
3201 << LastFpContractOverrideOption
3202 << Args.MakeArgString("-ffp-contract=" + Val);
3203 }
3204
3205 FPContract = Val;
3206 LastSeenFfpContractOption = Val;
3207 LastFpContractOverrideOption = "";
3208 } else
3209 D.Diag(diag::err_drv_unsupported_option_argument)
3210 << A->getSpelling() << Val;
3211 break;
3212 }
3213
3214 // Validate and pass through -ffp-exception-behavior option.
3215 case options::OPT_ffp_exception_behavior_EQ: {
3216 StringRef Val = A->getValue();
3217 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3218 FPExceptionBehavior != Val)
3219 // Warn that previous value of option is overridden.
3220 D.Diag(clang::diag::warn_drv_overriding_option)
3221 << Args.MakeArgString("-ffp-exception-behavior=" +
3222 FPExceptionBehavior)
3223 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3224 TrappingMath = TrappingMathPresent = false;
3225 if (Val == "ignore" || Val == "maytrap")
3226 FPExceptionBehavior = Val;
3227 else if (Val == "strict") {
3228 FPExceptionBehavior = Val;
3229 TrappingMath = TrappingMathPresent = true;
3230 } else
3231 D.Diag(diag::err_drv_unsupported_option_argument)
3232 << A->getSpelling() << Val;
3233 break;
3234 }
3235
3236 // Validate and pass through -ffp-eval-method option.
3237 case options::OPT_ffp_eval_method_EQ: {
3238 StringRef Val = A->getValue();
3239 if (Val == "double" || Val == "extended" || Val == "source")
3240 FPEvalMethod = Val;
3241 else
3242 D.Diag(diag::err_drv_unsupported_option_argument)
3243 << A->getSpelling() << Val;
3244 break;
3245 }
3246
3247 case options::OPT_fexcess_precision_EQ: {
3248 StringRef Val = A->getValue();
3249 const llvm::Triple::ArchType Arch = TC.getArch();
3250 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3251 if (Val == "standard" || Val == "fast")
3252 Float16ExcessPrecision = Val;
3253 // To make it GCC compatible, allow the value of "16" which
3254 // means disable excess precision, the same meaning than clang's
3255 // equivalent value "none".
3256 else if (Val == "16")
3257 Float16ExcessPrecision = "none";
3258 else
3259 D.Diag(diag::err_drv_unsupported_option_argument)
3260 << A->getSpelling() << Val;
3261 } else {
3262 if (!(Val == "standard" || Val == "fast"))
3263 D.Diag(diag::err_drv_unsupported_option_argument)
3264 << A->getSpelling() << Val;
3265 }
3266 BFloat16ExcessPrecision = Float16ExcessPrecision;
3267 break;
3268 }
3269 case options::OPT_ffinite_math_only:
3270 HonorINFs = false;
3271 HonorNaNs = false;
3272 break;
3273 case options::OPT_fno_finite_math_only:
3274 HonorINFs = true;
3275 HonorNaNs = true;
3276 break;
3277
3278 case options::OPT_funsafe_math_optimizations:
3279 AssociativeMath = true;
3280 ReciprocalMath = true;
3281 SignedZeros = false;
3282 ApproxFunc = true;
3283 TrappingMath = false;
3284 FPExceptionBehavior = "";
3285 FPContract = "fast";
3286 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3287 SeenUnsafeMathModeOption = true;
3288 break;
3289 case options::OPT_fno_unsafe_math_optimizations:
3290 AssociativeMath = false;
3291 ReciprocalMath = false;
3292 SignedZeros = true;
3293 ApproxFunc = false;
3294 restoreFPContractState();
3295 break;
3296
3297 case options::OPT_Ofast:
3298 // If -Ofast is the optimization level, then -ffast-math should be enabled
3299 if (!OFastEnabled)
3300 continue;
3301 [[fallthrough]];
3302 case options::OPT_ffast_math:
3303 applyFastMath(true, A->getSpelling());
3304 if (A->getOption().getID() == options::OPT_Ofast)
3305 LastFpContractOverrideOption = "-Ofast";
3306 else
3307 LastFpContractOverrideOption = "-ffast-math";
3308 break;
3309 case options::OPT_fno_fast_math:
3310 HonorINFs = true;
3311 HonorNaNs = true;
3312 // Turning on -ffast-math (with either flag) removes the need for
3313 // MathErrno. However, turning *off* -ffast-math merely restores the
3314 // toolchain default (which may be false).
3315 MathErrno = TC.IsMathErrnoDefault();
3316 AssociativeMath = false;
3317 ReciprocalMath = false;
3318 ApproxFunc = false;
3319 SignedZeros = true;
3320 restoreFPContractState();
3322 setComplexRange(D, A->getSpelling(),
3324 LastComplexRangeOption, Range);
3325 else
3327 LastComplexRangeOption = "";
3328 LastFpContractOverrideOption = "";
3329 break;
3330 } // End switch (A->getOption().getID())
3331
3332 // The StrictFPModel local variable is needed to report warnings
3333 // in the way we intend. If -ffp-model=strict has been used, we
3334 // want to report a warning for the next option encountered that
3335 // takes us out of the settings described by fp-model=strict, but
3336 // we don't want to continue issuing warnings for other conflicting
3337 // options after that.
3338 if (StrictFPModel) {
3339 // If -ffp-model=strict has been specified on command line but
3340 // subsequent options conflict then emit warning diagnostic.
3341 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3342 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3343 FPContract == "off")
3344 // OK: Current Arg doesn't conflict with -ffp-model=strict
3345 ;
3346 else {
3347 StrictFPModel = false;
3348 FPModel = "";
3349 // The warning for -ffp-contract would have been reported by the
3350 // OPT_ffp_contract_EQ handler above. A special check here is needed
3351 // to avoid duplicating the warning.
3352 auto RHS = (A->getNumValues() == 0)
3353 ? A->getSpelling()
3354 : Args.MakeArgString(A->getSpelling() + A->getValue());
3355 if (A->getSpelling() != "-ffp-contract=") {
3356 if (RHS != "-ffp-model=strict")
3357 D.Diag(clang::diag::warn_drv_overriding_option)
3358 << "-ffp-model=strict" << RHS;
3359 }
3360 }
3361 }
3362
3363 // If we handled this option claim it
3364 A->claim();
3365 }
3366
3367 if (!HonorINFs)
3368 CmdArgs.push_back("-menable-no-infs");
3369
3370 if (!HonorNaNs)
3371 CmdArgs.push_back("-menable-no-nans");
3372
3373 if (ApproxFunc)
3374 CmdArgs.push_back("-fapprox-func");
3375
3376 if (MathErrno) {
3377 CmdArgs.push_back("-fmath-errno");
3378 if (NoMathErrnoWasImpliedByVecLib)
3379 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3380 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3381 << VecLibArg->getAsString(Args);
3382 }
3383
3384 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3385 !TrappingMath)
3386 CmdArgs.push_back("-funsafe-math-optimizations");
3387
3388 if (!SignedZeros)
3389 CmdArgs.push_back("-fno-signed-zeros");
3390
3391 if (AssociativeMath && !SignedZeros && !TrappingMath)
3392 CmdArgs.push_back("-mreassociate");
3393
3394 if (ReciprocalMath)
3395 CmdArgs.push_back("-freciprocal-math");
3396
3397 if (TrappingMath) {
3398 // FP Exception Behavior is also set to strict
3399 assert(FPExceptionBehavior == "strict");
3400 }
3401
3402 // The default is IEEE.
3403 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3404 llvm::SmallString<64> DenormFlag;
3405 llvm::raw_svector_ostream ArgStr(DenormFlag);
3406 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3407 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3408 }
3409
3410 // Add f32 specific denormal mode flag if it's different.
3411 if (DenormalFP32Math != DenormalFPMath) {
3412 llvm::SmallString<64> DenormFlag;
3413 llvm::raw_svector_ostream ArgStr(DenormFlag);
3414 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3415 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3416 }
3417
3418 if (!FPContract.empty())
3419 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3420
3421 if (RoundingFPMath)
3422 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3423 else
3424 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3425
3426 if (!FPExceptionBehavior.empty())
3427 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3428 FPExceptionBehavior));
3429
3430 if (!FPEvalMethod.empty())
3431 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3432
3433 if (!Float16ExcessPrecision.empty())
3434 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3435 Float16ExcessPrecision));
3436 if (!BFloat16ExcessPrecision.empty())
3437 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3438 BFloat16ExcessPrecision));
3439
3440 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3441 if (!Recip.empty())
3442 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3443
3444 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3445 // individual features enabled by -ffast-math instead of the option itself as
3446 // that's consistent with gcc's behaviour.
3447 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3448 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3449 CmdArgs.push_back("-ffast-math");
3450
3451 // Handle __FINITE_MATH_ONLY__ similarly.
3452 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3453 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3454 // -menable-no-nans are set by the user.
3455 bool shouldAddFiniteMathOnly = false;
3456 if (!HonorINFs && !HonorNaNs) {
3457 shouldAddFiniteMathOnly = true;
3458 } else {
3459 bool InfValues = true;
3460 bool NanValues = true;
3461 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3462 StringRef ArgValue = Arg->getValue();
3463 if (ArgValue == "-menable-no-nans")
3464 NanValues = false;
3465 else if (ArgValue == "-menable-no-infs")
3466 InfValues = false;
3467 }
3468 if (!NanValues && !InfValues)
3469 shouldAddFiniteMathOnly = true;
3470 }
3471 if (shouldAddFiniteMathOnly) {
3472 CmdArgs.push_back("-ffinite-math-only");
3473 }
3474 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3475 CmdArgs.push_back("-mfpmath");
3476 CmdArgs.push_back(A->getValue());
3477 }
3478
3479 // Disable a codegen optimization for floating-point casts.
3480 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3481 options::OPT_fstrict_float_cast_overflow, false))
3482 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3483
3485 ComplexRangeStr = renderComplexRangeOption(Range);
3486 if (!ComplexRangeStr.empty()) {
3487 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3488 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3489 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3490 complexRangeKindToStr(Range)));
3491 }
3492 if (Args.hasArg(options::OPT_fcx_limited_range))
3493 CmdArgs.push_back("-fcx-limited-range");
3494 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3495 CmdArgs.push_back("-fcx-fortran-rules");
3496 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3497 CmdArgs.push_back("-fno-cx-limited-range");
3498 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3499 CmdArgs.push_back("-fno-cx-fortran-rules");
3500}
3501
3502static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3503 const llvm::Triple &Triple,
3504 const InputInfo &Input) {
3505 // Add default argument set.
3506 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3507 CmdArgs.push_back("-analyzer-checker=core");
3508 CmdArgs.push_back("-analyzer-checker=apiModeling");
3509
3510 if (!Triple.isWindowsMSVCEnvironment()) {
3511 CmdArgs.push_back("-analyzer-checker=unix");
3512 } else {
3513 // Enable "unix" checkers that also work on Windows.
3514 CmdArgs.push_back("-analyzer-checker=unix.API");
3515 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3516 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3517 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3518 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3519 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3520 }
3521
3522 // Disable some unix checkers for PS4/PS5.
3523 if (Triple.isPS()) {
3524 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3525 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3526 }
3527
3528 if (Triple.isOSDarwin()) {
3529 CmdArgs.push_back("-analyzer-checker=osx");
3530 CmdArgs.push_back(
3531 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3532 }
3533 else if (Triple.isOSFuchsia())
3534 CmdArgs.push_back("-analyzer-checker=fuchsia");
3535
3536 CmdArgs.push_back("-analyzer-checker=deadcode");
3537
3538 if (types::isCXX(Input.getType()))
3539 CmdArgs.push_back("-analyzer-checker=cplusplus");
3540
3541 if (!Triple.isPS()) {
3542 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3543 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3544 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3545 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3546 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3547 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3548 }
3549
3550 // Default nullability checks.
3551 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3552 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3553 }
3554
3555 // Set the output format. The default is plist, for (lame) historical reasons.
3556 CmdArgs.push_back("-analyzer-output");
3557 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3558 CmdArgs.push_back(A->getValue());
3559 else
3560 CmdArgs.push_back("plist");
3561
3562 // Disable the presentation of standard compiler warnings when using
3563 // --analyze. We only want to show static analyzer diagnostics or frontend
3564 // errors.
3565 CmdArgs.push_back("-w");
3566
3567 // Add -Xanalyzer arguments when running as analyzer.
3568 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3569}
3570
3571static bool isValidSymbolName(StringRef S) {
3572 if (S.empty())
3573 return false;
3574
3575 if (std::isdigit(S[0]))
3576 return false;
3577
3578 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3579}
3580
3581static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3582 const ArgList &Args, ArgStringList &CmdArgs,
3583 bool KernelOrKext) {
3584 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3585
3586 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3587 // doesn't even have a stack!
3588 if (EffectiveTriple.isNVPTX())
3589 return;
3590
3591 // -stack-protector=0 is default.
3593 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3594 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3595
3596 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3597 options::OPT_fstack_protector_all,
3598 options::OPT_fstack_protector_strong,
3599 options::OPT_fstack_protector)) {
3600 if (A->getOption().matches(options::OPT_fstack_protector))
3601 StackProtectorLevel =
3602 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3603 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3604 StackProtectorLevel = LangOptions::SSPStrong;
3605 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3606 StackProtectorLevel = LangOptions::SSPReq;
3607
3608 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3609 D.Diag(diag::warn_drv_unsupported_option_for_target)
3610 << A->getSpelling() << EffectiveTriple.getTriple();
3611 StackProtectorLevel = DefaultStackProtectorLevel;
3612 }
3613 } else {
3614 StackProtectorLevel = DefaultStackProtectorLevel;
3615 }
3616
3617 if (StackProtectorLevel) {
3618 CmdArgs.push_back("-stack-protector");
3619 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3620 }
3621
3622 // --param ssp-buffer-size=
3623 for (const Arg *A : Args.filtered(options::OPT__param)) {
3624 StringRef Str(A->getValue());
3625 if (Str.consume_front("ssp-buffer-size=")) {
3626 if (StackProtectorLevel) {
3627 CmdArgs.push_back("-stack-protector-buffer-size");
3628 // FIXME: Verify the argument is a valid integer.
3629 CmdArgs.push_back(Args.MakeArgString(Str));
3630 }
3631 A->claim();
3632 }
3633 }
3634
3635 const std::string &TripleStr = EffectiveTriple.getTriple();
3636 StringRef GuardValue;
3637 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3638 GuardValue = A->getValue();
3639 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3640 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3641 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3642 !EffectiveTriple.isSystemZ())
3643 D.Diag(diag::err_drv_unsupported_opt_for_target)
3644 << A->getAsString(Args) << TripleStr;
3645 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3646 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3647 GuardValue != "tls" && GuardValue != "global") {
3648 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3649 << A->getOption().getName() << GuardValue << "tls global";
3650 return;
3651 }
3652 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3653 GuardValue == "tls") {
3654 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3655 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3656 << A->getAsString(Args);
3657 return;
3658 }
3659 // Check whether the target subarch supports the hardware TLS register
3660 if (!arm::isHardTPSupported(EffectiveTriple)) {
3661 D.Diag(diag::err_target_unsupported_tp_hard)
3662 << EffectiveTriple.getArchName();
3663 return;
3664 }
3665 // Check whether the user asked for something other than -mtp=cp15
3666 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3667 StringRef Value = A->getValue();
3668 if (Value != "cp15") {
3669 D.Diag(diag::err_drv_argument_not_allowed_with)
3670 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3671 return;
3672 }
3673 }
3674 CmdArgs.push_back("-target-feature");
3675 CmdArgs.push_back("+read-tp-tpidruro");
3676 }
3677 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3678 GuardValue != "global") {
3679 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3680 << A->getOption().getName() << GuardValue << "sysreg global";
3681 return;
3682 }
3683 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3684 if (GuardValue != "tls" && GuardValue != "global") {
3685 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3686 << A->getOption().getName() << GuardValue << "tls global";
3687 return;
3688 }
3689 if (GuardValue == "tls") {
3690 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3691 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3692 << A->getAsString(Args);
3693 return;
3694 }
3695 }
3696 }
3697 A->render(Args, CmdArgs);
3698 }
3699
3700 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3701 StringRef Value = A->getValue();
3702 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3703 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3704 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3705 D.Diag(diag::err_drv_unsupported_opt_for_target)
3706 << A->getAsString(Args) << TripleStr;
3707 int Offset;
3708 if (Value.getAsInteger(10, Offset)) {
3709 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3710 return;
3711 }
3712 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3713 (Offset < 0 || Offset > 0xfffff)) {
3714 D.Diag(diag::err_drv_invalid_int_value)
3715 << A->getOption().getName() << Value;
3716 return;
3717 }
3718 A->render(Args, CmdArgs);
3719 }
3720
3721 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3722 StringRef Value = A->getValue();
3723 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3724 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3725 D.Diag(diag::err_drv_unsupported_opt_for_target)
3726 << A->getAsString(Args) << TripleStr;
3727 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3728 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3729 << A->getOption().getName() << Value << "fs gs";
3730 return;
3731 }
3732 if (EffectiveTriple.isAArch64() &&
3733 llvm::StringSwitch<bool>(Value)
3734 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3735 "tpidr_el2", "far_el1", "far_el2"},
3736 false)
3737 .Default(true)) {
3738 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3739 << A->getOption().getName() << Value
3740 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3741 return;
3742 }
3743 if (EffectiveTriple.isRISCV() && Value != "tp") {
3744 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3745 << A->getOption().getName() << Value << "tp";
3746 return;
3747 }
3748 if (EffectiveTriple.isPPC64() && Value != "r13") {
3749 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3750 << A->getOption().getName() << Value << "r13";
3751 return;
3752 }
3753 if (EffectiveTriple.isPPC32() && Value != "r2") {
3754 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3755 << A->getOption().getName() << Value << "r2";
3756 return;
3757 }
3758 A->render(Args, CmdArgs);
3759 }
3760
3761 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3762 StringRef Value = A->getValue();
3763 if (!isValidSymbolName(Value)) {
3764 D.Diag(diag::err_drv_argument_only_allowed_with)
3765 << A->getOption().getName() << "legal symbol name";
3766 return;
3767 }
3768 A->render(Args, CmdArgs);
3769 }
3770
3771 if (Arg *A =
3772 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3773 if (!EffectiveTriple.isAArch64())
3774 D.Diag(diag::err_drv_unsupported_opt_for_target)
3775 << A->getAsString(Args) << TripleStr;
3776 StringRef Value = A->getValue();
3777 unsigned Width;
3778 if (Value.getAsInteger(10, Width)) {
3779 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3780 return;
3781 }
3782 if (Width != 4 && Width != 8) {
3783 D.Diag(diag::err_drv_invalid_int_value)
3784 << A->getOption().getName() << Value;
3785 }
3786 }
3787 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3788 if (!EffectiveTriple.isSystemZ()) {
3789 D.Diag(diag::err_drv_unsupported_opt_for_target)
3790 << A->getAsString(Args) << TripleStr;
3791 return;
3792 }
3793 if (GuardValue != "global") {
3794 D.Diag(diag::err_drv_argument_only_allowed_with)
3795 << "-mstack-protector-guard-record"
3796 << "-mstack-protector-guard=global";
3797 return;
3798 }
3799 A->render(Args, CmdArgs);
3800 }
3801}
3802
3803static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3804 ArgStringList &CmdArgs) {
3805 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3806
3807 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3808 !EffectiveTriple.isOSFuchsia())
3809 return;
3810
3811 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3812 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3813 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3814 return;
3815
3816 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3817 options::OPT_fno_stack_clash_protection);
3818}
3819
3821 const ToolChain &TC,
3822 const ArgList &Args,
3823 ArgStringList &CmdArgs) {
3824 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3825 StringRef TrivialAutoVarInit = "";
3826
3827 for (const Arg *A : Args) {
3828 switch (A->getOption().getID()) {
3829 default:
3830 continue;
3831 case options::OPT_ftrivial_auto_var_init: {
3832 A->claim();
3833 StringRef Val = A->getValue();
3834 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3835 TrivialAutoVarInit = Val;
3836 else
3837 D.Diag(diag::err_drv_unsupported_option_argument)
3838 << A->getSpelling() << Val;
3839 break;
3840 }
3841 }
3842 }
3843
3844 if (TrivialAutoVarInit.empty())
3845 switch (DefaultTrivialAutoVarInit) {
3847 break;
3849 TrivialAutoVarInit = "pattern";
3850 break;
3852 TrivialAutoVarInit = "zero";
3853 break;
3854 }
3855
3856 if (!TrivialAutoVarInit.empty()) {
3857 CmdArgs.push_back(
3858 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3859 }
3860
3861 if (Arg *A =
3862 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3863 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3864 StringRef(
3865 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3866 "uninitialized")
3867 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3868 A->claim();
3869 StringRef Val = A->getValue();
3870 if (std::stoi(Val.str()) <= 0)
3871 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3872 CmdArgs.push_back(
3873 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3874 }
3875
3876 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3877 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3878 StringRef(
3879 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3880 "uninitialized")
3881 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3882 A->claim();
3883 StringRef Val = A->getValue();
3884 if (std::stoi(Val.str()) <= 0)
3885 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3886 CmdArgs.push_back(
3887 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3888 }
3889}
3890
3891static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3892 types::ID InputType) {
3893 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3894 // for denormal flushing handling based on the target.
3895 const unsigned ForwardedArguments[] = {
3896 options::OPT_cl_opt_disable,
3897 options::OPT_cl_strict_aliasing,
3898 options::OPT_cl_single_precision_constant,
3899 options::OPT_cl_finite_math_only,
3900 options::OPT_cl_kernel_arg_info,
3901 options::OPT_cl_unsafe_math_optimizations,
3902 options::OPT_cl_fast_relaxed_math,
3903 options::OPT_cl_mad_enable,
3904 options::OPT_cl_no_signed_zeros,
3905 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3906 options::OPT_cl_uniform_work_group_size
3907 };
3908
3909 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3910 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3911 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3912 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3913 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3914 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3915 }
3916
3917 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3918 CmdArgs.push_back("-menable-no-infs");
3919 CmdArgs.push_back("-menable-no-nans");
3920 }
3921
3922 for (const auto &Arg : ForwardedArguments)
3923 if (const auto *A = Args.getLastArg(Arg))
3924 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3925
3926 // Only add the default headers if we are compiling OpenCL sources.
3927 if ((types::isOpenCL(InputType) ||
3928 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3929 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3930 CmdArgs.push_back("-finclude-default-header");
3931 CmdArgs.push_back("-fdeclare-opencl-builtins");
3932 }
3933}
3934
3935static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3936 ArgStringList &CmdArgs, types::ID InputType) {
3937 const unsigned ForwardedArguments[] = {
3938 options::OPT_hlsl_all_resources_bound,
3939 options::OPT_dxil_validator_version,
3940 options::OPT_res_may_alias,
3941 options::OPT_D,
3942 options::OPT_I,
3943 options::OPT_O,
3944 options::OPT_emit_llvm,
3945 options::OPT_emit_obj,
3946 options::OPT_disable_llvm_passes,
3947 options::OPT_fnative_half_type,
3948 options::OPT_fnative_int16_type,
3949 options::OPT_fmatrix_memory_layout_EQ,
3950 options::OPT_hlsl_entrypoint,
3951 options::OPT_fdx_rootsignature_define,
3952 options::OPT_fdx_rootsignature_version,
3953 options::OPT_fhlsl_spv_use_unknown_image_format,
3954 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3955 options::OPT_fhlsl_spv_preserve_interface};
3956 if (!types::isHLSL(InputType))
3957 return;
3958 for (const auto &Arg : ForwardedArguments)
3959 if (const auto *A = Args.getLastArg(Arg))
3960 A->renderAsInput(Args, CmdArgs);
3961 // Add the default headers if dxc_no_stdinc is not set.
3962 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3963 !Args.hasArg(options::OPT_nostdinc))
3964 CmdArgs.push_back("-finclude-default-header");
3965
3966 if (Args.hasArg(options::OPT_dxc_Zss)) {
3967 if (Args.hasArg(options::OPT_dxc_Zsb))
3968 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
3969 CmdArgs.push_back("-mllvm");
3970 CmdArgs.push_back("-dx-Zss");
3971 }
3972 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
3973 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3974}
3975
3976static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3977 ArgStringList &CmdArgs, types::ID InputType) {
3978 if (!Args.hasArg(options::OPT_fopenacc))
3979 return;
3980
3981 CmdArgs.push_back("-fopenacc");
3982}
3983
3984static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3985 const ArgList &Args, ArgStringList &CmdArgs) {
3986 // -fbuiltin is default unless -mkernel is used.
3987 bool UseBuiltins =
3988 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3989 !Args.hasArg(options::OPT_mkernel));
3990 if (!UseBuiltins)
3991 CmdArgs.push_back("-fno-builtin");
3992
3993 // -ffreestanding implies -fno-builtin.
3994 if (Args.hasArg(options::OPT_ffreestanding))
3995 UseBuiltins = false;
3996
3997 // Process the -fno-builtin-* options.
3998 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3999 A->claim();
4000
4001 // If -fno-builtin is specified, then there's no need to pass the option to
4002 // the frontend.
4003 if (UseBuiltins)
4004 A->render(Args, CmdArgs);
4005 }
4006}
4007
4009 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4010 Twine Path{Str};
4011 Path.toVector(Result);
4012 return Path.getSingleStringRef() != "";
4013 }
4014 if (llvm::sys::path::cache_directory(Result)) {
4015 llvm::sys::path::append(Result, "clang");
4016 llvm::sys::path::append(Result, "ModuleCache");
4017 return true;
4018 }
4019 return false;
4020}
4021
4024 const char *BaseInput) {
4025 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4026 return StringRef(ModuleOutputEQ->getValue());
4027
4028 SmallString<256> OutputPath;
4029 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4030 FinalOutput && Args.hasArg(options::OPT_c))
4031 OutputPath = FinalOutput->getValue();
4032 else {
4033 llvm::sys::fs::current_path(OutputPath);
4034 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4035 }
4036
4037 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4038 llvm::sys::path::replace_extension(OutputPath, Extension);
4039 return OutputPath;
4040}
4041
4043 const ArgList &Args, const InputInfo &Input,
4044 const InputInfo &Output, bool HaveStd20,
4045 ArgStringList &CmdArgs) {
4046 const bool IsCXX = types::isCXX(Input.getType());
4047 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4048 bool HaveModules = HaveStdCXXModules;
4049
4050 // -fmodules enables the use of precompiled modules (off by default).
4051 // Users can pass -fno-cxx-modules to turn off modules support for
4052 // C++/Objective-C++ programs.
4053 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4054 options::OPT_fno_cxx_modules, true);
4055 bool HaveClangModules = false;
4056 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4057 if (AllowedInCXX || !IsCXX) {
4058 CmdArgs.push_back("-fmodules");
4059 HaveClangModules = true;
4060 }
4061 }
4062
4063 HaveModules |= HaveClangModules;
4064
4065 if (HaveModules && !AllowedInCXX)
4066 CmdArgs.push_back("-fno-cxx-modules");
4067
4068 // -fmodule-maps enables implicit reading of module map files. By default,
4069 // this is enabled if we are using Clang's flavor of precompiled modules.
4070 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4071 options::OPT_fno_implicit_module_maps, HaveClangModules))
4072 CmdArgs.push_back("-fimplicit-module-maps");
4073
4074 // -fmodules-decluse checks that modules used are declared so (off by default)
4075 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4076 options::OPT_fno_modules_decluse);
4077
4078 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4079 // all #included headers are part of modules.
4080 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4081 options::OPT_fno_modules_strict_decluse, false))
4082 CmdArgs.push_back("-fmodules-strict-decluse");
4083
4084 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4085 options::OPT_fno_modulemap_allow_subdirectory_search);
4086
4087 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4088 bool ImplicitModules = false;
4089 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4090 options::OPT_fno_implicit_modules, HaveClangModules)) {
4091 if (HaveModules)
4092 CmdArgs.push_back("-fno-implicit-modules");
4093 } else if (HaveModules) {
4094 ImplicitModules = true;
4095 // -fmodule-cache-path specifies where our implicitly-built module files
4096 // should be written.
4097 SmallString<128> Path;
4098 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4099 Path = A->getValue();
4100
4101 bool HasPath = true;
4102 if (C.isForDiagnostics()) {
4103 // When generating crash reports, we want to emit the modules along with
4104 // the reproduction sources, so we ignore any provided module path.
4105 Path = Output.getFilename();
4106 llvm::sys::path::replace_extension(Path, ".cache");
4107 llvm::sys::path::append(Path, "modules");
4108 } else if (Path.empty()) {
4109 // No module path was provided: use the default.
4110 HasPath = Driver::getDefaultModuleCachePath(Path);
4111 }
4112
4113 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4114 // That being said, that failure is unlikely and not caching is harmless.
4115 if (HasPath) {
4116 const char Arg[] = "-fmodules-cache-path=";
4117 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4118 CmdArgs.push_back(Args.MakeArgString(Path));
4119 }
4120
4121 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4122 }
4123
4124 if (HaveModules) {
4125 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4126 options::OPT_fno_prebuilt_implicit_modules, false))
4127 CmdArgs.push_back("-fprebuilt-implicit-modules");
4128 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4129 options::OPT_fno_modules_validate_input_files_content,
4130 false))
4131 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4132 }
4133
4134 // -fmodule-name specifies the module that is currently being built (or
4135 // used for header checking by -fmodule-maps).
4136 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4137
4138 // -fmodule-map-file can be used to specify files containing module
4139 // definitions.
4140 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4141
4142 // -fbuiltin-module-map can be used to load the clang
4143 // builtin headers modulemap file.
4144 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4145 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4146 llvm::sys::path::append(BuiltinModuleMap, "include");
4147 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4148 if (llvm::sys::fs::exists(BuiltinModuleMap))
4149 CmdArgs.push_back(
4150 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4151 }
4152
4153 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4154 // names to precompiled module files (the module is loaded only if used).
4155 // The -fmodule-file=<file> form can be used to unconditionally load
4156 // precompiled module files (whether used or not).
4157 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4158 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4159
4160 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4161 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4162 CmdArgs.push_back(Args.MakeArgString(
4163 std::string("-fprebuilt-module-path=") + A->getValue()));
4164 A->claim();
4165 }
4166 } else
4167 Args.ClaimAllArgs(options::OPT_fmodule_file);
4168
4169 // When building modules and generating crashdumps, we need to dump a module
4170 // dependency VFS alongside the output.
4171 if (HaveClangModules && C.isForDiagnostics()) {
4172 SmallString<128> VFSDir(Output.getFilename());
4173 llvm::sys::path::replace_extension(VFSDir, ".cache");
4174 // Add the cache directory as a temp so the crash diagnostics pick it up.
4175 C.addTempFile(Args.MakeArgString(VFSDir));
4176
4177 llvm::sys::path::append(VFSDir, "vfs");
4178 CmdArgs.push_back("-module-dependency-dir");
4179 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4180 }
4181
4182 if (HaveClangModules)
4183 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4184
4185 // Pass through all -fmodules-ignore-macro arguments.
4186 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4187 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4188 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4189
4190 if (HaveClangModules) {
4191 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4192
4193 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4194 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4195 D.Diag(diag::err_drv_argument_not_allowed_with)
4196 << A->getAsString(Args) << "-fbuild-session-timestamp";
4197
4198 llvm::sys::fs::file_status Status;
4199 if (llvm::sys::fs::status(A->getValue(), Status))
4200 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4201 CmdArgs.push_back(Args.MakeArgString(
4202 "-fbuild-session-timestamp=" +
4203 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4204 Status.getLastModificationTime().time_since_epoch())
4205 .count())));
4206 }
4207
4208 if (Args.getLastArg(
4209 options::OPT_fmodules_validate_once_per_build_session)) {
4210 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4211 options::OPT_fbuild_session_file))
4212 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4213
4214 Args.AddLastArg(CmdArgs,
4215 options::OPT_fmodules_validate_once_per_build_session);
4216 }
4217
4218 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4219 options::OPT_fno_modules_validate_system_headers,
4220 ImplicitModules))
4221 CmdArgs.push_back("-fmodules-validate-system-headers");
4222
4223 Args.AddLastArg(CmdArgs,
4224 options::OPT_fmodules_disable_diagnostic_validation);
4225 } else {
4226 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4227 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4228 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4229 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4230 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4231 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4232 }
4233
4234 // FIXME: We provisionally don't check ODR violations for decls in the global
4235 // module fragment.
4236 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4237
4238 if (Input.getType() == driver::types::TY_CXXModule ||
4239 Input.getType() == driver::types::TY_PP_CXXModule) {
4240 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4241 CmdArgs.push_back("-fmodules-reduced-bmi");
4242
4243 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4244 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4245 else if (!(Args.hasArg(options::OPT__precompile) ||
4246 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4247 Args.hasArg(options::OPT_fmodule_output))
4248 // If --precompile is specified, we will always generate a module file if
4249 // we're compiling an importable module unit. This is fine even if the
4250 // compilation process won't reach the point of generating the module file
4251 // (e.g., in the preprocessing mode), since the attached flag
4252 // '-fmodule-output' is useless.
4253 //
4254 // But if '--precompile' is specified, it might be annoying to always
4255 // generate the module file as '--precompile' will generate the module
4256 // file anyway.
4257 CmdArgs.push_back(Args.MakeArgString(
4258 "-fmodule-output=" +
4260 }
4261
4262 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4263 Args.hasArg(options::OPT__precompile) &&
4264 (!Args.hasArg(options::OPT_o) ||
4265 Args.getLastArg(options::OPT_o)->getValue() ==
4267 D.Diag(diag::err_drv_reduced_module_output_overrided);
4268 }
4269
4270 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4271 // other translation units than module units. This is more user friendly to
4272 // allow end uers to enable this feature without asking for help from build
4273 // systems.
4274 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4275 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4276
4277 // We need to include the case the input file is a module file here.
4278 // Since the default compilation model for C++ module interface unit will
4279 // create temporary module file and compile the temporary module file
4280 // to get the object file. Then the `-fmodule-output` flag will be
4281 // brought to the second compilation process. So we have to claim it for
4282 // the case too.
4283 if (Input.getType() == driver::types::TY_CXXModule ||
4284 Input.getType() == driver::types::TY_PP_CXXModule ||
4285 Input.getType() == driver::types::TY_ModuleFile) {
4286 Args.ClaimAllArgs(options::OPT_fmodule_output);
4287 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4288 }
4289
4290 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4291 CmdArgs.push_back("-fmodules-embed-all-files");
4292
4293 return HaveModules;
4294}
4295
4296static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4297 ArgStringList &CmdArgs) {
4298 // -fsigned-char is default.
4299 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4300 options::OPT_fno_signed_char,
4301 options::OPT_funsigned_char,
4302 options::OPT_fno_unsigned_char)) {
4303 if (A->getOption().matches(options::OPT_funsigned_char) ||
4304 A->getOption().matches(options::OPT_fno_signed_char)) {
4305 CmdArgs.push_back("-fno-signed-char");
4306 }
4307 } else if (!isSignedCharDefault(T)) {
4308 CmdArgs.push_back("-fno-signed-char");
4309 }
4310
4311 // The default depends on the language standard.
4312 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4313
4314 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4315 options::OPT_fno_short_wchar)) {
4316 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4317 CmdArgs.push_back("-fwchar-type=short");
4318 CmdArgs.push_back("-fno-signed-wchar");
4319 } else {
4320 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4321 CmdArgs.push_back("-fwchar-type=int");
4322 if (T.isOSzOS() ||
4323 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4324 CmdArgs.push_back("-fno-signed-wchar");
4325 else
4326 CmdArgs.push_back("-fsigned-wchar");
4327 }
4328 } else if (T.isOSzOS())
4329 CmdArgs.push_back("-fno-signed-wchar");
4330}
4331
4332static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4333 const llvm::Triple &T, const ArgList &Args,
4334 ObjCRuntime &Runtime, bool InferCovariantReturns,
4335 const InputInfo &Input, ArgStringList &CmdArgs) {
4336 const llvm::Triple::ArchType Arch = TC.getArch();
4337
4338 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4339 // is the default. Except for deployment target of 10.5, next runtime is
4340 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4341 if (Runtime.isNonFragile()) {
4342 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4343 options::OPT_fno_objc_legacy_dispatch,
4345 if (TC.UseObjCMixedDispatch())
4346 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4347 else
4348 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4349 }
4350 }
4351
4352 // Forward -fobjc-direct-precondition-thunk to cc1
4353 // Defaults to false and needs explict turn on for now
4354 // TODO: switch to default true and needs explict turn off in the future.
4355 // TODO: add support for other runtimes
4356 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4357 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4358 if (Runtime.isNeXTFamily()) {
4359 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4360 } else {
4361 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4362 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4363 }
4364 }
4365
4366 if (types::isObjC(Input.getType())) {
4367 // Pass down -fobjc-msgsend-selector-stubs if present.
4368 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4369 options::OPT_fno_objc_msgsend_selector_stubs, false))
4370 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4371
4372 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4373 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4374 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4375 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4376 }
4377
4378 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4379 // to do Array/Dictionary subscripting by default.
4380 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4381 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4382 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4383
4384 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4385 // NOTE: This logic is duplicated in ToolChains.cpp.
4386 if (isObjCAutoRefCount(Args)) {
4387 TC.CheckObjCARC();
4388
4389 CmdArgs.push_back("-fobjc-arc");
4390
4391 // FIXME: It seems like this entire block, and several around it should be
4392 // wrapped in isObjC, but for now we just use it here as this is where it
4393 // was being used previously.
4394 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4396 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4397 else
4398 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4399 }
4400
4401 // Allow the user to enable full exceptions code emission.
4402 // We default off for Objective-C, on for Objective-C++.
4403 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4404 options::OPT_fno_objc_arc_exceptions,
4405 /*Default=*/types::isCXX(Input.getType())))
4406 CmdArgs.push_back("-fobjc-arc-exceptions");
4407 }
4408
4409 // Silence warning for full exception code emission options when explicitly
4410 // set to use no ARC.
4411 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4412 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4413 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4414 }
4415
4416 // Allow the user to control whether messages can be converted to runtime
4417 // functions.
4418 if (types::isObjC(Input.getType())) {
4419 auto *Arg = Args.getLastArg(
4420 options::OPT_fobjc_convert_messages_to_runtime_calls,
4421 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4422 if (Arg &&
4423 Arg->getOption().matches(
4424 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4425 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4426 }
4427
4428 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4429 // rewriter.
4430 if (InferCovariantReturns)
4431 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4432
4433 // Pass down -fobjc-weak or -fno-objc-weak if present.
4434 if (types::isObjC(Input.getType())) {
4435 auto WeakArg =
4436 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4437 if (!WeakArg) {
4438 // nothing to do
4439 } else if (!Runtime.allowsWeak()) {
4440 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4441 D.Diag(diag::err_objc_weak_unsupported);
4442 } else {
4443 WeakArg->render(Args, CmdArgs);
4444 }
4445 }
4446
4447 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4448 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4449
4450 // Forward constant literal flags to cc1.
4451 if (types::isObjC(Input.getType())) {
4452 bool EnableConstantLiterals =
4453 Args.hasFlag(options::OPT_fobjc_constant_literals,
4454 options::OPT_fno_objc_constant_literals,
4455 /*default=*/true) &&
4456 Runtime.hasConstantLiteralClasses();
4457 if (EnableConstantLiterals)
4458 CmdArgs.push_back("-fobjc-constant-literals");
4459 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4460 options::OPT_fno_constant_nsnumber_literals,
4461 /*default=*/true) &&
4462 EnableConstantLiterals)
4463 CmdArgs.push_back("-fconstant-nsnumber-literals");
4464 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4465 options::OPT_fno_constant_nsarray_literals,
4466 /*default=*/true) &&
4467 EnableConstantLiterals)
4468 CmdArgs.push_back("-fconstant-nsarray-literals");
4469 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4470 options::OPT_fno_constant_nsdictionary_literals,
4471 /*default=*/true) &&
4472 EnableConstantLiterals)
4473 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4474 }
4475}
4476
4477static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4478 ArgStringList &CmdArgs) {
4479 bool CaretDefault = true;
4480 bool ColumnDefault = true;
4481
4482 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4483 options::OPT__SLASH_diagnostics_column,
4484 options::OPT__SLASH_diagnostics_caret)) {
4485 switch (A->getOption().getID()) {
4486 case options::OPT__SLASH_diagnostics_caret:
4487 CaretDefault = true;
4488 ColumnDefault = true;
4489 break;
4490 case options::OPT__SLASH_diagnostics_column:
4491 CaretDefault = false;
4492 ColumnDefault = true;
4493 break;
4494 case options::OPT__SLASH_diagnostics_classic:
4495 CaretDefault = false;
4496 ColumnDefault = false;
4497 break;
4498 }
4499 }
4500
4501 // -fcaret-diagnostics is default.
4502 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4503 options::OPT_fno_caret_diagnostics, CaretDefault))
4504 CmdArgs.push_back("-fno-caret-diagnostics");
4505
4506 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4507 options::OPT_fno_diagnostics_fixit_info);
4508 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4509 options::OPT_fno_diagnostics_show_option);
4510
4511 if (const Arg *A =
4512 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4513 CmdArgs.push_back("-fdiagnostics-show-category");
4514 CmdArgs.push_back(A->getValue());
4515 }
4516
4517 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4518 options::OPT_fno_diagnostics_show_hotness);
4519
4520 if (const Arg *A =
4521 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4522 std::string Opt =
4523 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4524 CmdArgs.push_back(Args.MakeArgString(Opt));
4525 }
4526
4527 if (const Arg *A =
4528 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4529 std::string Opt =
4530 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4531 CmdArgs.push_back(Args.MakeArgString(Opt));
4532 }
4533
4534 if (const Arg *A =
4535 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4536 options::OPT_fno_diagnostics_show_inlining_chain)) {
4537 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4538 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4539 else
4540 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4541 }
4542
4543 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4544 CmdArgs.push_back("-fdiagnostics-format");
4545 CmdArgs.push_back(A->getValue());
4546 if (StringRef(A->getValue()) == "sarif" ||
4547 StringRef(A->getValue()) == "SARIF")
4548 D.Diag(diag::warn_drv_sarif_format_unstable);
4549 }
4550
4551 if (const Arg *A = Args.getLastArg(
4552 options::OPT_fdiagnostics_show_note_include_stack,
4553 options::OPT_fno_diagnostics_show_note_include_stack)) {
4554 const Option &O = A->getOption();
4555 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4556 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4557 else
4558 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4559 }
4560
4561 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4562
4563 if (Args.hasArg(options::OPT_fansi_escape_codes))
4564 CmdArgs.push_back("-fansi-escape-codes");
4565
4566 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4567 options::OPT_fno_show_source_location);
4568
4569 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4570 options::OPT_fno_diagnostics_show_line_numbers);
4571
4572 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4573 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4574
4575 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4576 ColumnDefault))
4577 CmdArgs.push_back("-fno-show-column");
4578
4579 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4580 options::OPT_fno_spell_checking);
4581
4582 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4583}
4584
4585static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4586 const ArgList &Args, ArgStringList &CmdArgs,
4587 unsigned DwarfVersion) {
4588 auto *DwarfFormatArg =
4589 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4590 if (!DwarfFormatArg)
4591 return;
4592
4593 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4594 if (DwarfVersion < 3)
4595 D.Diag(diag::err_drv_argument_only_allowed_with)
4596 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4597 else if (!T.isArch64Bit())
4598 D.Diag(diag::err_drv_argument_only_allowed_with)
4599 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4600 else if (!T.isOSBinFormatELF())
4601 D.Diag(diag::err_drv_argument_only_allowed_with)
4602 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4603 }
4604
4605 DwarfFormatArg->render(Args, CmdArgs);
4606}
4607
4608static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4609 const ArgList &Args) {
4610 bool NeedsSimpleTemplateNames =
4611 Args.hasFlag(options::OPT_gsimple_template_names,
4612 options::OPT_gno_simple_template_names,
4614 if (!NeedsSimpleTemplateNames)
4615 return false;
4616
4617 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4618 if (!checkDebugInfoOption(A, Args, D, TC))
4619 return false;
4620
4621 return true;
4622}
4623
4624static void
4625renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4626 const ArgList &Args, types::ID InputType,
4627 ArgStringList &CmdArgs, const InputInfo &Output,
4628 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4629 DwarfFissionKind &DwarfFission) {
4630 bool IRInput = isLLVMIR(InputType);
4631 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4632 !isHIP(InputType) && !isObjC(InputType) &&
4633 !isOpenCL(InputType);
4634
4635 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4636
4637 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4638 options::OPT_fno_debug_record_sysroot, true))
4639 CmdArgs.push_back("-fno-debug-record-sysroot");
4640
4641 // The 'g' groups options involve a somewhat intricate sequence of decisions
4642 // about what to pass from the driver to the frontend, but by the time they
4643 // reach cc1 they've been factored into three well-defined orthogonal choices:
4644 // * what level of debug info to generate
4645 // * what dwarf version to write
4646 // * what debugger tuning to use
4647 // This avoids having to monkey around further in cc1 other than to disable
4648 // codeview if not running in a Windows environment. Perhaps even that
4649 // decision should be made in the driver as well though.
4650 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4651
4652 bool SplitDWARFInlining =
4653 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4654 options::OPT_fno_split_dwarf_inlining, false);
4655
4656 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4657 // object file generation and no IR generation, -gN should not be needed. So
4658 // allow -gsplit-dwarf with either -gN or IR input.
4659 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4660 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4661 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4662 D.Diag(diag::err_drv_unsupported_opt_for_target)
4663 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4664 << TC.getTripleString();
4665 return;
4666 }
4667 Arg *SplitDWARFArg;
4668 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4669 if (DwarfFission != DwarfFissionKind::None &&
4670 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4671 DwarfFission = DwarfFissionKind::None;
4672 SplitDWARFInlining = false;
4673 }
4674 }
4675 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4676 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4677
4678 // If the last option explicitly specified a debug-info level, use it.
4679 if (checkDebugInfoOption(A, Args, D, TC) &&
4680 A->getOption().matches(options::OPT_gN_Group)) {
4681 DebugInfoKind = debugLevelToInfoKind(*A);
4682 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4683 // complicated if you've disabled inline info in the skeleton CUs
4684 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4685 // line-tables-only, so let those compose naturally in that case.
4686 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4687 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4688 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4689 SplitDWARFInlining))
4690 DwarfFission = DwarfFissionKind::None;
4691 }
4692 }
4693
4694 // If a debugger tuning argument appeared, remember it.
4695 bool HasDebuggerTuning = false;
4696 if (const Arg *A =
4697 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4698 HasDebuggerTuning = true;
4699 if (checkDebugInfoOption(A, Args, D, TC)) {
4700 if (A->getOption().matches(options::OPT_glldb))
4701 DebuggerTuning = llvm::DebuggerKind::LLDB;
4702 else if (A->getOption().matches(options::OPT_gsce))
4703 DebuggerTuning = llvm::DebuggerKind::SCE;
4704 else if (A->getOption().matches(options::OPT_gdbx))
4705 DebuggerTuning = llvm::DebuggerKind::DBX;
4706 else
4707 DebuggerTuning = llvm::DebuggerKind::GDB;
4708 }
4709 }
4710
4711 // If a -gdwarf argument appeared, remember it.
4712 bool EmitDwarf = false;
4713 if (const Arg *A = getDwarfNArg(Args))
4714 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4715
4716 bool EmitCodeView = false;
4717 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4718 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4719
4720 // If the user asked for debug info but did not explicitly specify -gcodeview
4721 // or -gdwarf, ask the toolchain for the default format.
4722 if (!EmitCodeView && !EmitDwarf &&
4723 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4724 switch (TC.getDefaultDebugFormat()) {
4725 case llvm::codegenoptions::DIF_CodeView:
4726 EmitCodeView = true;
4727 break;
4728 case llvm::codegenoptions::DIF_DWARF:
4729 EmitDwarf = true;
4730 break;
4731 }
4732 }
4733
4734 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4735 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4736 // be lower than what the user wanted.
4737 if (EmitDwarf) {
4738 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4739 // Clamp effective DWARF version to the max supported by the toolchain.
4740 EffectiveDWARFVersion =
4741 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4742 } else {
4743 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4744 }
4745
4746 // -gline-directives-only supported only for the DWARF debug info.
4747 if (RequestedDWARFVersion == 0 &&
4748 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4749 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4750
4751 // strict DWARF is set to false by default. But for DBX, we need it to be set
4752 // as true by default.
4753 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4754 (void)checkDebugInfoOption(A, Args, D, TC);
4755 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4756 DebuggerTuning == llvm::DebuggerKind::DBX))
4757 CmdArgs.push_back("-gstrict-dwarf");
4758
4759 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4760 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4761
4762 // Column info is included by default for everything except SCE and
4763 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4764 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4765 // practice, however, the Microsoft debuggers don't handle missing end columns
4766 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4767 // it's better not to include any column info.
4768 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4769 (void)checkDebugInfoOption(A, Args, D, TC);
4770 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4771 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4772 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4773 DebuggerTuning != llvm::DebuggerKind::DBX)))
4774 CmdArgs.push_back("-gno-column-info");
4775
4776 if (!Args.hasFlag(options::OPT_gcall_site_info,
4777 options::OPT_gno_call_site_info, true))
4778 CmdArgs.push_back("-gno-call-site-info");
4779
4780 // FIXME: Move backend command line options to the module.
4781 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4782 // If -gline-tables-only or -gline-directives-only is the last option it
4783 // wins.
4784 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4785 TC)) {
4786 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4787 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4788 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4789 CmdArgs.push_back("-dwarf-ext-refs");
4790 CmdArgs.push_back("-fmodule-format=obj");
4791 }
4792 }
4793 }
4794
4795 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4796 CmdArgs.push_back("-fsplit-dwarf-inlining");
4797
4798 // After we've dealt with all combinations of things that could
4799 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4800 // figure out if we need to "upgrade" it to standalone debug info.
4801 // We parse these two '-f' options whether or not they will be used,
4802 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4803 bool NeedFullDebug = Args.hasFlag(
4804 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4805 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4807 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4808 (void)checkDebugInfoOption(A, Args, D, TC);
4809
4810 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4811 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4812 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4813 options::OPT_feliminate_unused_debug_types, false))
4814 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4815 else if (NeedFullDebug)
4816 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4817 }
4818
4819 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4820 false)) {
4821 // Source embedding is a vendor extension to DWARF v5. By now we have
4822 // checked if a DWARF version was stated explicitly, and have otherwise
4823 // fallen back to the target default, so if this is still not at least 5
4824 // we emit an error.
4825 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4826 if (RequestedDWARFVersion < 5)
4827 D.Diag(diag::err_drv_argument_only_allowed_with)
4828 << A->getAsString(Args) << "-gdwarf-5";
4829 else if (EffectiveDWARFVersion < 5)
4830 // The toolchain has reduced allowed dwarf version, so we can't enable
4831 // -gembed-source.
4832 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4833 << A->getAsString(Args) << TC.getTripleString() << 5
4834 << EffectiveDWARFVersion;
4835 else if (checkDebugInfoOption(A, Args, D, TC))
4836 CmdArgs.push_back("-gembed-source");
4837 }
4838
4839 // Enable Key Instructions by default if we're emitting DWARF, the language is
4840 // plain C or C++, and optimisations are enabled.
4841 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4842 bool KeyInstructionsOnByDefault =
4843 EmitDwarf && PlainCOrCXX && OptLevel &&
4844 !OptLevel->getOption().matches(options::OPT_O0);
4845 if (Args.hasFlag(options::OPT_gkey_instructions,
4846 options::OPT_gno_key_instructions,
4847 KeyInstructionsOnByDefault))
4848 CmdArgs.push_back("-gkey-instructions");
4849
4850 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4851 options::OPT_gno_structor_decl_linkage_names, true))
4852 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4853
4854 if (EmitCodeView) {
4855 CmdArgs.push_back("-gcodeview");
4856
4857 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4858 options::OPT_gno_codeview_ghash);
4859
4860 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4861 options::OPT_gno_codeview_command_line);
4862 }
4863
4864 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4865 options::OPT_gno_inline_line_tables);
4866
4867 // When emitting remarks, we need at least debug lines in the output.
4868 if (willEmitRemarks(Args) &&
4869 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4870 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4871
4872 // Adjust the debug info kind for the given toolchain.
4873 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4874
4875 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4876 // set.
4877 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4878 T.isOSAIX() && !HasDebuggerTuning
4879 ? llvm::DebuggerKind::Default
4880 : DebuggerTuning);
4881
4882 // -fdebug-macro turns on macro debug info generation.
4883 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4884 false))
4885 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4886 D, TC))
4887 CmdArgs.push_back("-debug-info-macro");
4888
4889 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4890 const auto *PubnamesArg =
4891 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4892 options::OPT_gpubnames, options::OPT_gno_pubnames);
4893 if (DwarfFission != DwarfFissionKind::None ||
4894 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4895 const bool OptionSet =
4896 (PubnamesArg &&
4897 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4898 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4899 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4900 (!PubnamesArg ||
4901 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4902 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4903 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4904 options::OPT_gpubnames)
4905 ? "-gpubnames"
4906 : "-ggnu-pubnames");
4907 }
4908
4909 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4910 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4911 ForwardTemplateParams = true;
4912 CmdArgs.push_back("-gsimple-template-names=simple");
4913 }
4914
4915 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4916 bool UseDebugTemplateAlias =
4917 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4918 if (const auto *DebugTemplateAlias = Args.getLastArg(
4919 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4920 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4921 // asks for it we should let them have it (if the target supports it).
4922 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4923 const auto &Opt = DebugTemplateAlias->getOption();
4924 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4925 }
4926 }
4927 if (UseDebugTemplateAlias)
4928 CmdArgs.push_back("-gtemplate-alias");
4929
4930 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4931 StringRef v = A->getValue();
4932 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4933 }
4934
4935 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4936 options::OPT_fno_debug_ranges_base_address);
4937
4938 // -gdwarf-aranges turns on the emission of the aranges section in the
4939 // backend.
4940 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4941 A && checkDebugInfoOption(A, Args, D, TC)) {
4942 CmdArgs.push_back("-mllvm");
4943 CmdArgs.push_back("-generate-arange-section");
4944 }
4945
4946 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4947 options::OPT_fno_force_dwarf_frame);
4948
4949 bool EnableTypeUnits = false;
4950 if (Args.hasFlag(options::OPT_fdebug_types_section,
4951 options::OPT_fno_debug_types_section, false)) {
4952 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4953 D.Diag(diag::err_drv_unsupported_opt_for_target)
4954 << Args.getLastArg(options::OPT_fdebug_types_section)
4955 ->getAsString(Args)
4956 << T.getTriple();
4957 } else if (checkDebugInfoOption(
4958 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4959 TC)) {
4960 EnableTypeUnits = true;
4961 CmdArgs.push_back("-mllvm");
4962 CmdArgs.push_back("-generate-type-units");
4963 }
4964 }
4965
4966 if (const Arg *A =
4967 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4968 options::OPT_gno_omit_unreferenced_methods))
4969 (void)checkDebugInfoOption(A, Args, D, TC);
4970 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4971 options::OPT_gno_omit_unreferenced_methods, false) &&
4972 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4973 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4974 !EnableTypeUnits) {
4975 CmdArgs.push_back("-gomit-unreferenced-methods");
4976 }
4977
4978 // To avoid join/split of directory+filename, the integrated assembler prefers
4979 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4980 // form before DWARF v5.
4981 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4982 options::OPT_fno_dwarf_directory_asm,
4983 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4984 CmdArgs.push_back("-fno-dwarf-directory-asm");
4985
4986 // Decide how to render forward declarations of template instantiations.
4987 // SCE wants full descriptions, others just get them in the name.
4988 if (ForwardTemplateParams)
4989 CmdArgs.push_back("-debug-forward-template-params");
4990
4991 // Do we need to explicitly import anonymous namespaces into the parent
4992 // scope?
4993 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4994 CmdArgs.push_back("-dwarf-explicit-import");
4995
4996 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4997 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4998
4999 // This controls whether or not we perform JustMyCode instrumentation.
5000 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5001 if (TC.getTriple().isOSBinFormatELF() ||
5002 TC.getTriple().isWindowsMSVCEnvironment()) {
5003 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5004 CmdArgs.push_back("-fjmc");
5005 else if (D.IsCLMode())
5006 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5007 << "'/Zi', '/Z7'";
5008 else
5009 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5010 << "-g";
5011 } else {
5012 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5013 }
5014 }
5015
5016 // Add in -fdebug-compilation-dir if necessary.
5017 const char *DebugCompilationDir =
5018 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5019
5020 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5021
5022 // Add the output path to the object file for CodeView debug infos.
5023 if (EmitCodeView && Output.isFilename())
5024 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5025 Output.getFilename());
5026}
5027
5028static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5029 ArgStringList &CmdArgs) {
5030 unsigned RTOptionID = options::OPT__SLASH_MT;
5031
5032 if (Args.hasArg(options::OPT__SLASH_LDd))
5033 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5034 // but defining _DEBUG is sticky.
5035 RTOptionID = options::OPT__SLASH_MTd;
5036
5037 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5038 RTOptionID = A->getOption().getID();
5039
5040 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5041 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5042 .Case("static", options::OPT__SLASH_MT)
5043 .Case("static_dbg", options::OPT__SLASH_MTd)
5044 .Case("dll", options::OPT__SLASH_MD)
5045 .Case("dll_dbg", options::OPT__SLASH_MDd)
5046 .Default(options::OPT__SLASH_MT);
5047 }
5048
5049 StringRef FlagForCRT;
5050 switch (RTOptionID) {
5051 case options::OPT__SLASH_MD:
5052 if (Args.hasArg(options::OPT__SLASH_LDd))
5053 CmdArgs.push_back("-D_DEBUG");
5054 CmdArgs.push_back("-D_MT");
5055 CmdArgs.push_back("-D_DLL");
5056 FlagForCRT = "--dependent-lib=msvcrt";
5057 break;
5058 case options::OPT__SLASH_MDd:
5059 CmdArgs.push_back("-D_DEBUG");
5060 CmdArgs.push_back("-D_MT");
5061 CmdArgs.push_back("-D_DLL");
5062 FlagForCRT = "--dependent-lib=msvcrtd";
5063 break;
5064 case options::OPT__SLASH_MT:
5065 if (Args.hasArg(options::OPT__SLASH_LDd))
5066 CmdArgs.push_back("-D_DEBUG");
5067 CmdArgs.push_back("-D_MT");
5068 CmdArgs.push_back("-flto-visibility-public-std");
5069 FlagForCRT = "--dependent-lib=libcmt";
5070 break;
5071 case options::OPT__SLASH_MTd:
5072 CmdArgs.push_back("-D_DEBUG");
5073 CmdArgs.push_back("-D_MT");
5074 CmdArgs.push_back("-flto-visibility-public-std");
5075 FlagForCRT = "--dependent-lib=libcmtd";
5076 break;
5077 default:
5078 llvm_unreachable("Unexpected option ID.");
5079 }
5080
5081 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5082 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5083 } else {
5084 CmdArgs.push_back(FlagForCRT.data());
5085
5086 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5087 // users want. The /Za flag to cl.exe turns this off, but it's not
5088 // implemented in clang.
5089 CmdArgs.push_back("--dependent-lib=oldnames");
5090 }
5091
5092 // SYCL: Add SYCL runtime library dependency
5093 // SYCL runtime is a required dependency similar to CRT, so we use
5094 // --dependent-lib to embed it in the object file metadata
5095 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5096 !Args.hasArg(options::OPT_nolibsycl) &&
5097 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5098
5099 // Determine debug vs release based on CRT flags
5100 bool IsDebugBuild = false;
5101
5102 // Check -fms-runtime-lib=dll_dbg
5103 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5104 StringRef RuntimeVal = A->getValue();
5105 if (RuntimeVal == "dll_dbg")
5106 IsDebugBuild = true;
5107 }
5108
5109 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5110 // overriding options (e.g., /MDd /MD -> /MD wins)
5111 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5112 if (A->getOption().matches(options::OPT__SLASH_MDd))
5113 IsDebugBuild = true;
5114 }
5115
5116 // Add appropriate SYCL runtime library dependency
5117 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5118 : "--dependent-lib=LLVMSYCL");
5119 }
5120
5121 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5122 // even if the file doesn't actually refer to any of the routines because
5123 // the CRT itself has incomplete dependency markings.
5124 if (TC.getTriple().isWindowsArm64EC())
5125 CmdArgs.push_back("--dependent-lib=softintrin");
5126}
5127
5129 const InputInfo &Output, const InputInfoList &Inputs,
5130 const ArgList &Args, const char *LinkingOutput) const {
5131 const auto &TC = getToolChain();
5132 const llvm::Triple &RawTriple = TC.getTriple();
5133 const llvm::Triple &Triple = TC.getEffectiveTriple();
5134 const std::string &TripleStr = Triple.getTriple();
5135
5136 bool KernelOrKext =
5137 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5138 const Driver &D = TC.getDriver();
5139 ArgStringList CmdArgs;
5140
5141 assert(Inputs.size() >= 1 && "Must have at least one input.");
5142 // CUDA/HIP compilation may have multiple inputs (source file + results of
5143 // device-side compilations). OpenMP device jobs also take the host IR as a
5144 // second input. Module precompilation accepts a list of header files to
5145 // include as part of the module. API extraction accepts a list of header
5146 // files whose API information is emitted in the output. All other jobs are
5147 // expected to have exactly one input. SYCL compilation only expects a
5148 // single input.
5149 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5150 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5151 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5152 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5153 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5154 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5155 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5156 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5157 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5159 bool IsHostOffloadingAction =
5162 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5163 Args.hasFlag(options::OPT_offload_new_driver,
5164 options::OPT_no_offload_new_driver,
5165 C.getActiveOffloadKinds() != Action::OFK_None));
5166
5167 bool IsRDCMode =
5168 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
5169
5170 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5171 bool IsUsingLTO = LTOMode != LTOK_None;
5172
5173 // Extract API doesn't have a main input file, so invent a fake one as a
5174 // placeholder.
5175 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5176 "extract-api");
5177
5178 const InputInfo &Input =
5179 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5180
5181 InputInfoList ExtractAPIInputs;
5182 InputInfoList HostOffloadingInputs;
5183 const InputInfo *CudaDeviceInput = nullptr;
5184 const InputInfo *OpenMPDeviceInput = nullptr;
5185 for (const InputInfo &I : Inputs) {
5186 if (&I == &Input || I.getType() == types::TY_Nothing) {
5187 // This is the primary input or contains nothing.
5188 } else if (IsExtractAPI) {
5189 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5190 if (I.getType() != ExpectedInputType) {
5191 D.Diag(diag::err_drv_extract_api_wrong_kind)
5192 << I.getFilename() << types::getTypeName(I.getType())
5193 << types::getTypeName(ExpectedInputType);
5194 }
5195 ExtractAPIInputs.push_back(I);
5196 } else if (IsHostOffloadingAction) {
5197 HostOffloadingInputs.push_back(I);
5198 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5199 CudaDeviceInput = &I;
5200 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5201 OpenMPDeviceInput = &I;
5202 } else {
5203 llvm_unreachable("unexpectedly given multiple inputs");
5204 }
5205 }
5206
5207 bool IsUEFI = RawTriple.isUEFI();
5208 bool IsIAMCU = RawTriple.isOSIAMCU();
5209
5210 // C++ is not supported for IAMCU.
5211 if (IsIAMCU && types::isCXX(Input.getType()))
5212 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5213
5214 // Invoke ourselves in -cc1 mode.
5215 //
5216 // FIXME: Implement custom jobs for internal actions.
5217 CmdArgs.push_back("-cc1");
5218
5219 // Add the "effective" target triple.
5220 CmdArgs.push_back("-triple");
5221 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5222
5223 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5224
5225 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5226 if (AuxTriple) {
5227 CmdArgs.push_back("-aux-triple");
5228 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5229
5230 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5231 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5232 // Windows), we need to pass Windows-specific flags to cc1.
5233 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5235 // Figure out the device side triple for the host-side compilation.
5236 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5237 ++I) {
5239 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5240 if (OffloadToolChains.first == OffloadToolChains.second)
5241 continue;
5242
5243 const llvm::Triple &DeviceAuxTriple =
5244 OffloadToolChains.first->second->getTriple();
5245 CmdArgs.push_back("-aux-triple");
5246 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5247 break;
5248 }
5249 }
5250
5251 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5252 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5253 Args.ClaimAllArgs(options::OPT_MJ);
5254 } else if (const Arg *GenCDBFragment =
5255 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5256 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5257 TripleStr, Output, Input, Args);
5258 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5259 }
5260
5261 if ((getToolChain().getTriple().isAMDGPU() ||
5262 (getToolChain().getTriple().isSPIRV() &&
5263 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5264 // Device side compilation printf
5265 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5266 CmdArgs.push_back(Args.MakeArgString(
5267 "-mprintf-kind=" +
5268 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5269 // Force compiler error on invalid conversion specifiers
5270 CmdArgs.push_back(
5271 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5272 }
5273 }
5274
5275 if (IsCuda && !IsCudaDevice) {
5276 // We need to figure out which CUDA version we're compiling for, as that
5277 // determines how we load and launch GPU kernels.
5278 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5279 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5280 assert(CTC && "Expected valid CUDA Toolchain.");
5281 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5282 CmdArgs.push_back(Args.MakeArgString(
5283 Twine("-target-sdk-version=") +
5284 CudaVersionToString(CTC->CudaInstallation.version())));
5285 }
5286
5287 // Optimization level for CodeGen.
5288 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5289 if (A->getOption().matches(options::OPT_O4)) {
5290 CmdArgs.push_back("-O3");
5291 D.Diag(diag::warn_O4_is_O3);
5292 } else {
5293 A->render(Args, CmdArgs);
5294 }
5295 }
5296
5297 // Unconditionally claim the printf option now to avoid unused diagnostic.
5298 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5299 PF->claim();
5300
5301 if (IsSYCL) {
5302 if (IsSYCLDevice) {
5303 // We want to compile sycl kernels.
5304 CmdArgs.push_back("-fsycl-is-device");
5305
5306 // Set O2 optimization level by default
5307 if (!Args.getLastArg(options::OPT_O_Group))
5308 CmdArgs.push_back("-O2");
5309 } else {
5310 // Add any options that are needed specific to SYCL offload while
5311 // performing the host side compilation.
5312
5313 // Let the front-end host compilation flow know about SYCL offload
5314 // compilation.
5315 CmdArgs.push_back("-fsycl-is-host");
5316 }
5317
5318 // Set options for both host and device.
5319 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5320 if (SYCLStdArg) {
5321 SYCLStdArg->render(Args, CmdArgs);
5322 } else {
5323 // Ensure the default version in SYCL mode is 2020.
5324 CmdArgs.push_back("-sycl-std=2020");
5325 }
5326 }
5327
5328 if (Args.hasArg(options::OPT_fclangir))
5329 CmdArgs.push_back("-fclangir");
5330
5331 if (IsOpenMPDevice) {
5332 // We have to pass the triple of the host if compiling for an OpenMP device.
5333 const llvm::Triple &HostTriple =
5334 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5335 CmdArgs.push_back("-aux-triple");
5336 CmdArgs.push_back(HostTriple.str().c_str());
5337 }
5338
5339 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5340 Triple.getArch() == llvm::Triple::thumb)) {
5341 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5342 unsigned Version = 0;
5343 bool Failure =
5344 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5345 if (Failure || Version < 7)
5346 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5347 << TripleStr;
5348 }
5349
5350 // Push all default warning arguments that are specific to
5351 // the given target. These come before user provided warning options
5352 // are provided.
5353 TC.addClangWarningOptions(CmdArgs);
5354
5355 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5356 if (Triple.isSPIR() || Triple.isSPIRV())
5357 CmdArgs.push_back("-Wspir-compat");
5358
5359 // Select the appropriate action.
5360 RewriteKind rewriteKind = RK_None;
5361
5362 bool UnifiedLTO = false;
5363 if (IsUsingLTO) {
5364 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5365 options::OPT_fno_unified_lto, Triple.isPS());
5366 if (UnifiedLTO)
5367 CmdArgs.push_back("-funified-lto");
5368 }
5369
5370 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5371 // it claims when not running an assembler. Otherwise, clang would emit
5372 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5373 // flags while debugging something. That'd be somewhat inconvenient, and it's
5374 // also inconsistent with most other flags -- we don't warn on
5375 // -ffunction-sections not being used in -E mode either for example, even
5376 // though it's not really used either.
5377 if (!isa<AssembleJobAction>(JA)) {
5378 // The args claimed here should match the args used in
5379 // CollectArgsForIntegratedAssembler().
5380 if (TC.useIntegratedAs()) {
5381 Args.ClaimAllArgs(options::OPT_mrelax_all);
5382 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5383 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5384 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5385 switch (C.getDefaultToolChain().getArch()) {
5386 case llvm::Triple::arm:
5387 case llvm::Triple::armeb:
5388 case llvm::Triple::thumb:
5389 case llvm::Triple::thumbeb:
5390 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5391 break;
5392 default:
5393 break;
5394 }
5395 }
5396 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5397 Args.ClaimAllArgs(options::OPT_Xassembler);
5398 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5399 }
5400
5401 bool IsAMDSPIRVForHIPDevice =
5402 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5403 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5404
5405 if (isa<AnalyzeJobAction>(JA)) {
5406 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5407 CmdArgs.push_back("-analyze");
5408 } else if (isa<PreprocessJobAction>(JA)) {
5409 if (Output.getType() == types::TY_Dependencies)
5410 CmdArgs.push_back("-Eonly");
5411 else {
5412 CmdArgs.push_back("-E");
5413 if (Args.hasArg(options::OPT_rewrite_objc) &&
5414 !Args.hasArg(options::OPT_g_Group))
5415 CmdArgs.push_back("-P");
5416 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5417 CmdArgs.push_back("-fdirectives-only");
5418 }
5419 } else if (isa<AssembleJobAction>(JA)) {
5420 CmdArgs.push_back("-emit-obj");
5421
5422 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5423
5424 // Also ignore explicit -force_cpusubtype_ALL option.
5425 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5426 } else if (isa<PrecompileJobAction>(JA)) {
5427 if (JA.getType() == types::TY_Nothing)
5428 CmdArgs.push_back("-fsyntax-only");
5429 else if (JA.getType() == types::TY_ModuleFile) {
5430 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5431 ((Input.getType() == types::TY_CXXStdModule ||
5432 Input.getType() == types::TY_PP_CXXStdModule) &&
5433 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5434 CmdArgs.push_back("-emit-reduced-module-interface");
5435 else
5436 CmdArgs.push_back("-emit-module-interface");
5437 } else if (JA.getType() == types::TY_HeaderUnit)
5438 CmdArgs.push_back("-emit-header-unit");
5439 else if (!Args.hasArg(options::OPT_ignore_pch))
5440 CmdArgs.push_back("-emit-pch");
5441 } else if (isa<VerifyPCHJobAction>(JA)) {
5442 CmdArgs.push_back("-verify-pch");
5443 } else if (isa<ExtractAPIJobAction>(JA)) {
5444 assert(JA.getType() == types::TY_API_INFO &&
5445 "Extract API actions must generate a API information.");
5446 CmdArgs.push_back("-extract-api");
5447
5448 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5449 PrettySGFArg->render(Args, CmdArgs);
5450
5451 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5452
5453 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5454 ProductNameArg->render(Args, CmdArgs);
5455 if (Arg *ExtractAPIIgnoresFileArg =
5456 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5457 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5458 if (Arg *EmitExtensionSymbolGraphs =
5459 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5460 if (!SymbolGraphDirArg)
5461 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5462
5463 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5464 }
5465 if (SymbolGraphDirArg)
5466 SymbolGraphDirArg->render(Args, CmdArgs);
5467 } else {
5468 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5469 "Invalid action for clang tool.");
5470 if (JA.getType() == types::TY_Nothing) {
5471 CmdArgs.push_back("-fsyntax-only");
5472 } else if (JA.getType() == types::TY_LLVM_IR ||
5473 JA.getType() == types::TY_LTO_IR) {
5474 CmdArgs.push_back("-emit-llvm");
5475 } else if (JA.getType() == types::TY_LLVM_BC ||
5476 JA.getType() == types::TY_LTO_BC) {
5477 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5478 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5479 Args.hasArg(options::OPT_emit_llvm)) {
5480 CmdArgs.push_back("-emit-llvm");
5481 } else {
5482 CmdArgs.push_back("-emit-llvm-bc");
5483 }
5484 } else if (JA.getType() == types::TY_IFS ||
5485 JA.getType() == types::TY_IFS_CPP) {
5486 StringRef ArgStr =
5487 Args.hasArg(options::OPT_interface_stub_version_EQ)
5488 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5489 : "ifs-v1";
5490 CmdArgs.push_back("-emit-interface-stubs");
5491 CmdArgs.push_back(
5492 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5493 } else if (JA.getType() == types::TY_PP_Asm) {
5494 CmdArgs.push_back("-S");
5495 } else if (JA.getType() == types::TY_AST) {
5496 if (!Args.hasArg(options::OPT_ignore_pch))
5497 CmdArgs.push_back("-emit-pch");
5498 } else if (JA.getType() == types::TY_ModuleFile) {
5499 CmdArgs.push_back("-module-file-info");
5500 } else if (JA.getType() == types::TY_RewrittenObjC) {
5501 CmdArgs.push_back("-rewrite-objc");
5502 rewriteKind = RK_NonFragile;
5503 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5504 CmdArgs.push_back("-rewrite-objc");
5505 rewriteKind = RK_Fragile;
5506 } else if (JA.getType() == types::TY_CIR) {
5507 CmdArgs.push_back("-emit-cir");
5508 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5509 CmdArgs.push_back("-emit-obj");
5510 } else {
5511 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5512 }
5513
5514 // Preserve use-list order by default when emitting bitcode, so that
5515 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5516 // same result as running passes here. For LTO, we don't need to preserve
5517 // the use-list order, since serialization to bitcode is part of the flow.
5518 if (JA.getType() == types::TY_LLVM_BC)
5519 CmdArgs.push_back("-emit-llvm-uselists");
5520
5521 if (IsUsingLTO) {
5522 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5523 options::OPT_foffload_lto_EQ);
5524 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5525 !Args.hasFlag(options::OPT_offload_new_driver,
5526 options::OPT_no_offload_new_driver,
5527 C.getActiveOffloadKinds() != Action::OFK_None) &&
5528 !Triple.isAMDGPU() && !Triple.isSPIRV()) {
5529 D.Diag(diag::err_drv_unsupported_opt_for_target)
5530 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5531 << Triple.getTriple();
5532 } else if (Triple.isNVPTX() && !IsRDCMode &&
5534 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5535 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5536 << "-fno-gpu-rdc";
5537 } else {
5538 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5539 CmdArgs.push_back(Args.MakeArgString(
5540 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5541 // PS4 uses the legacy LTO API, which does not support some of the
5542 // features enabled by -flto-unit.
5543 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5544 CmdArgs.push_back("-flto-unit");
5545 }
5546 }
5547 }
5548
5549 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5550
5551 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5552 if (!types::isLLVMIR(Input.getType()))
5553 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5554 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5555 }
5556
5557 if (Triple.isPPC())
5558 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5559 options::OPT_mno_regnames);
5560
5561 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5562 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5563
5564 if (Args.getLastArg(options::OPT_save_temps_EQ))
5565 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5566
5567 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5568 options::OPT_fmemory_profile_EQ,
5569 options::OPT_fno_memory_profile);
5570 if (MemProfArg &&
5571 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5572 MemProfArg->render(Args, CmdArgs);
5573
5574 if (auto *MemProfUseArg =
5575 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5576 if (MemProfArg)
5577 D.Diag(diag::err_drv_argument_not_allowed_with)
5578 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5579 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5580 options::OPT_fprofile_generate_EQ))
5581 D.Diag(diag::err_drv_argument_not_allowed_with)
5582 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5583 MemProfUseArg->render(Args, CmdArgs);
5584 }
5585
5586 // Embed-bitcode option.
5587 // Only white-listed flags below are allowed to be embedded.
5588 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5590 // Add flags implied by -fembed-bitcode.
5591 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5592 // Disable all llvm IR level optimizations.
5593 CmdArgs.push_back("-disable-llvm-passes");
5594
5595 // Render target options.
5596 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5598
5599 // reject options that shouldn't be supported in bitcode
5600 // also reject kernel/kext
5601 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5602 options::OPT_mkernel,
5603 options::OPT_fapple_kext,
5604 options::OPT_ffunction_sections,
5605 options::OPT_fno_function_sections,
5606 options::OPT_fdata_sections,
5607 options::OPT_fno_data_sections,
5608 options::OPT_fbasic_block_sections_EQ,
5609 options::OPT_funique_internal_linkage_names,
5610 options::OPT_fno_unique_internal_linkage_names,
5611 options::OPT_funique_section_names,
5612 options::OPT_fno_unique_section_names,
5613 options::OPT_funique_basic_block_section_names,
5614 options::OPT_fno_unique_basic_block_section_names,
5615 options::OPT_mrestrict_it,
5616 options::OPT_mno_restrict_it,
5617 options::OPT_mstackrealign,
5618 options::OPT_mno_stackrealign,
5619 options::OPT_mstack_alignment,
5620 options::OPT_mcmodel_EQ,
5621 options::OPT_mlong_calls,
5622 options::OPT_mno_long_calls,
5623 options::OPT_ggnu_pubnames,
5624 options::OPT_gdwarf_aranges,
5625 options::OPT_fdebug_types_section,
5626 options::OPT_fno_debug_types_section,
5627 options::OPT_fdwarf_directory_asm,
5628 options::OPT_fno_dwarf_directory_asm,
5629 options::OPT_mrelax_all,
5630 options::OPT_mno_relax_all,
5631 options::OPT_ftrap_function_EQ,
5632 options::OPT_ffixed_r9,
5633 options::OPT_mfix_cortex_a53_835769,
5634 options::OPT_mno_fix_cortex_a53_835769,
5635 options::OPT_ffixed_x18,
5636 options::OPT_mglobal_merge,
5637 options::OPT_mno_global_merge,
5638 options::OPT_mred_zone,
5639 options::OPT_mno_red_zone,
5640 options::OPT_Wa_COMMA,
5641 options::OPT_Xassembler,
5642 options::OPT_mllvm,
5643 options::OPT_mmlir,
5644 };
5645 for (const auto &A : Args)
5646 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5647 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5648
5649 // Render the CodeGen options that need to be passed.
5650 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5651 options::OPT_fno_optimize_sibling_calls);
5652
5654 CmdArgs, JA);
5655
5656 // Render ABI arguments
5657 switch (TC.getArch()) {
5658 default: break;
5659 case llvm::Triple::arm:
5660 case llvm::Triple::armeb:
5661 case llvm::Triple::thumbeb:
5662 RenderARMABI(D, Triple, Args, CmdArgs);
5663 break;
5664 case llvm::Triple::aarch64:
5665 case llvm::Triple::aarch64_32:
5666 case llvm::Triple::aarch64_be:
5667 RenderAArch64ABI(Triple, Args, CmdArgs);
5668 break;
5669 }
5670
5671 // Input/Output file.
5672 if (Output.getType() == types::TY_Dependencies) {
5673 // Handled with other dependency code.
5674 } else if (Output.isFilename()) {
5675 CmdArgs.push_back("-o");
5676 CmdArgs.push_back(Output.getFilename());
5677 } else {
5678 assert(Output.isNothing() && "Input output.");
5679 }
5680
5681 for (const auto &II : Inputs) {
5682 addDashXForInput(Args, II, CmdArgs);
5683 if (II.isFilename())
5684 CmdArgs.push_back(II.getFilename());
5685 else
5686 II.getInputArg().renderAsInput(Args, CmdArgs);
5687 }
5688
5689 C.addCommand(std::make_unique<Command>(
5691 CmdArgs, Inputs, Output, D.getPrependArg()));
5692 return;
5693 }
5694
5695 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5696 CmdArgs.push_back("-fembed-bitcode=marker");
5697
5698 // We normally speed up the clang process a bit by skipping destructors at
5699 // exit, but when we're generating diagnostics we can rely on some of the
5700 // cleanup.
5701 if (!C.isForDiagnostics())
5702 CmdArgs.push_back("-disable-free");
5703 CmdArgs.push_back("-clear-ast-before-backend");
5704
5705#ifdef NDEBUG
5706 const bool IsAssertBuild = false;
5707#else
5708 const bool IsAssertBuild = true;
5709#endif
5710
5711 // Disable the verification pass in no-asserts builds unless otherwise
5712 // specified.
5713 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5714 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5715 CmdArgs.push_back("-disable-llvm-verifier");
5716 }
5717
5718 // Discard value names in no-asserts builds unless otherwise specified.
5719 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5720 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5721 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5722 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5723 return types::isLLVMIR(II.getType());
5724 })) {
5725 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5726 }
5727 CmdArgs.push_back("-discard-value-names");
5728 }
5729
5730 // Set the main file name, so that debug info works even with
5731 // -save-temps.
5732 CmdArgs.push_back("-main-file-name");
5733 CmdArgs.push_back(getBaseInputName(Args, Input));
5734
5735 // Some flags which affect the language (via preprocessor
5736 // defines).
5737 if (Args.hasArg(options::OPT_static))
5738 CmdArgs.push_back("-static-define");
5739
5740 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5741
5742 if (Args.hasArg(options::OPT_municode))
5743 CmdArgs.push_back("-DUNICODE");
5744
5745 if (isa<AnalyzeJobAction>(JA))
5746 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5747
5748 if (isa<AnalyzeJobAction>(JA) ||
5749 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5750 CmdArgs.push_back("-setup-static-analyzer");
5751
5752 // Enable compatilibily mode to avoid analyzer-config related errors.
5753 // Since we can't access frontend flags through hasArg, let's manually iterate
5754 // through them.
5755 bool FoundAnalyzerConfig = false;
5756 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5757 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5758 FoundAnalyzerConfig = true;
5759 break;
5760 }
5761 if (!FoundAnalyzerConfig)
5762 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5763 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5764 FoundAnalyzerConfig = true;
5765 break;
5766 }
5767 if (FoundAnalyzerConfig)
5768 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5769
5771
5772 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5773 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5774 if (FunctionAlignment) {
5775 CmdArgs.push_back("-function-alignment");
5776 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5777 }
5778
5779 if (const Arg *A =
5780 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5781 unsigned Value = 0;
5782 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5783 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5784 << A->getAsString(Args) << A->getValue();
5785 else if (!llvm::isPowerOf2_32(Value))
5786 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5787 << A->getAsString(Args) << A->getValue();
5788
5789 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5790 Twine(std::min(Value, 65536u))));
5791 }
5792
5793 // We support -falign-loops=N where N is a power of 2. GCC supports more
5794 // forms.
5795 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5796 unsigned Value = 0;
5797 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5798 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5799 << A->getAsString(Args) << A->getValue();
5800 else if (Value & (Value - 1))
5801 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5802 << A->getAsString(Args) << A->getValue();
5803 // Treat =0 as unspecified (use the target preference).
5804 if (Value)
5805 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5806 Twine(std::min(Value, 65536u))));
5807 }
5808
5809 if (Triple.isOSzOS()) {
5810 // On z/OS some of the system header feature macros need to
5811 // be defined to enable most cross platform projects to build
5812 // successfully. Ths include the libc++ library. A
5813 // complicating factor is that users can define these
5814 // macros to the same or different values. We need to add
5815 // the definition for these macros to the compilation command
5816 // if the user hasn't already defined them.
5817
5818 auto findMacroDefinition = [&](const std::string &Macro) {
5819 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5820 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5821 return M == Macro || M.find(Macro + '=') != std::string::npos;
5822 });
5823 };
5824
5825 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5826 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5827 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5828 // _OPEN_DEFAULT is required for XL compat
5829 if (!findMacroDefinition("_OPEN_DEFAULT"))
5830 CmdArgs.push_back("-D_OPEN_DEFAULT");
5831 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5832 // _XOPEN_SOURCE=600 is required for libcxx.
5833 if (!findMacroDefinition("_XOPEN_SOURCE"))
5834 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5835 }
5836 }
5837
5838 llvm::Reloc::Model RelocationModel;
5839 unsigned PICLevel;
5840 bool IsPIE;
5841 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5842 Arg *LastPICDataRelArg =
5843 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5844 options::OPT_mpic_data_is_text_relative);
5845 bool NoPICDataIsTextRelative = false;
5846 if (LastPICDataRelArg) {
5847 if (LastPICDataRelArg->getOption().matches(
5848 options::OPT_mno_pic_data_is_text_relative)) {
5849 NoPICDataIsTextRelative = true;
5850 if (!PICLevel)
5851 D.Diag(diag::err_drv_argument_only_allowed_with)
5852 << "-mno-pic-data-is-text-relative"
5853 << "-fpic/-fpie";
5854 }
5855 if (!Triple.isSystemZ())
5856 D.Diag(diag::err_drv_unsupported_opt_for_target)
5857 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5858 : "-mpic-data-is-text-relative")
5859 << RawTriple.str();
5860 }
5861
5862 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5863 RelocationModel == llvm::Reloc::ROPI_RWPI;
5864 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5865 RelocationModel == llvm::Reloc::ROPI_RWPI;
5866
5867 if (Args.hasArg(options::OPT_mcmse) &&
5868 !Args.hasArg(options::OPT_fallow_unsupported)) {
5869 if (IsROPI)
5870 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5871 if (IsRWPI)
5872 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5873 }
5874
5875 if (IsROPI && types::isCXX(Input.getType()) &&
5876 !Args.hasArg(options::OPT_fallow_unsupported))
5877 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5878
5879 const char *RMName = RelocationModelName(RelocationModel);
5880 if (RMName) {
5881 CmdArgs.push_back("-mrelocation-model");
5882 CmdArgs.push_back(RMName);
5883 }
5884 if (PICLevel > 0) {
5885 CmdArgs.push_back("-pic-level");
5886 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5887 if (IsPIE)
5888 CmdArgs.push_back("-pic-is-pie");
5889 if (NoPICDataIsTextRelative)
5890 CmdArgs.push_back("-mcmodel=medium");
5891 }
5892
5893 if (RelocationModel == llvm::Reloc::ROPI ||
5894 RelocationModel == llvm::Reloc::ROPI_RWPI)
5895 CmdArgs.push_back("-fropi");
5896 if (RelocationModel == llvm::Reloc::RWPI ||
5897 RelocationModel == llvm::Reloc::ROPI_RWPI)
5898 CmdArgs.push_back("-frwpi");
5899
5900 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5901 CmdArgs.push_back("-meabi");
5902 CmdArgs.push_back(A->getValue());
5903 }
5904
5905 // -fsemantic-interposition is forwarded to CC1: set the
5906 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5907 // make default visibility external linkage definitions dso_preemptable.
5908 //
5909 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5910 // aliases (make default visibility external linkage definitions dso_local).
5911 // This is the CC1 default for ELF to match COFF/Mach-O.
5912 //
5913 // Otherwise use Clang's traditional behavior: like
5914 // -fno-semantic-interposition but local aliases are not used. So references
5915 // can be interposed if not optimized out.
5916 if (Triple.isOSBinFormatELF()) {
5917 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5918 options::OPT_fno_semantic_interposition);
5919 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5920 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5921 bool SupportsLocalAlias =
5922 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5923 if (!A)
5924 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5925 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5926 A->render(Args, CmdArgs);
5927 else if (!SupportsLocalAlias)
5928 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5929 }
5930 }
5931
5932 {
5933 std::string Model;
5934 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5935 if (!TC.isThreadModelSupported(A->getValue()))
5936 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5937 << A->getValue() << A->getAsString(Args);
5938 Model = A->getValue();
5939 } else
5940 Model = TC.getThreadModel();
5941 if (Model != "posix") {
5942 CmdArgs.push_back("-mthread-model");
5943 CmdArgs.push_back(Args.MakeArgString(Model));
5944 }
5945 }
5946
5947 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5948 StringRef Name = A->getValue();
5949 if (Name == "SVML") {
5950 if (Triple.getArch() != llvm::Triple::x86 &&
5951 Triple.getArch() != llvm::Triple::x86_64)
5952 D.Diag(diag::err_drv_unsupported_opt_for_target)
5953 << Name << Triple.getArchName();
5954 } else if (Name == "AMDLIBM") {
5955 if (Triple.getArch() != llvm::Triple::x86 &&
5956 Triple.getArch() != llvm::Triple::x86_64)
5957 D.Diag(diag::err_drv_unsupported_opt_for_target)
5958 << Name << Triple.getArchName();
5959 } else if (Name == "libmvec") {
5960 if (Triple.getArch() != llvm::Triple::x86 &&
5961 Triple.getArch() != llvm::Triple::x86_64 &&
5962 Triple.getArch() != llvm::Triple::aarch64 &&
5963 Triple.getArch() != llvm::Triple::aarch64_be)
5964 D.Diag(diag::err_drv_unsupported_opt_for_target)
5965 << Name << Triple.getArchName();
5966 } else if (Name == "SLEEF" || Name == "ArmPL") {
5967 if (Triple.getArch() != llvm::Triple::aarch64 &&
5968 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5969 D.Diag(diag::err_drv_unsupported_opt_for_target)
5970 << Name << Triple.getArchName();
5971 }
5972 A->render(Args, CmdArgs);
5973 }
5974
5975 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5976 options::OPT_fno_merge_all_constants, false))
5977 CmdArgs.push_back("-fmerge-all-constants");
5978
5979 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5980 options::OPT_fno_delete_null_pointer_checks);
5981
5982 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
5983 options::OPT_fno_lifetime_dse);
5984
5985 // LLVM Code Generator Options.
5986
5987 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5988 if (!Triple.isOSAIX() || Triple.isPPC32())
5989 D.Diag(diag::err_drv_unsupported_opt_for_target)
5990 << A->getSpelling() << RawTriple.str();
5991 CmdArgs.push_back("-mabi=quadword-atomics");
5992 }
5993
5994 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5995 // Emit the unsupported option error until the Clang's library integration
5996 // support for 128-bit long double is available for AIX.
5997 if (Triple.isOSAIX())
5998 D.Diag(diag::err_drv_unsupported_opt_for_target)
5999 << A->getSpelling() << RawTriple.str();
6000 }
6001
6002 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6003 StringRef V = A->getValue(), V1 = V;
6004 unsigned Size;
6005 if (V1.consumeInteger(10, Size) || !V1.empty())
6006 D.Diag(diag::err_drv_invalid_argument_to_option)
6007 << V << A->getOption().getName();
6008 else
6009 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6010 }
6011
6012 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6013 options::OPT_fno_jump_tables);
6014 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6015 options::OPT_fno_profile_sample_accurate);
6016 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6017 options::OPT_fno_preserve_as_comments);
6018
6019 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6020 CmdArgs.push_back("-mregparm");
6021 CmdArgs.push_back(A->getValue());
6022 }
6023
6024 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6025 options::OPT_msvr4_struct_return)) {
6026 if (!TC.getTriple().isPPC32()) {
6027 D.Diag(diag::err_drv_unsupported_opt_for_target)
6028 << A->getSpelling() << RawTriple.str();
6029 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6030 CmdArgs.push_back("-maix-struct-return");
6031 } else {
6032 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6033 CmdArgs.push_back("-msvr4-struct-return");
6034 }
6035 }
6036
6037 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6038 options::OPT_freg_struct_return)) {
6039 if (TC.getArch() != llvm::Triple::x86) {
6040 D.Diag(diag::err_drv_unsupported_opt_for_target)
6041 << A->getSpelling() << RawTriple.str();
6042 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6043 CmdArgs.push_back("-fpcc-struct-return");
6044 } else {
6045 assert(A->getOption().matches(options::OPT_freg_struct_return));
6046 CmdArgs.push_back("-freg-struct-return");
6047 }
6048 }
6049
6050 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6051 if (Triple.getArch() == llvm::Triple::m68k)
6052 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6053 else
6054 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6055 }
6056
6057 if (Args.hasArg(options::OPT_fenable_matrix)) {
6058 // enable-matrix is needed by both the LangOpts and by LLVM.
6059 CmdArgs.push_back("-fenable-matrix");
6060 CmdArgs.push_back("-mllvm");
6061 CmdArgs.push_back("-enable-matrix");
6062 // Only handle default layout if matrix is enabled
6063 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6064 StringRef Val = A->getValue();
6065 if (Val == "row-major" || Val == "column-major") {
6066 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6067 CmdArgs.push_back("-mllvm");
6068 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6069
6070 } else {
6071 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6072 }
6073 }
6074 }
6075
6077 getFramePointerKind(Args, RawTriple);
6078 const char *FPKeepKindStr = nullptr;
6079 switch (FPKeepKind) {
6081 FPKeepKindStr = "-mframe-pointer=none";
6082 break;
6084 FPKeepKindStr = "-mframe-pointer=reserved";
6085 break;
6087 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6088 break;
6090 FPKeepKindStr = "-mframe-pointer=non-leaf";
6091 break;
6093 FPKeepKindStr = "-mframe-pointer=all";
6094 break;
6095 }
6096 assert(FPKeepKindStr && "unknown FramePointerKind");
6097 CmdArgs.push_back(FPKeepKindStr);
6098
6099 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6100 options::OPT_fno_zero_initialized_in_bss);
6101
6102 bool OFastEnabled = isOptimizationLevelFast(Args);
6103 if (Args.hasArg(options::OPT_Ofast))
6104 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6105 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6106 // enabled. This alias option is being used to simplify the hasFlag logic.
6107 OptSpecifier StrictAliasingAliasOption =
6108 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6109 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6110 // doesn't do any TBAA.
6111 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6112 options::OPT_fno_strict_aliasing,
6113 !IsWindowsMSVC && !IsUEFI))
6114 CmdArgs.push_back("-relaxed-aliasing");
6115 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6116 false))
6117 CmdArgs.push_back("-no-pointer-tbaa");
6118 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6119 options::OPT_fno_struct_path_tbaa, true))
6120 CmdArgs.push_back("-no-struct-path-tbaa");
6121
6122 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6123 options::OPT_fno_strict_bool,
6124 options::OPT_fno_strict_bool_EQ)) {
6125 StringRef BFM = "";
6126 if (A->getOption().matches(options::OPT_fstrict_bool))
6127 BFM = "strict";
6128 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6129 BFM = "nonstrict";
6130 else if (A->getValue() == StringRef("truncate"))
6131 BFM = "truncate";
6132 else if (A->getValue() == StringRef("nonzero"))
6133 BFM = "nonzero";
6134 else
6135 D.Diag(diag::err_drv_invalid_value)
6136 << A->getAsString(Args) << A->getValue();
6137 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6138 } else if (KernelOrKext) {
6139 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6140 CmdArgs.push_back("-load-bool-from-mem=truncate");
6141 }
6142
6143 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6144 options::OPT_fno_strict_enums);
6145 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6146 options::OPT_fno_strict_return);
6147 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6148 options::OPT_fno_allow_editor_placeholders);
6149 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6150 options::OPT_fno_strict_vtable_pointers);
6151 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6152 options::OPT_fno_force_emit_vtables);
6153 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6154 options::OPT_fno_optimize_sibling_calls);
6155 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6156 options::OPT_fno_escaping_block_tail_calls);
6157
6158 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6159 options::OPT_fno_fine_grained_bitfield_accesses);
6160
6161 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6162 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6163
6164 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6165 options::OPT_fno_experimental_omit_vtable_rtti);
6166
6167 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6168 options::OPT_fno_disable_block_signature_string);
6169
6170 // Handle segmented stacks.
6171 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6172 options::OPT_fno_split_stack);
6173
6174 // -fprotect-parens=0 is default.
6175 if (Args.hasFlag(options::OPT_fprotect_parens,
6176 options::OPT_fno_protect_parens, false))
6177 CmdArgs.push_back("-fprotect-parens");
6178
6179 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6180
6181 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6182 options::OPT_fno_atomic_remote_memory);
6183 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6184 options::OPT_fno_atomic_fine_grained_memory);
6185 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6186 options::OPT_fno_atomic_ignore_denormal_mode);
6187
6188 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6189 const llvm::Triple::ArchType Arch = TC.getArch();
6190 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6191 StringRef V = A->getValue();
6192 if (V == "64")
6193 CmdArgs.push_back("-fextend-arguments=64");
6194 else if (V != "32")
6195 D.Diag(diag::err_drv_invalid_argument_to_option)
6196 << A->getValue() << A->getOption().getName();
6197 } else
6198 D.Diag(diag::err_drv_unsupported_opt_for_target)
6199 << A->getOption().getName() << TripleStr;
6200 }
6201
6202 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6203 if (TC.getArch() == llvm::Triple::avr)
6204 A->render(Args, CmdArgs);
6205 else
6206 D.Diag(diag::err_drv_unsupported_opt_for_target)
6207 << A->getAsString(Args) << TripleStr;
6208 }
6209
6210 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6211 if (TC.getTriple().isX86())
6212 A->render(Args, CmdArgs);
6213 else if (TC.getTriple().isPPC() &&
6214 (A->getOption().getID() != options::OPT_mlong_double_80))
6215 A->render(Args, CmdArgs);
6216 else
6217 D.Diag(diag::err_drv_unsupported_opt_for_target)
6218 << A->getAsString(Args) << TripleStr;
6219 }
6220
6221 // Decide whether to use verbose asm. Verbose assembly is the default on
6222 // toolchains which have the integrated assembler on by default.
6223 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6224 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6225 IsIntegratedAssemblerDefault))
6226 CmdArgs.push_back("-fno-verbose-asm");
6227
6228 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6229 // use that to indicate the MC default in the backend.
6230 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6231 StringRef V = A->getValue();
6232 unsigned Num;
6233 if (V == "none")
6234 A->render(Args, CmdArgs);
6235 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6236 (V.empty() || (V.consume_front(".") &&
6237 !V.consumeInteger(10, Num) && V.empty())))
6238 A->render(Args, CmdArgs);
6239 else
6240 D.Diag(diag::err_drv_invalid_argument_to_option)
6241 << A->getValue() << A->getOption().getName();
6242 }
6243
6244 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6245 // option to disable integrated-as explicitly.
6247 CmdArgs.push_back("-no-integrated-as");
6248
6249 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6250 CmdArgs.push_back("-mdebug-pass");
6251 CmdArgs.push_back("Structure");
6252 }
6253 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6254 CmdArgs.push_back("-mdebug-pass");
6255 CmdArgs.push_back("Arguments");
6256 }
6257
6258 // Enable -mconstructor-aliases except on darwin, where we have to work around
6259 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6260 // code, where aliases aren't supported.
6261 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6262 CmdArgs.push_back("-mconstructor-aliases");
6263
6264 // Darwin's kernel doesn't support guard variables; just die if we
6265 // try to use them.
6266 if (KernelOrKext && RawTriple.isOSDarwin())
6267 CmdArgs.push_back("-fforbid-guard-variables");
6268
6269 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6270 options::OPT_mno_ms_bitfields)) {
6271 if (A->getOption().matches(options::OPT_mms_bitfields))
6272 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6273 else
6274 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6275 }
6276
6277 if (Triple.isOSCygMing()) {
6278 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6279 options::OPT_fno_auto_import);
6280 }
6281
6282 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6283 Triple.isX86() && IsWindowsMSVC))
6284 CmdArgs.push_back("-fms-volatile");
6285
6286 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6287 // defaults to -fno-direct-access-external-data. Pass the option if different
6288 // from the default.
6289 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6290 options::OPT_fno_direct_access_external_data)) {
6291 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6292 (PICLevel == 0))
6293 A->render(Args, CmdArgs);
6294 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6295 // Some targets default to -fno-direct-access-external-data even for
6296 // -fno-pic.
6297 CmdArgs.push_back("-fno-direct-access-external-data");
6298 }
6299
6300 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6301 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6302
6303 // -fhosted is default.
6304 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6305 // use Freestanding.
6306 bool Freestanding =
6307 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6308 KernelOrKext;
6309 if (Freestanding)
6310 CmdArgs.push_back("-ffreestanding");
6311
6312 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6313
6315 auto SanitizeArgs =
6317 Args.AddLastArg(CmdArgs,
6318 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6319
6320 // This is a coarse approximation of what llvm-gcc actually does, both
6321 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6322 // complicated ways.
6323 bool IsAsyncUnwindTablesDefault =
6325 bool IsSyncUnwindTablesDefault =
6327
6328 bool AsyncUnwindTables = Args.hasFlag(
6329 options::OPT_fasynchronous_unwind_tables,
6330 options::OPT_fno_asynchronous_unwind_tables,
6331 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6332 !Freestanding);
6333 bool UnwindTables =
6334 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6335 IsSyncUnwindTablesDefault && !Freestanding);
6336 if (AsyncUnwindTables)
6337 CmdArgs.push_back("-funwind-tables=2");
6338 else if (UnwindTables)
6339 CmdArgs.push_back("-funwind-tables=1");
6340
6341 // Sframe unwind tables are independent of the other types. Although also
6342 // defined for aarch64, only x86_64 support is implemented at the moment.
6343 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6344 if (Triple.isOSBinFormatELF() && Triple.isX86())
6345 CmdArgs.push_back("--gsframe");
6346 else
6347 D.Diag(diag::err_drv_unsupported_opt_for_target)
6348 << A->getOption().getName() << TripleStr;
6349 }
6350
6351 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6352 // `--gpu-use-aux-triple-only` is specified.
6353 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6354 const ArgList &HostArgs =
6355 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6356 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6357 if (!HostCPU.empty()) {
6358 CmdArgs.push_back("-aux-target-cpu");
6359 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6360 }
6361 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6362 /*ForAS*/ false, /*IsAux*/ true);
6363 }
6364
6365 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6367
6368 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6369
6370 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6371 StringRef Value = A->getValue();
6372 unsigned TLSSize = 0;
6373 Value.getAsInteger(10, TLSSize);
6374 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6375 D.Diag(diag::err_drv_unsupported_opt_for_target)
6376 << A->getOption().getName() << TripleStr;
6377 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6378 D.Diag(diag::err_drv_invalid_int_value)
6379 << A->getOption().getName() << Value;
6380 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6381 }
6382
6383 if (isTLSDESCEnabled(TC, Args))
6384 CmdArgs.push_back("-enable-tlsdesc");
6385
6386 // Add the target cpu
6387 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6388 if (!CPU.empty()) {
6389 CmdArgs.push_back("-target-cpu");
6390 CmdArgs.push_back(Args.MakeArgString(CPU));
6391 }
6392
6393 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6394
6395 // Add clang-cl arguments.
6396 types::ID InputType = Input.getType();
6397 if (D.IsCLMode())
6398 AddClangCLArgs(Args, InputType, CmdArgs);
6399
6400 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6401 llvm::codegenoptions::NoDebugInfo;
6403 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6404 DebugInfoKind, DwarfFission);
6405
6406 // Add the split debug info name to the command lines here so we
6407 // can propagate it to the backend.
6408 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6409 (TC.getTriple().isOSBinFormatELF() ||
6410 TC.getTriple().isOSBinFormatWasm() ||
6411 TC.getTriple().isOSBinFormatCOFF()) &&
6414 if (SplitDWARF) {
6415 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6416 CmdArgs.push_back("-split-dwarf-file");
6417 CmdArgs.push_back(SplitDWARFOut);
6418 if (DwarfFission == DwarfFissionKind::Split) {
6419 CmdArgs.push_back("-split-dwarf-output");
6420 CmdArgs.push_back(SplitDWARFOut);
6421 }
6422 }
6423
6424 // Pass the linker version in use.
6425 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6426 CmdArgs.push_back("-target-linker-version");
6427 CmdArgs.push_back(A->getValue());
6428 }
6429
6430 // Explicitly error on some things we know we don't support and can't just
6431 // ignore.
6432 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6433 Arg *Unsupported;
6434 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6435 TC.getArch() == llvm::Triple::x86) {
6436 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6437 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6438 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6439 << Unsupported->getOption().getName();
6440 }
6441 // The faltivec option has been superseded by the maltivec option.
6442 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6443 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6444 << Unsupported->getOption().getName()
6445 << "please use -maltivec and include altivec.h explicitly";
6446 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6447 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6448 << Unsupported->getOption().getName() << "please use -mno-altivec";
6449 }
6450
6451 Args.AddAllArgs(CmdArgs, options::OPT_v);
6452
6453 if (Args.getLastArg(options::OPT_H)) {
6454 CmdArgs.push_back("-H");
6455 CmdArgs.push_back("-sys-header-deps");
6456 }
6457 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6458
6460 CmdArgs.push_back("-header-include-file");
6461 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6462 ? D.CCPrintHeadersFilename.c_str()
6463 : "-");
6464 CmdArgs.push_back("-sys-header-deps");
6465 CmdArgs.push_back(Args.MakeArgString(
6466 "-header-include-format=" +
6468 CmdArgs.push_back(Args.MakeArgString(
6469 "-header-include-filtering=" +
6471 }
6472 Args.AddLastArg(CmdArgs, options::OPT_P);
6473 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6474
6475 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6476 CmdArgs.push_back("-diagnostic-log-file");
6477 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6478 ? D.CCLogDiagnosticsFilename.c_str()
6479 : "-");
6480 }
6481
6482 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6483 // crashes.
6484 if (D.CCGenDiagnostics)
6485 CmdArgs.push_back("-disable-pragma-debug-crash");
6486
6487 // Allow backend to put its diagnostic files in the same place as frontend
6488 // crash diagnostics files.
6489 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6490 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6491 CmdArgs.push_back("-mllvm");
6492 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6493 }
6494
6495 addSeparateSectionFlags(Triple, Args, CmdArgs);
6496
6497 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6498 options::OPT_fno_basic_block_address_map)) {
6499 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6500 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6501 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6502 A->render(Args, CmdArgs);
6503 } else {
6504 D.Diag(diag::err_drv_unsupported_opt_for_target)
6505 << A->getAsString(Args) << TripleStr;
6506 }
6507 }
6508
6509 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6510 StringRef Val = A->getValue();
6511 if (Val == "labels") {
6512 D.Diag(diag::warn_drv_deprecated_arg)
6513 << A->getAsString(Args) << /*hasReplacement=*/true
6514 << "-fbasic-block-address-map";
6515 CmdArgs.push_back("-fbasic-block-address-map");
6516 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6517 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6518 D.Diag(diag::err_drv_invalid_value)
6519 << A->getAsString(Args) << A->getValue();
6520 else
6521 A->render(Args, CmdArgs);
6522 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6523 // "all" is not supported on AArch64 since branch relaxation creates new
6524 // basic blocks for some cross-section branches.
6525 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6526 D.Diag(diag::err_drv_invalid_value)
6527 << A->getAsString(Args) << A->getValue();
6528 else
6529 A->render(Args, CmdArgs);
6530 } else if (Triple.isNVPTX()) {
6531 // Do not pass the option to the GPU compilation. We still want it enabled
6532 // for the host-side compilation, so seeing it here is not an error.
6533 } else if (Val != "none") {
6534 // =none is allowed everywhere. It's useful for overriding the option
6535 // and is the same as not specifying the option.
6536 D.Diag(diag::err_drv_unsupported_opt_for_target)
6537 << A->getAsString(Args) << TripleStr;
6538 }
6539 }
6540
6541 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6542 options::OPT_fno_unique_section_names);
6543 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6544 options::OPT_fno_separate_named_sections);
6545 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6546 options::OPT_fno_unique_internal_linkage_names);
6547 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6548 options::OPT_fno_unique_basic_block_section_names);
6549
6550 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6551 options::OPT_fno_split_machine_functions)) {
6552 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6553 // This codegen pass is only available on x86 and AArch64 ELF targets.
6554 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6555 A->render(Args, CmdArgs);
6556 else
6557 D.Diag(diag::err_drv_unsupported_opt_for_target)
6558 << A->getAsString(Args) << TripleStr;
6559 }
6560 }
6561
6562 if (Arg *A =
6563 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6564 options::OPT_fno_partition_static_data_sections)) {
6565 if (!A->getOption().matches(
6566 options::OPT_fno_partition_static_data_sections)) {
6567 // This codegen pass is only available on x86 and AArch64 ELF targets.
6568 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6569 A->render(Args, CmdArgs);
6570 CmdArgs.push_back("-mllvm");
6571 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6572 } else
6573 D.Diag(diag::err_drv_unsupported_opt_for_target)
6574 << A->getAsString(Args) << TripleStr;
6575 }
6576 }
6577
6578 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6579 options::OPT_finstrument_functions_after_inlining,
6580 options::OPT_finstrument_function_entry_bare);
6581 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6582 options::OPT_fno_convergent_functions);
6583
6584 // NVPTX doesn't support PGO or coverage
6585 if (!Triple.isNVPTX())
6586 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6587
6588 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6589
6590 if (getLastProfileSampleUseArg(Args) &&
6591 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6592 options::OPT_fno_sample_profile_use_profi, true)) {
6593 CmdArgs.push_back("-mllvm");
6594 CmdArgs.push_back("-sample-profile-use-profi");
6595 }
6596
6597 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6598 if (RawTriple.isPS() &&
6599 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6600 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6601 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6602 }
6603
6604 // Pass options for controlling the default header search paths.
6605 if (Args.hasArg(options::OPT_nostdinc)) {
6606 CmdArgs.push_back("-nostdsysteminc");
6607 CmdArgs.push_back("-nobuiltininc");
6608 } else {
6609 if (Args.hasArg(options::OPT_nostdlibinc))
6610 CmdArgs.push_back("-nostdsysteminc");
6611 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6612 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6613 }
6614
6615 // Pass the path to compiler resource files.
6616 CmdArgs.push_back("-resource-dir");
6617 CmdArgs.push_back(D.ResourceDir.c_str());
6618
6619 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6620
6621 // Add preprocessing options like -I, -D, etc. if we are using the
6622 // preprocessor.
6623 //
6624 // FIXME: Support -fpreprocessed
6626 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6627
6628 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6629 // that "The compiler can only warn and ignore the option if not recognized".
6630 // When building with ccache, it will pass -D options to clang even on
6631 // preprocessed inputs and configure concludes that -fPIC is not supported.
6632 Args.ClaimAllArgs(options::OPT_D);
6633
6634 // Warn about ignored options to clang.
6635 for (const Arg *A :
6636 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6637 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6638 A->claim();
6639 }
6640
6641 for (const Arg *A :
6642 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6643 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6644 A->claim();
6645 }
6646
6647 claimNoWarnArgs(Args);
6648
6649 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6650
6651 for (const Arg *A :
6652 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6653 A->claim();
6654 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6655 unsigned WarningNumber;
6656 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6657 D.Diag(diag::err_drv_invalid_int_value)
6658 << A->getAsString(Args) << A->getValue();
6659 continue;
6660 }
6661
6662 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6663 CmdArgs.push_back(Args.MakeArgString(
6664 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6665 }
6666 continue;
6667 }
6668 A->render(Args, CmdArgs);
6669 }
6670
6671 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6672
6673 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6674 CmdArgs.push_back("-pedantic");
6675 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6676 Args.AddLastArg(CmdArgs, options::OPT_w);
6677
6678 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6679 options::OPT_fno_fixed_point);
6680
6681 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6682 options::OPT_fno_experimental_overflow_behavior_types);
6683
6684 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6685 A->render(Args, CmdArgs);
6686
6687 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6688 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6689
6690 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6691 options::OPT_fno_experimental_omit_vtable_rtti);
6692
6693 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6694 A->render(Args, CmdArgs);
6695
6696 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6697 // (-ansi is equivalent to -std=c89 or -std=c++98).
6698 //
6699 // If a std is supplied, only add -trigraphs if it follows the
6700 // option.
6701 bool ImplyVCPPCVer = false;
6702 bool ImplyVCPPCXXVer = false;
6703 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6704 if (Std) {
6705 if (Std->getOption().matches(options::OPT_ansi))
6706 if (types::isCXX(InputType))
6707 CmdArgs.push_back("-std=c++98");
6708 else
6709 CmdArgs.push_back("-std=c89");
6710 else {
6711 if (IsSYCL) {
6712 const LangStandard *LangStd =
6713 LangStandard::getLangStandardForName(Std->getValue());
6714 if (LangStd) {
6715 // Use of -std= with 'C' is not supported for SYCL.
6716 if (LangStd->getLanguage() == Language::C)
6717 D.Diag(diag::err_drv_argument_not_allowed_with)
6718 << Std->getAsString(Args) << "-fsycl";
6719 // SYCL requires C++17 or later.
6720 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6721 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6722 }
6723 }
6724 Std->render(Args, CmdArgs);
6725 }
6726
6727 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6728 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6729 options::OPT_ftrigraphs,
6730 options::OPT_fno_trigraphs))
6731 if (A != Std)
6732 A->render(Args, CmdArgs);
6733 } else {
6734 // Honor -std-default.
6735 //
6736 // FIXME: Clang doesn't correctly handle -std= when the input language
6737 // doesn't match. For the time being just ignore this for C++ inputs;
6738 // eventually we want to do all the standard defaulting here instead of
6739 // splitting it between the driver and clang -cc1.
6740 if (!types::isCXX(InputType)) {
6741 if (!Args.hasArg(options::OPT__SLASH_std)) {
6742 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6743 /*Joined=*/true);
6744 } else
6745 ImplyVCPPCVer = true;
6746 }
6747 else if (IsWindowsMSVC)
6748 ImplyVCPPCXXVer = true;
6749
6750 if (IsSYCL && types::isCXX(InputType) &&
6751 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6752 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6753 // on the command line will override. On Windows MSVC, this is handled
6754 // by the ImplyVCPPCXXVer path below.
6755 CmdArgs.push_back("-std=c++17");
6756
6757 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6758 options::OPT_fno_trigraphs);
6759 }
6760
6761 // GCC's behavior for -Wwrite-strings is a bit strange:
6762 // * In C, this "warning flag" changes the types of string literals from
6763 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6764 // for the discarded qualifier.
6765 // * In C++, this is just a normal warning flag.
6766 //
6767 // Implementing this warning correctly in C is hard, so we follow GCC's
6768 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6769 // a non-const char* in C, rather than using this crude hack.
6770 if (!types::isCXX(InputType)) {
6771 // FIXME: This should behave just like a warning flag, and thus should also
6772 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6773 Arg *WriteStrings =
6774 Args.getLastArg(options::OPT_Wwrite_strings,
6775 options::OPT_Wno_write_strings, options::OPT_w);
6776 if (WriteStrings &&
6777 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6778 CmdArgs.push_back("-fconst-strings");
6779 }
6780
6781 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6782 // during C++ compilation, which it is by default. GCC keeps this define even
6783 // in the presence of '-w', match this behavior bug-for-bug.
6784 if (types::isCXX(InputType) &&
6785 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6786 true)) {
6787 CmdArgs.push_back("-fdeprecated-macro");
6788 }
6789
6790 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6791 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6792 if (Asm->getOption().matches(options::OPT_fasm))
6793 CmdArgs.push_back("-fgnu-keywords");
6794 else
6795 CmdArgs.push_back("-fno-gnu-keywords");
6796 }
6797
6798 if (!ShouldEnableAutolink(Args, TC, JA))
6799 CmdArgs.push_back("-fno-autolink");
6800
6801 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6802 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6803 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6804 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6805
6806 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6807
6808 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6809 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6810 Args.AddLastArg(CmdArgs,
6811 options::OPT_fno_experimental_new_constant_interpreter);
6812 } else {
6813 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6814 Args.AddLastArg(CmdArgs,
6815 options::OPT_fexperimental_new_constant_interpreter);
6816 }
6817
6818 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6819 CmdArgs.push_back("-fbracket-depth");
6820 CmdArgs.push_back(A->getValue());
6821 }
6822
6823 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6824 options::OPT_Wlarge_by_value_copy_def)) {
6825 if (A->getNumValues()) {
6826 StringRef bytes = A->getValue();
6827 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6828 } else
6829 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6830 }
6831
6832 if (Args.hasArg(options::OPT_relocatable_pch))
6833 CmdArgs.push_back("-relocatable-pch");
6834
6835 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6836 static const char *kCFABIs[] = {
6837 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6838 };
6839
6840 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6841 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6842 else
6843 A->render(Args, CmdArgs);
6844 }
6845
6846 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6847 CmdArgs.push_back("-fconstant-string-class");
6848 CmdArgs.push_back(A->getValue());
6849 }
6850
6851 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6852 CmdArgs.push_back("-fconstant-array-class");
6853 CmdArgs.push_back(A->getValue());
6854 }
6855 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6856 CmdArgs.push_back("-fconstant-dictionary-class");
6857 CmdArgs.push_back(A->getValue());
6858 }
6859 if (Arg *A =
6860 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6861 CmdArgs.push_back("-fconstant-integer-number-class");
6862 CmdArgs.push_back(A->getValue());
6863 }
6864 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6865 CmdArgs.push_back("-fconstant-float-number-class");
6866 CmdArgs.push_back(A->getValue());
6867 }
6868 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6869 CmdArgs.push_back("-fconstant-double-number-class");
6870 CmdArgs.push_back(A->getValue());
6871 }
6872
6873 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6874 CmdArgs.push_back("-ftabstop");
6875 CmdArgs.push_back(A->getValue());
6876 }
6877
6878 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6879 options::OPT_fno_experimental_call_graph_section, false))
6880 CmdArgs.push_back("-fexperimental-call-graph-section");
6881
6882 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6883 options::OPT_fno_stack_size_section);
6884
6885 if (Args.hasArg(options::OPT_fstack_usage)) {
6886 CmdArgs.push_back("-stack-usage-file");
6887
6888 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6889 SmallString<128> OutputFilename(OutputOpt->getValue());
6890 llvm::sys::path::replace_extension(OutputFilename, "su");
6891 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6892 } else
6893 CmdArgs.push_back(
6894 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6895 }
6896
6897 CmdArgs.push_back("-ferror-limit");
6898 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6899 CmdArgs.push_back(A->getValue());
6900 else
6901 CmdArgs.push_back("19");
6902
6903 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6904 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6905 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6906 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6907 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6908
6909 // Pass -fmessage-length=.
6910 unsigned MessageLength = 0;
6911 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6912 StringRef V(A->getValue());
6913 if (V.getAsInteger(0, MessageLength))
6914 D.Diag(diag::err_drv_invalid_argument_to_option)
6915 << V << A->getOption().getName();
6916 } else {
6917 // If -fmessage-length=N was not specified, determine whether this is a
6918 // terminal and, if so, implicitly define -fmessage-length appropriately.
6919 MessageLength = llvm::sys::Process::StandardErrColumns();
6920 }
6921 if (MessageLength != 0)
6922 CmdArgs.push_back(
6923 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6924
6925 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6926 CmdArgs.push_back(
6927 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6928
6929 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6930 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6931 Twine(A->getValue(0))));
6932
6933 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6934 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6935 options::OPT_fvisibility_ms_compat)) {
6936 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6937 A->render(Args, CmdArgs);
6938 } else {
6939 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6940 CmdArgs.push_back("-fvisibility=hidden");
6941 CmdArgs.push_back("-ftype-visibility=default");
6942 }
6943 } else if (IsOpenMPDevice) {
6944 // When compiling for the OpenMP device we want protected visibility by
6945 // default. This prevents the device from accidentally preempting code on
6946 // the host, makes the system more robust, and improves performance.
6947 CmdArgs.push_back("-fvisibility=protected");
6948 }
6949
6950 // PS4/PS5 process these options in addClangTargetOptions.
6951 if (!RawTriple.isPS()) {
6952 if (const Arg *A =
6953 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6954 options::OPT_fno_visibility_from_dllstorageclass)) {
6955 if (A->getOption().matches(
6956 options::OPT_fvisibility_from_dllstorageclass)) {
6957 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6958 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6959 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6960 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6961 Args.AddLastArg(CmdArgs,
6962 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6963 }
6964 }
6965 }
6966
6967 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6968 options::OPT_fno_visibility_inlines_hidden, false))
6969 CmdArgs.push_back("-fvisibility-inlines-hidden");
6970
6971 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6972 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6973
6974 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6975 // -fvisibility-global-new-delete=force-hidden.
6976 if (const Arg *A =
6977 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6978 D.Diag(diag::warn_drv_deprecated_arg)
6979 << A->getAsString(Args) << /*hasReplacement=*/true
6980 << "-fvisibility-global-new-delete=force-hidden";
6981 }
6982
6983 if (const Arg *A =
6984 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6985 options::OPT_fvisibility_global_new_delete_hidden)) {
6986 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6987 A->render(Args, CmdArgs);
6988 } else {
6989 assert(A->getOption().matches(
6990 options::OPT_fvisibility_global_new_delete_hidden));
6991 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
6992 }
6993 }
6994
6995 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6996
6997 if (Args.hasFlag(options::OPT_fnew_infallible,
6998 options::OPT_fno_new_infallible, false))
6999 CmdArgs.push_back("-fnew-infallible");
7000
7001 if (Args.hasFlag(options::OPT_fno_operator_names,
7002 options::OPT_foperator_names, false))
7003 CmdArgs.push_back("-fno-operator-names");
7004
7005 // Forward -f (flag) options which we can pass directly.
7006 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7007 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7008 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7009 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7010 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7011 options::OPT_fno_raw_string_literals);
7012
7013 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7014 Triple.hasDefaultEmulatedTLS()))
7015 CmdArgs.push_back("-femulated-tls");
7016
7017 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7018 options::OPT_fno_check_new);
7019
7020 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7021 // FIXME: There's no reason for this to be restricted to some backend.
7022 // The backend code needs to be changed to include the appropriate function
7023 // calls automatically.
7024 StringRef Value = A->getValue();
7025 if (!Triple.isX86() && !Triple.isAArch64() &&
7026 !(Triple.isRISCV() && (Value == "skip" || Value.contains("gpr"))))
7027 D.Diag(diag::err_drv_unsupported_opt_for_target)
7028 << A->getAsString(Args) << TripleStr;
7029 }
7030
7031 // AltiVec-like language extensions aren't relevant for assembling.
7032 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7033 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7034
7035 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7036 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7037
7038 // Forward flags for OpenMP. We don't do this if the current action is an
7039 // device offloading action other than OpenMP.
7040 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7041 options::OPT_fno_openmp, false) &&
7042 !Args.hasFlag(options::OPT_foffload_via_llvm,
7043 options::OPT_fno_offload_via_llvm, false) &&
7046
7047 // Determine if target-fast optimizations should be enabled
7048 bool TargetFastUsed =
7049 Args.hasFlag(options::OPT_fopenmp_target_fast,
7050 options::OPT_fno_openmp_target_fast, OFastEnabled);
7051 switch (D.getOpenMPRuntime(Args)) {
7052 case Driver::OMPRT_OMP:
7054 // Clang can generate useful OpenMP code for these two runtime libraries.
7055 CmdArgs.push_back("-fopenmp");
7056
7057 // If no option regarding the use of TLS in OpenMP codegeneration is
7058 // given, decide a default based on the target. Otherwise rely on the
7059 // options and pass the right information to the frontend.
7060 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7061 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7062 CmdArgs.push_back("-fnoopenmp-use-tls");
7063 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7064 options::OPT_fno_openmp_simd);
7065 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7066 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7067 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7068 options::OPT_fno_openmp_extensions, /*Default=*/true))
7069 CmdArgs.push_back("-fno-openmp-extensions");
7070 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7071 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7072 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7073 // effect: the teams reduction buffer is sized at kernel launch by the
7074 // offload plugin to match the actual number of teams. Honoring a
7075 // smaller user-supplied value would silently truncate the buffer for
7076 // larger launches.
7077 if (Arg *A = Args.getLastArg(
7078 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7079 D.Diag(diag::warn_drv_deprecated_custom)
7080 << A->getAsString(Args)
7081 << "the value is ignored; the teams reduction buffer is sized "
7082 "automatically at kernel launch";
7083 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7084 options::OPT_fno_openmp_optimistic_collapse,
7085 /*Default=*/false))
7086 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7087
7088 // When in OpenMP offloading mode with NVPTX target, forward
7089 // cuda-mode flag
7090 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7091 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7092 CmdArgs.push_back("-fopenmp-cuda-mode");
7093
7094 // When in OpenMP offloading mode, enable debugging on the device.
7095 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7096 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7097 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7098 CmdArgs.push_back("-fopenmp-target-debug");
7099
7100 // When in OpenMP offloading mode, forward assumptions information about
7101 // thread and team counts in the device.
7102 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7103 options::OPT_fno_openmp_assume_teams_oversubscription,
7104 /*Default=*/false))
7105 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7106 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7107 options::OPT_fno_openmp_assume_threads_oversubscription,
7108 /*Default=*/false))
7109 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7110
7111 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7112 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7113 options::OPT_fno_openmp_assume_no_thread_state,
7114 /*Default=*/TargetFastUsed))
7115 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7116
7117 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7118 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7119 options::OPT_fno_openmp_assume_no_nested_parallelism,
7120 /*Default=*/TargetFastUsed))
7121 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7122
7123 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7124 CmdArgs.push_back("-fopenmp-offload-mandatory");
7125 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7126 CmdArgs.push_back("-fopenmp-force-usm");
7127 break;
7128 default:
7129 // By default, if Clang doesn't know how to generate useful OpenMP code
7130 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7131 // down to the actual compilation.
7132 // FIXME: It would be better to have a mode which *only* omits IR
7133 // generation based on the OpenMP support so that we get consistent
7134 // semantic analysis, etc.
7135 break;
7136 }
7137 } else {
7138 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7139 options::OPT_fno_openmp_simd);
7140 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7141 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7142 options::OPT_fno_openmp_extensions);
7143 }
7144 // Forward the offload runtime change to code generation, liboffload implies
7145 // new driver. Otherwise, check if we should forward the new driver to change
7146 // offloading code generation.
7147 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7148 options::OPT_fno_offload_via_llvm, false)) {
7149 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
7150 } else if (Args.hasFlag(options::OPT_offload_new_driver,
7151 options::OPT_no_offload_new_driver,
7152 C.getActiveOffloadKinds() != Action::OFK_None)) {
7153 CmdArgs.push_back("--offload-new-driver");
7154 }
7155
7156 const XRayArgs &XRay = TC.getXRayArgs(Args);
7157 XRay.addArgs(TC, Args, CmdArgs, InputType);
7158
7159 for (const auto &Filename :
7160 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7161 if (D.getVFS().exists(Filename))
7162 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7163 else
7164 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7165 }
7166
7167 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7168 StringRef S0 = A->getValue(), S = S0;
7169 unsigned Size, Offset = 0;
7170 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7171 !Triple.isX86() && !Triple.isSystemZ() &&
7172 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7173 Triple.getArch() == llvm::Triple::ppc64 ||
7174 Triple.getArch() == llvm::Triple::ppc64le)))
7175 D.Diag(diag::err_drv_unsupported_opt_for_target)
7176 << A->getAsString(Args) << TripleStr;
7177 else if (S.consumeInteger(10, Size) ||
7178 (!S.empty() &&
7179 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7180 (!S.empty() && (!S.consume_front(",") || S.empty())))
7181 D.Diag(diag::err_drv_invalid_argument_to_option)
7182 << S0 << A->getOption().getName();
7183 else if (Size < Offset)
7184 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7185 else {
7186 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7187 CmdArgs.push_back(Args.MakeArgString(
7188 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7189 if (!S.empty())
7190 CmdArgs.push_back(
7191 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7192 }
7193 }
7194
7195 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7196
7197 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7198 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7199
7200 for (const auto &A :
7201 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7202 CmdArgs.push_back(
7203 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7204
7205 if (TC.SupportsProfiling()) {
7206 Args.AddLastArg(CmdArgs, options::OPT_pg);
7207
7208 llvm::Triple::ArchType Arch = TC.getArch();
7209 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7210 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7211 A->render(Args, CmdArgs);
7212 else
7213 D.Diag(diag::err_drv_unsupported_opt_for_target)
7214 << A->getAsString(Args) << TripleStr;
7215 }
7216 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7217 if (Arch == llvm::Triple::systemz)
7218 A->render(Args, CmdArgs);
7219 else
7220 D.Diag(diag::err_drv_unsupported_opt_for_target)
7221 << A->getAsString(Args) << TripleStr;
7222 }
7223 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7224 if (Arch == llvm::Triple::systemz)
7225 A->render(Args, CmdArgs);
7226 else
7227 D.Diag(diag::err_drv_unsupported_opt_for_target)
7228 << A->getAsString(Args) << TripleStr;
7229 }
7230 }
7231
7232 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7233 if (TC.getTriple().isOSzOS()) {
7234 D.Diag(diag::err_drv_unsupported_opt_for_target)
7235 << A->getAsString(Args) << TripleStr;
7236 }
7237 }
7238 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7239 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7240 D.Diag(diag::err_drv_unsupported_opt_for_target)
7241 << A->getAsString(Args) << TripleStr;
7242 }
7243 }
7244 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7245 if (A->getOption().matches(options::OPT_p)) {
7246 A->claim();
7247 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7248 CmdArgs.push_back("-pg");
7249 }
7250 }
7251
7252 // Reject AIX-specific link options on other targets.
7253 if (!TC.getTriple().isOSAIX()) {
7254 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7255 options::OPT_mxcoff_build_id_EQ)) {
7256 D.Diag(diag::err_drv_unsupported_opt_for_target)
7257 << A->getSpelling() << TripleStr;
7258 }
7259 }
7260
7261 if (Args.getLastArg(options::OPT_fapple_kext) ||
7262 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7263 CmdArgs.push_back("-fapple-kext");
7264
7265 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7266 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7267 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7268 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7269 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7270 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7271 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7272 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7273 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7274 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7275 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7276
7277 if (const char *Name = C.getTimeTraceFile(&JA)) {
7278 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7279 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7280 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7281 }
7282
7283 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7284 CmdArgs.push_back("-ftrapv-handler");
7285 CmdArgs.push_back(A->getValue());
7286 }
7287
7288 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7289
7290 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7291 options::OPT_fno_finite_loops);
7292
7293 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7294 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7295 options::OPT_fno_unroll_loops);
7296 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7297 options::OPT_fno_loop_interchange);
7298 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7299 options::OPT_fno_experimental_loop_fusion);
7300
7301 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7302
7303 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7304
7305 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7306 options::OPT_mno_speculative_load_hardening);
7307
7308 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7309 RenderSCPOptions(TC, Args, CmdArgs);
7310 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7311
7312 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7313
7314 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7315 options::OPT_mno_stackrealign);
7316
7317 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7318 StringRef Value = A->getValue();
7319 int64_t Alignment = 0;
7320 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7321 D.Diag(diag::err_drv_invalid_argument_to_option)
7322 << Value << A->getOption().getName();
7323 else if (Alignment & (Alignment - 1))
7324 D.Diag(diag::err_drv_alignment_not_power_of_two)
7325 << A->getAsString(Args) << Value;
7326 else
7327 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7328 }
7329
7330 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7331 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7332
7333 if (!Size.empty())
7334 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7335 else
7336 CmdArgs.push_back("-mstack-probe-size=0");
7337 }
7338
7339 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7340 options::OPT_mno_stack_arg_probe);
7341
7342 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7343 options::OPT_mno_restrict_it)) {
7344 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7345 CmdArgs.push_back("-mllvm");
7346 CmdArgs.push_back("-arm-restrict-it");
7347 } else {
7348 CmdArgs.push_back("-mllvm");
7349 CmdArgs.push_back("-arm-default-it");
7350 }
7351 }
7352
7353 // Forward -cl options to -cc1
7354 RenderOpenCLOptions(Args, CmdArgs, InputType);
7355
7356 // Forward hlsl options to -cc1
7357 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7358
7359 // Forward OpenACC options to -cc1
7360 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7361
7362 if (IsHIP) {
7363 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7364 options::OPT_fno_hip_new_launch_api, true))
7365 CmdArgs.push_back("-fhip-new-launch-api");
7366 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7367 options::OPT_fno_gpu_allow_device_init);
7368 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7369 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7370 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7371 options::OPT_fno_hip_kernel_arg_name);
7372 }
7373
7374 if (IsCuda || IsHIP) {
7375 if (IsRDCMode)
7376 CmdArgs.push_back("-fgpu-rdc");
7377 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7378 options::OPT_fno_gpu_defer_diag);
7379 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7380 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7381 false)) {
7382 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7383 CmdArgs.push_back("-fgpu-defer-diag");
7384 }
7385 }
7386
7387 // Forward --no-offloadlib to -cc1.
7388 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7389 CmdArgs.push_back("--no-offloadlib");
7390
7391 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7392 CmdArgs.push_back(
7393 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7394
7395 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7396 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7397 SA->getValue()));
7398 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7399 // Emit IBT endbr64 instructions by default
7400 CmdArgs.push_back("-fcf-protection=branch");
7401 // jump-table can generate indirect jumps, which are not permitted
7402 CmdArgs.push_back("-fno-jump-tables");
7403 }
7404
7405 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7406 CmdArgs.push_back(
7407 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7408
7409 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7410
7411 // Forward -f options with positive and negative forms; we translate these by
7412 // hand. Do not propagate PGO options to the GPU-side compilations as the
7413 // profile info is for the host-side compilation only.
7414 if (!(IsCudaDevice || IsHIPDevice)) {
7415 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7416 auto *PGOArg = Args.getLastArg(
7417 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7418 options::OPT_fcs_profile_generate,
7419 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7420 options::OPT_fprofile_use_EQ);
7421 if (PGOArg)
7422 D.Diag(diag::err_drv_argument_not_allowed_with)
7423 << "SampleUse with PGO options";
7424
7425 StringRef fname = A->getValue();
7426 if (!llvm::sys::fs::exists(fname))
7427 D.Diag(diag::err_drv_no_such_file) << fname;
7428 else
7429 A->render(Args, CmdArgs);
7430 }
7431 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7432
7433 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7434 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7435 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7436 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7437 // off.
7438 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7439 options::OPT_fno_unique_internal_linkage_names, true))
7440 CmdArgs.push_back("-funique-internal-linkage-names");
7441 }
7442 }
7443 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7444
7445 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7446 options::OPT_fno_assume_sane_operator_new);
7447
7448 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7449 CmdArgs.push_back("-fapinotes");
7450 if (Args.hasFlag(options::OPT_fapinotes_modules,
7451 options::OPT_fno_apinotes_modules, false))
7452 CmdArgs.push_back("-fapinotes-modules");
7453 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7454
7455 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7456 options::OPT_fno_swift_version_independent_apinotes, false))
7457 CmdArgs.push_back("-fswift-version-independent-apinotes");
7458
7459 // -fblocks=0 is default.
7460 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7461 TC.IsBlocksDefault()) ||
7462 (Args.hasArg(options::OPT_fgnu_runtime) &&
7463 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7464 !Args.hasArg(options::OPT_fno_blocks))) {
7465 CmdArgs.push_back("-fblocks");
7466
7467 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7468 CmdArgs.push_back("-fblocks-runtime-optional");
7469 }
7470
7471 // -fencode-extended-block-signature=1 is default.
7473 CmdArgs.push_back("-fencode-extended-block-signature");
7474
7475 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7476 options::OPT_fno_coro_aligned_allocation, false) &&
7477 types::isCXX(InputType))
7478 CmdArgs.push_back("-fcoro-aligned-allocation");
7479
7480 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7481 /*Default=*/false))
7482 CmdArgs.push_back("-fdefer-ts");
7483
7484 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7485 options::OPT_fno_double_square_bracket_attributes);
7486
7487 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7488 options::OPT_fno_access_control);
7489 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7490 options::OPT_fno_elide_constructors);
7491
7492 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7493
7494 if (KernelOrKext || (types::isCXX(InputType) &&
7495 (RTTIMode == ToolChain::RM_Disabled)))
7496 CmdArgs.push_back("-fno-rtti");
7497
7498 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7499 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7500 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7501 CmdArgs.push_back("-fshort-enums");
7502
7503 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7504
7505 // -fuse-cxa-atexit is default.
7506 if (!Args.hasFlag(
7507 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7508 !RawTriple.isOSAIX() &&
7509 (!RawTriple.isOSWindows() ||
7510 RawTriple.isWindowsCygwinEnvironment()) &&
7511 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7512 RawTriple.hasEnvironment())) ||
7513 KernelOrKext)
7514 CmdArgs.push_back("-fno-use-cxa-atexit");
7515
7516 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7517 options::OPT_fno_register_global_dtors_with_atexit,
7518 RawTriple.isOSDarwin() && !KernelOrKext))
7519 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7520
7521 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7522 options::OPT_fno_use_line_directives);
7523
7524 // -fno-minimize-whitespace is default.
7525 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7526 options::OPT_fno_minimize_whitespace, false)) {
7527 types::ID InputType = Inputs[0].getType();
7528 if (!isDerivedFromC(InputType))
7529 D.Diag(diag::err_drv_opt_unsupported_input_type)
7530 << "-fminimize-whitespace" << types::getTypeName(InputType);
7531 CmdArgs.push_back("-fminimize-whitespace");
7532 }
7533
7534 // -fno-keep-system-includes is default.
7535 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7536 options::OPT_fno_keep_system_includes, false)) {
7537 types::ID InputType = Inputs[0].getType();
7538 if (!isDerivedFromC(InputType))
7539 D.Diag(diag::err_drv_opt_unsupported_input_type)
7540 << "-fkeep-system-includes" << types::getTypeName(InputType);
7541 CmdArgs.push_back("-fkeep-system-includes");
7542 }
7543
7544 // -fms-extensions=0 is default.
7545 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7546 IsWindowsMSVC || IsUEFI))
7547 CmdArgs.push_back("-fms-extensions");
7548
7549 // -fms-compatibility=0 is default.
7550 bool IsMSVCCompat = Args.hasFlag(
7551 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7552 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7553 options::OPT_fno_ms_extensions, true)));
7554 if (IsMSVCCompat) {
7555 CmdArgs.push_back("-fms-compatibility");
7556 if (!types::isCXX(Input.getType()) &&
7557 Args.hasArg(options::OPT_fms_define_stdc))
7558 CmdArgs.push_back("-fms-define-stdc");
7559 }
7560
7561 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7562 // clang and flang.
7563 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7564
7565 // -fms-anonymous-structs is disabled by default.
7566 // Determine whether to enable Microsoft named anonymous struct/union support.
7567 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7568 // where the feature can be:
7569 // - Explicitly enabled via -fms-anonymous-structs.
7570 // - Explicitly disabled via fno-ms-anonymous-structs
7571 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7572 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7573 //
7574 // When multiple relevent options are present, the last option on the command
7575 // line takes precedence. This allows users to selectively override implicit
7576 // enablement. Examples:
7577 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7578 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7579 auto MSAnonymousStructsOptionToUseOrNull =
7580 [](const ArgList &Args) -> const char * {
7581 const char *Option = nullptr;
7582 constexpr const char *Enable = "-fms-anonymous-structs";
7583 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7584
7585 // Iterate through all arguments in order to implement "last flag wins".
7586 for (const Arg *A : Args) {
7587 switch (A->getOption().getID()) {
7588 case options::OPT_fms_anonymous_structs:
7589 A->claim();
7590 Option = Enable;
7591 break;
7592 case options::OPT_fno_ms_anonymous_structs:
7593 A->claim();
7594 Option = Disable;
7595 break;
7596 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7597 // feature.
7598 case options::OPT_fms_extensions:
7599 case options::OPT_fms_compatibility:
7600 Option = Enable;
7601 break;
7602 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7603 // disables the feature.
7604 case options::OPT_fno_ms_extensions:
7605 case options::OPT_fno_ms_compatibility:
7606 Option = Disable;
7607 break;
7608 default:
7609 break;
7610 }
7611 }
7612 return Option;
7613 };
7614
7615 // Only pass a flag to CC1 if a relevant option was seen
7616 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7617 CmdArgs.push_back(MSAnonOpt);
7618
7619 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7620 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7621 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7622
7623 // Handle -fgcc-version, if present.
7624 VersionTuple GNUCVer;
7625 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7626 // Check that the version has 1 to 3 components and the minor and patch
7627 // versions fit in two decimal digits.
7628 StringRef Val = A->getValue();
7629 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7630 bool Invalid = GNUCVer.tryParse(Val);
7631 unsigned Minor = GNUCVer.getMinor().value_or(0);
7632 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7633 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7634 D.Diag(diag::err_drv_invalid_value)
7635 << A->getAsString(Args) << A->getValue();
7636 }
7637 } else if (!IsMSVCCompat) {
7638 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7639 GNUCVer = VersionTuple(4, 2, 1);
7640 }
7641 if (!GNUCVer.empty()) {
7642 CmdArgs.push_back(
7643 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7644 }
7645
7646 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7647 if (!MSVT.empty())
7648 CmdArgs.push_back(
7649 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7650
7651 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7652 if (ImplyVCPPCVer) {
7653 StringRef LanguageStandard;
7654 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7655 Std = StdArg;
7656 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7657 .Case("c11", "-std=c11")
7658 .Case("c17", "-std=c17")
7659 // If you add cases below for spellings that are
7660 // not in LangStandards.def, update
7661 // TransferableCommand::tryParseStdArg() in
7662 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7663 // to match.
7664 // TODO: add c23 when MSVC supports it.
7665 .Case("clatest", "-std=c23")
7666 .Default("");
7667 if (LanguageStandard.empty())
7668 D.Diag(clang::diag::warn_drv_unused_argument)
7669 << StdArg->getAsString(Args);
7670 }
7671 CmdArgs.push_back(LanguageStandard.data());
7672 }
7673 if (ImplyVCPPCXXVer) {
7674 StringRef LanguageStandard;
7675 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7676 Std = StdArg;
7677 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7678 .Case("c++14", "-std=c++14")
7679 .Case("c++17", "-std=c++17")
7680 .Case("c++20", "-std=c++20")
7681 // If you add cases below for spellings that are
7682 // not in LangStandards.def, update
7683 // TransferableCommand::tryParseStdArg() in
7684 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7685 // to match.
7686 // TODO add c++23 and c++26 when MSVC supports it.
7687 .Case("c++23preview", "-std=c++23")
7688 .Case("c++latest", "-std=c++26")
7689 .Default("");
7690 if (IsSYCL) {
7691 const LangStandard *LangStd =
7692 LangStandard::getLangStandardForName(StdArg->getValue());
7693 if (LangStd) {
7694 // Use of /std: with 'C' is not supported for SYCL.
7695 if (LangStd->getLanguage() == Language::C)
7696 D.Diag(diag::err_drv_argument_not_allowed_with)
7697 << StdArg->getAsString(Args) << "-fsycl";
7698 // SYCL requires C++17 or later.
7699 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7700 D.Diag(diag::err_drv_sycl_requires_cxx17)
7701 << StdArg->getAsString(Args);
7702 }
7703 }
7704 if (LanguageStandard.empty())
7705 D.Diag(clang::diag::warn_drv_unused_argument)
7706 << StdArg->getAsString(Args);
7707 }
7708
7709 if (LanguageStandard.empty()) {
7710 if (IsSYCL)
7711 // For SYCL, C++17 is the default.
7712 LanguageStandard = "-std=c++17";
7713 else if (IsMSVC2015Compatible)
7714 LanguageStandard = "-std=c++14";
7715 else
7716 LanguageStandard = "-std=c++11";
7717 }
7718
7719 CmdArgs.push_back(LanguageStandard.data());
7720 }
7721
7722 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7723 options::OPT_fno_borland_extensions);
7724
7725 // -fno-declspec is default, except for PS4/PS5.
7726 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7727 RawTriple.isPS()))
7728 CmdArgs.push_back("-fdeclspec");
7729 else if (Args.hasArg(options::OPT_fno_declspec))
7730 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7731
7732 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7733 // than 19.
7734 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7735 options::OPT_fno_threadsafe_statics,
7736 !types::isOpenCL(InputType) &&
7737 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7738 CmdArgs.push_back("-fno-threadsafe-statics");
7739
7740 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7741 true))
7742 CmdArgs.push_back("-fno-ms-tls-guards");
7743
7744 // Add -fno-assumptions, if it was specified.
7745 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7746 true))
7747 CmdArgs.push_back("-fno-assumptions");
7748
7749 // -fgnu-keywords default varies depending on language; only pass if
7750 // specified.
7751 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7752 options::OPT_fno_gnu_keywords);
7753
7754 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7755 options::OPT_fno_gnu89_inline);
7756
7757 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7758 options::OPT_finline_hint_functions,
7759 options::OPT_fno_inline_functions);
7760 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7761 if (A->getOption().matches(options::OPT_fno_inline))
7762 A->render(Args, CmdArgs);
7763 } else if (InlineArg) {
7764 InlineArg->render(Args, CmdArgs);
7765 }
7766
7767 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7768
7769 // FIXME: Find a better way to determine whether we are in C++20.
7770 bool HaveCxx20 =
7771 Std &&
7772 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7773 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7774 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7775 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7776 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7777 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7778 Std->containsValue("gnu++26") || Std->containsValue("c++latest") ||
7779 Std->containsValue("gnu++latest"));
7780 bool HaveModules =
7781 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7782
7783 // -fdelayed-template-parsing is default when targeting MSVC.
7784 // Many old Windows SDK versions require this to parse.
7785 //
7786 // According to
7787 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7788 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7789 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7790 // not enable -fdelayed-template-parsing by default after C++20.
7791 //
7792 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7793 // able to disable this by default at some point.
7794 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7795 options::OPT_fno_delayed_template_parsing,
7796 IsWindowsMSVC && !HaveCxx20)) {
7797 if (HaveCxx20)
7798 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7799
7800 CmdArgs.push_back("-fdelayed-template-parsing");
7801 }
7802
7803 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7804 options::OPT_fno_pch_validate_input_files_content, false))
7805 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7806 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7807 options::OPT_fno_pch_instantiate_templates, false))
7808 CmdArgs.push_back("-fpch-instantiate-templates");
7809 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7810 false))
7811 CmdArgs.push_back("-fmodules-codegen");
7812 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7813 false))
7814 CmdArgs.push_back("-fmodules-debuginfo");
7815
7816 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7817 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7818 Input, CmdArgs);
7819
7820 if (types::isObjC(Input.getType()) &&
7821 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7822 options::OPT_fno_objc_encode_cxx_class_template_spec,
7823 !Runtime.isNeXTFamily()))
7824 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7825
7826 if (Args.hasFlag(options::OPT_fapplication_extension,
7827 options::OPT_fno_application_extension, false))
7828 CmdArgs.push_back("-fapplication-extension");
7829
7830 // Handle GCC-style exception args.
7831 bool EH = false;
7832 if (!C.getDriver().IsCLMode())
7833 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7834 IsDeviceOffloadAction, Runtime, CmdArgs);
7835
7836 // Handle exception personalities
7837 Arg *A = Args.getLastArg(
7838 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7839 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7840 if (A) {
7841 const Option &Opt = A->getOption();
7842 if (Opt.matches(options::OPT_fsjlj_exceptions))
7843 CmdArgs.push_back("-exception-model=sjlj");
7844 if (Opt.matches(options::OPT_fseh_exceptions))
7845 CmdArgs.push_back("-exception-model=seh");
7846 if (Opt.matches(options::OPT_fdwarf_exceptions))
7847 CmdArgs.push_back("-exception-model=dwarf");
7848 if (Opt.matches(options::OPT_fwasm_exceptions))
7849 CmdArgs.push_back("-exception-model=wasm");
7850 } else {
7851 switch (TC.GetExceptionModel(Args)) {
7852 default:
7853 break;
7854 case llvm::ExceptionHandling::DwarfCFI:
7855 CmdArgs.push_back("-exception-model=dwarf");
7856 break;
7857 case llvm::ExceptionHandling::SjLj:
7858 CmdArgs.push_back("-exception-model=sjlj");
7859 break;
7860 case llvm::ExceptionHandling::WinEH:
7861 CmdArgs.push_back("-exception-model=seh");
7862 break;
7863 }
7864 }
7865
7866 // Unwind information version for x64 Windows.
7867 // Forward the new unified flag if present, otherwise translate legacy flags.
7868 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
7869 A->claim();
7870 CmdArgs.push_back(
7871 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
7872 } else if (const Arg *A =
7873 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
7874 A->claim();
7875 StringRef Val = A->getValue();
7876 if (Val == "best-effort")
7877 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
7878 else if (Val == "required")
7879 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
7880 // "disabled" maps to v1 default, nothing to forward.
7881 else if (Val != "disabled")
7882 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7883 }
7884
7885 // Control Flow Guard mechanism for Windows.
7886 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7887
7888 // C++ "sane" operator new.
7889 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7890 options::OPT_fno_assume_sane_operator_new);
7891
7892 // -fassume-unique-vtables is on by default.
7893 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7894 options::OPT_fno_assume_unique_vtables);
7895
7896 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7897 // by default.
7898 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7899 options::OPT_fno_sized_deallocation);
7900
7901 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7902 // by default.
7903 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7904 options::OPT_fno_aligned_allocation,
7905 options::OPT_faligned_new_EQ)) {
7906 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7907 CmdArgs.push_back("-fno-aligned-allocation");
7908 else
7909 CmdArgs.push_back("-faligned-allocation");
7910 }
7911
7912 // The default new alignment can be specified using a dedicated option or via
7913 // a GCC-compatible option that also turns on aligned allocation.
7914 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7915 options::OPT_faligned_new_EQ))
7916 CmdArgs.push_back(
7917 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7918
7919 // -fconstant-cfstrings is default, and may be subject to argument translation
7920 // on Darwin.
7921 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7922 options::OPT_fno_constant_cfstrings, true) ||
7923 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7924 options::OPT_mno_constant_cfstrings, true))
7925 CmdArgs.push_back("-fno-constant-cfstrings");
7926
7927 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7928 options::OPT_fno_pascal_strings);
7929
7930 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7931 // -fno-pack-struct doesn't apply to -fpack-struct=.
7932 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7933 CmdArgs.push_back(
7934 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
7935 } else if (Args.hasFlag(options::OPT_fpack_struct,
7936 options::OPT_fno_pack_struct, false)) {
7937 CmdArgs.push_back("-fpack-struct=1");
7938 }
7939
7940 // Handle -fmax-type-align=N and -fno-type-align
7941 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7942 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7943 if (!SkipMaxTypeAlign) {
7944 std::string MaxTypeAlignStr = "-fmax-type-align=";
7945 MaxTypeAlignStr += A->getValue();
7946 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7947 }
7948 } else if (RawTriple.isOSDarwin()) {
7949 if (!SkipMaxTypeAlign) {
7950 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7951 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7952 }
7953 }
7954
7955 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7956 CmdArgs.push_back("-Qn");
7957
7958 // -fno-common is the default, set -fcommon only when that flag is set.
7959 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7960
7961 // -fsigned-bitfields is default, and clang doesn't yet support
7962 // -funsigned-bitfields.
7963 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7964 options::OPT_funsigned_bitfields, true))
7965 D.Diag(diag::warn_drv_clang_unsupported)
7966 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7967
7968 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7969 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7970 D.Diag(diag::err_drv_clang_unsupported)
7971 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7972
7973 // -finput_charset=UTF-8 is default. Reject others
7974 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7975 StringRef value = inputCharset->getValue();
7976 if (!value.equals_insensitive("utf-8"))
7977 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7978 << value;
7979 }
7980
7981 // -fexec_charset=UTF-8 is default. Reject others
7982 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7983 StringRef value = execCharset->getValue();
7984 if (!value.equals_insensitive("utf-8"))
7985 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7986 << value;
7987 }
7988
7989 RenderDiagnosticsOptions(D, Args, CmdArgs);
7990
7991 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7992 options::OPT_fno_asm_blocks);
7993
7994 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7995 options::OPT_fno_gnu_inline_asm);
7996
7997 handleVectorizeLoopsArgs(Args, CmdArgs);
7998 handleVectorizeSLPArgs(Args, CmdArgs);
7999
8000 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8001 if (!VecWidth.empty())
8002 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8003
8004 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8005 Args.AddLastArg(CmdArgs,
8006 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8007
8008 // -fdollars-in-identifiers default varies depending on platform and
8009 // language; only pass if specified.
8010 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8011 options::OPT_fno_dollars_in_identifiers)) {
8012 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8013 CmdArgs.push_back("-fdollars-in-identifiers");
8014 else
8015 CmdArgs.push_back("-fno-dollars-in-identifiers");
8016 }
8017
8018 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8019 options::OPT_fno_apple_pragma_pack);
8020
8021 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8022 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8023 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8024
8025 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8026 options::OPT_fno_rewrite_imports, false);
8027 if (RewriteImports)
8028 CmdArgs.push_back("-frewrite-imports");
8029
8030 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8031 options::OPT_fno_directives_only);
8032
8033 // Enable rewrite includes if the user's asked for it or if we're generating
8034 // diagnostics.
8035 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8036 // nice to enable this when doing a crashdump for modules as well.
8037 if (Args.hasFlag(options::OPT_frewrite_includes,
8038 options::OPT_fno_rewrite_includes, false) ||
8039 (C.isForDiagnostics() && !HaveModules))
8040 CmdArgs.push_back("-frewrite-includes");
8041
8042 if (Args.hasFlag(options::OPT_fzos_extensions,
8043 options::OPT_fno_zos_extensions, false))
8044 CmdArgs.push_back("-fzos-extensions");
8045 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8046 CmdArgs.push_back("-fno-zos-extensions");
8047
8048 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8049 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8050 options::OPT_traditional_cpp)) {
8052 CmdArgs.push_back("-traditional-cpp");
8053 else
8054 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8055 }
8056
8057 Args.AddLastArg(CmdArgs, options::OPT_dM);
8058 Args.AddLastArg(CmdArgs, options::OPT_dD);
8059 Args.AddLastArg(CmdArgs, options::OPT_dI);
8060
8061 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8062
8063 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8064 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8065 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8066
8067 // Handle serialized diagnostics.
8068 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8069 CmdArgs.push_back("-serialize-diagnostic-file");
8070 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8071 }
8072
8073 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8074 CmdArgs.push_back("-fretain-comments-from-system-headers");
8075
8076 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8077 A->render(Args, CmdArgs);
8078 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8079 A && A->containsValue("g")) {
8080 // Set -fextend-variable-liveness=all by default at -Og.
8081 CmdArgs.push_back("-fextend-variable-liveness=all");
8082 }
8083
8084 // Forward -fcomment-block-commands to -cc1.
8085 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8086 // Forward -fparse-all-comments to -cc1.
8087 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8088
8089 // Turn -fplugin=name.so into -load name.so
8090 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8091 CmdArgs.push_back("-load");
8092 CmdArgs.push_back(A->getValue());
8093 A->claim();
8094 }
8095
8096 // Turn -fplugin-arg-pluginname-key=value into
8097 // -plugin-arg-pluginname key=value
8098 // GCC has an actual plugin_argument struct with key/value pairs that it
8099 // passes to its plugins, but we don't, so just pass it on as-is.
8100 //
8101 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8102 // argument key are allowed to contain dashes. GCC therefore only
8103 // allows dashes in the key. We do the same.
8104 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8105 auto ArgValue = StringRef(A->getValue());
8106 auto FirstDashIndex = ArgValue.find('-');
8107 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8108 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8109
8110 A->claim();
8111 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8112 if (PluginName.empty()) {
8113 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8114 } else {
8115 D.Diag(diag::warn_drv_missing_plugin_arg)
8116 << PluginName << A->getAsString(Args);
8117 }
8118 continue;
8119 }
8120
8121 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8122 CmdArgs.push_back(Args.MakeArgString(Arg));
8123 }
8124
8125 // Forward -fpass-plugin=name.so to -cc1.
8126 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8127 CmdArgs.push_back(
8128 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8129 A->claim();
8130 }
8131
8132 // Forward --vfsoverlay to -cc1.
8133 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8134 CmdArgs.push_back("--vfsoverlay");
8135 CmdArgs.push_back(A->getValue());
8136 A->claim();
8137 }
8138
8139 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8140 options::OPT_fno_safe_buffer_usage_suggestions);
8141
8142 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8143 options::OPT_fno_experimental_late_parse_attributes);
8144
8145 if (Args.hasFlag(options::OPT_funique_source_file_names,
8146 options::OPT_fno_unique_source_file_names, false)) {
8147 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8148 A->render(Args, CmdArgs);
8149 else
8150 CmdArgs.push_back(Args.MakeArgString(
8151 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8152 }
8153
8154 if (Args.hasFlag(
8155 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8156 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8157 false) ||
8158 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8159 options::OPT_fno_experimental_pointer_field_protection_abi,
8160 false))
8161 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8162
8163 if (!IsCudaDevice) {
8164 Args.addOptInFlag(
8165 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8166 options::OPT_fno_experimental_pointer_field_protection_abi);
8167 Args.addOptInFlag(
8168 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8169 options::OPT_fno_experimental_pointer_field_protection_tagged);
8170 }
8171
8172 // Setup statistics file output.
8173 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8174 if (!StatsFile.empty()) {
8175 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8177 CmdArgs.push_back("-stats-file-append");
8178 }
8179
8180 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8181 // parser.
8182 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8183 Arg->claim();
8184 // -finclude-default-header flag is for preprocessor,
8185 // do not pass it to other cc1 commands when save-temps is enabled
8186 if (C.getDriver().isSaveTempsEnabled() &&
8188 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8189 continue;
8190 }
8191 CmdArgs.push_back(Arg->getValue());
8192 }
8193 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8194 A->claim();
8195
8196 // We translate this by hand to the -cc1 argument, since nightly test uses
8197 // it and developers have been trained to spell it with -mllvm. Both
8198 // spellings are now deprecated and should be removed.
8199 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8200 CmdArgs.push_back("-disable-llvm-optzns");
8201 } else {
8202 A->render(Args, CmdArgs);
8203 }
8204 }
8205
8206 // This needs to run after -Xclang argument forwarding to pick up the target
8207 // features enabled through -Xclang -target-feature flags.
8208 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8209
8210 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8211
8212#if CLANG_ENABLE_CIR
8213 // Forward -mmlir arguments to to the MLIR option parser.
8214 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8215 A->claim();
8216 A->render(Args, CmdArgs);
8217 }
8218#endif // CLANG_ENABLE_CIR
8219
8220 // With -save-temps, we want to save the unoptimized bitcode output from the
8221 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8222 // by the frontend.
8223 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8224 // has slightly different breakdown between stages.
8225 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8226 // pristine IR generated by the frontend. Ideally, a new compile action should
8227 // be added so both IR can be captured.
8228 if ((C.getDriver().isSaveTempsEnabled() ||
8230 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8232 CmdArgs.push_back("-disable-llvm-passes");
8233
8234 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8235
8236 const char *Exec = D.getDriverProgramPath();
8237
8238 // Optionally embed the -cc1 level arguments into the debug info or a
8239 // section, for build analysis.
8240 // Also record command line arguments into the debug info if
8241 // -grecord-gcc-switches options is set on.
8242 // By default, -gno-record-gcc-switches is set on and no recording.
8243 auto GRecordSwitches = false;
8244 auto FRecordSwitches = false;
8245 bool DXRecordSwitches = false;
8246 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8247 DXRecordSwitches)) {
8248 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8249 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8250 CmdArgs.push_back("-dwarf-debug-flags");
8251 CmdArgs.push_back(FlagsArgString);
8252 }
8253 if (FRecordSwitches) {
8254 CmdArgs.push_back("-record-command-line");
8255 CmdArgs.push_back(FlagsArgString);
8256 }
8257 if (DXRecordSwitches) {
8258 CmdArgs.push_back("-fdx-record-command-line");
8259 CmdArgs.push_back(FlagsArgString);
8260 }
8261 }
8262
8263 // Host-side offloading compilation receives all device-side outputs. Include
8264 // them in the host compilation depending on the target. If the host inputs
8265 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8266 if ((IsCuda || IsHIP) && CudaDeviceInput) {
8267 CmdArgs.push_back("-fcuda-include-gpubinary");
8268 CmdArgs.push_back(CudaDeviceInput->getFilename());
8269 } else if (!HostOffloadingInputs.empty()) {
8270 if ((IsCuda || IsHIP) && !IsRDCMode) {
8271 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8272 CmdArgs.push_back("-fcuda-include-gpubinary");
8273 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8274 } else {
8275 for (const InputInfo Input : HostOffloadingInputs)
8276 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8277 TC.getInputFilename(Input)));
8278 }
8279 }
8280
8281 if (IsCuda) {
8282 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
8283 options::OPT_fno_cuda_short_ptr, false))
8284 CmdArgs.push_back("-fcuda-short-ptr");
8285 }
8286
8287 if (IsCuda || IsHIP) {
8288 // Determine the original source input.
8289 const Action *SourceAction = &JA;
8290 while (SourceAction->getKind() != Action::InputClass) {
8291 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8292 SourceAction = SourceAction->getInputs()[0];
8293 }
8294 auto CUID = cast<InputAction>(SourceAction)->getId();
8295 if (!CUID.empty())
8296 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8297
8298 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8299 // be overriden by -fno-gpu-approx-transcendentals.
8300 bool UseApproxTranscendentals = Args.hasFlag(
8301 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8302 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8303 options::OPT_fno_gpu_approx_transcendentals,
8304 UseApproxTranscendentals))
8305 CmdArgs.push_back("-fgpu-approx-transcendentals");
8306 } else {
8307 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8308 options::OPT_fno_gpu_approx_transcendentals);
8309 }
8310
8311 if (IsHIP) {
8312 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8313 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8314 }
8315
8316 Args.AddAllArgs(CmdArgs,
8317 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8318
8319 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8320 options::OPT_fno_offload_uniform_block);
8321
8322 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8323 options::OPT_fno_offload_implicit_host_device_templates);
8324
8325 if (IsCudaDevice || IsHIPDevice) {
8326 StringRef InlineThresh =
8327 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8328 if (!InlineThresh.empty()) {
8329 std::string ArgStr =
8330 std::string("-inline-threshold=") + InlineThresh.str();
8331 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8332 }
8333 }
8334
8335 if (IsHIPDevice)
8336 Args.addOptOutFlag(CmdArgs,
8337 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8338 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8339
8340 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8341 // to specify the result of the compile phase on the host, so the meaningful
8342 // device declarations can be identified. Also, -fopenmp-is-target-device is
8343 // passed along to tell the frontend that it is generating code for a device,
8344 // so that only the relevant declarations are emitted.
8345 if (IsOpenMPDevice) {
8346 CmdArgs.push_back("-fopenmp-is-target-device");
8347 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8348 if (Args.hasArg(options::OPT_foffload_via_llvm))
8349 CmdArgs.push_back("-fcuda-is-device");
8350
8351 if (OpenMPDeviceInput) {
8352 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8353 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8354 }
8355 }
8356
8357 if (Triple.isAMDGPU() ||
8358 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8359 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8360
8361 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8362 options::OPT_mno_unsafe_fp_atomics);
8363 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8364 options::OPT_mno_amdgpu_ieee);
8365 }
8366
8367 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8368
8369 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8370 options::OPT_fno_devirtualize_speculatively,
8371 /*Default value*/ false))
8372 CmdArgs.push_back("-fdevirtualize-speculatively");
8373
8374 bool VirtualFunctionElimination =
8375 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8376 options::OPT_fno_virtual_function_elimination, false);
8377 if (VirtualFunctionElimination) {
8378 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8379 // in the future).
8380 if (LTOMode != LTOK_Full)
8381 D.Diag(diag::err_drv_argument_only_allowed_with)
8382 << "-fvirtual-function-elimination"
8383 << "-flto=full";
8384
8385 CmdArgs.push_back("-fvirtual-function-elimination");
8386 }
8387
8388 // VFE requires whole-program-vtables, and enables it by default.
8389 bool WholeProgramVTables = Args.hasFlag(
8390 options::OPT_fwhole_program_vtables,
8391 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8392 if (VirtualFunctionElimination && !WholeProgramVTables) {
8393 D.Diag(diag::err_drv_argument_not_allowed_with)
8394 << "-fno-whole-program-vtables"
8395 << "-fvirtual-function-elimination";
8396 }
8397
8398 if (WholeProgramVTables) {
8399 // PS4 uses the legacy LTO API, which does not support this feature in
8400 // ThinLTO mode.
8401 bool IsPS4 = getToolChain().getTriple().isPS4();
8402
8403 // Check if we passed LTO options but they were suppressed because this is a
8404 // device offloading action, or we passed device offload LTO options which
8405 // were suppressed because this is not the device offload action.
8406 // Check if we are using PS4 in regular LTO mode.
8407 // Otherwise, issue an error.
8408
8409 auto OtherLTOMode = TC.getLTOMode(
8410 Args, IsDeviceOffloadAction ? Action::OFK_None
8411 : static_cast<Action::OffloadKind>(
8412 C.getActiveOffloadKinds()));
8413 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8414
8415 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8416 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8417 D.Diag(diag::err_drv_argument_only_allowed_with)
8418 << "-fwhole-program-vtables"
8419 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8420
8421 // Propagate -fwhole-program-vtables if this is an LTO compile.
8422 if (IsUsingLTO)
8423 CmdArgs.push_back("-fwhole-program-vtables");
8424 }
8425
8426 bool DefaultsSplitLTOUnit =
8427 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8428 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8429 (!Triple.isPS4() && UnifiedLTO);
8430 bool SplitLTOUnit =
8431 Args.hasFlag(options::OPT_fsplit_lto_unit,
8432 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8433 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8434 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8435 << "-fsanitize=cfi";
8436 if (SplitLTOUnit)
8437 CmdArgs.push_back("-fsplit-lto-unit");
8438
8439 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8440 options::OPT_fno_fat_lto_objects)) {
8441 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8442 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8443 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8444 D.Diag(diag::err_drv_unsupported_opt_for_target)
8445 << A->getAsString(Args) << TC.getTripleString();
8446 }
8447 CmdArgs.push_back(Args.MakeArgString(
8448 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8449 CmdArgs.push_back("-flto-unit");
8450 CmdArgs.push_back("-ffat-lto-objects");
8451 A->render(Args, CmdArgs);
8452 }
8453 }
8454
8455 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8456
8457 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8458 options::OPT_fno_force_enable_int128)) {
8459 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8460 CmdArgs.push_back("-fforce-enable-int128");
8461 }
8462
8463 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8464 options::OPT_fno_keep_static_consts);
8465 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8466 options::OPT_fno_keep_persistent_storage_variables);
8467 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8468 options::OPT_fno_complete_member_pointers);
8469 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8470 A->render(Args, CmdArgs);
8471
8472 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8473
8474 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8475
8476 if (Triple.isAArch64() &&
8477 (Args.hasArg(options::OPT_mno_fmv) ||
8478 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
8479 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8480 // Disable Function Multiversioning on AArch64 target.
8481 CmdArgs.push_back("-target-feature");
8482 CmdArgs.push_back("-fmv");
8483 }
8484
8485 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8486 (TC.getTriple().isOSBinFormatELF() ||
8487 TC.getTriple().isOSBinFormatCOFF()) &&
8488 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8489 !TC.getTriple().isOSNetBSD() &&
8490 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8491 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8492 CmdArgs.push_back("-faddrsig");
8493
8494 const bool HasDefaultDwarf2CFIASM =
8495 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8496 (EH || UnwindTables || AsyncUnwindTables ||
8497 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8498 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8499 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8500 CmdArgs.push_back("-fdwarf2-cfi-asm");
8501
8502 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8503 std::string Str = A->getAsString(Args);
8504 if (!TC.getTriple().isOSBinFormatELF())
8505 D.Diag(diag::err_drv_unsupported_opt_for_target)
8506 << Str << TC.getTripleString();
8507 CmdArgs.push_back(Args.MakeArgString(Str));
8508 }
8509
8510 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8511 // the -cc1 command easier to edit when reproducing compiler crashes.
8512 if (Output.getType() == types::TY_Dependencies) {
8513 // Handled with other dependency code.
8514 } else if (Output.isFilename()) {
8515 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8516 Output.getType() == clang::driver::types::TY_IFS) {
8517 SmallString<128> OutputFilename(Output.getFilename());
8518 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8519 CmdArgs.push_back("-o");
8520 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8521 } else {
8522 CmdArgs.push_back("-o");
8523 CmdArgs.push_back(Output.getFilename());
8524 }
8525 } else {
8526 assert(Output.isNothing() && "Invalid output.");
8527 }
8528
8529 addDashXForInput(Args, Input, CmdArgs);
8530
8531 ArrayRef<InputInfo> FrontendInputs = Input;
8532 if (IsExtractAPI)
8533 FrontendInputs = ExtractAPIInputs;
8534 else if (Input.isNothing())
8535 FrontendInputs = {};
8536
8537 for (const InputInfo &Input : FrontendInputs) {
8538 if (Input.isFilename())
8539 CmdArgs.push_back(Input.getFilename());
8540 else
8541 Input.getInputArg().renderAsInput(Args, CmdArgs);
8542 }
8543
8544 if (D.CC1Main && !D.CCGenDiagnostics) {
8545 // Invoke the CC1 directly in this process
8546 C.addCommand(std::make_unique<CC1Command>(
8547 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8548 Output, D.getPrependArg()));
8549 } else {
8550 C.addCommand(std::make_unique<Command>(
8551 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8552 Output, D.getPrependArg()));
8553 }
8554
8555 // Make the compile command echo its inputs for /showFilenames.
8556 if (Output.getType() == types::TY_Object &&
8557 Args.hasFlag(options::OPT__SLASH_showFilenames,
8558 options::OPT__SLASH_showFilenames_, false)) {
8559 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8560 }
8561
8562 if (Arg *A = Args.getLastArg(options::OPT_pg))
8563 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8564 !Args.hasArg(options::OPT_mfentry))
8565 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8566 << A->getAsString(Args);
8567
8568 // Claim some arguments which clang supports automatically.
8569
8570 // -fpch-preprocess is used with gcc to add a special marker in the output to
8571 // include the PCH file.
8572 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8573
8574 // Claim some arguments which clang doesn't support, but we don't
8575 // care to warn the user about.
8576 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8577 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8578
8579 // Disable warnings for clang -E -emit-llvm foo.c
8580 Args.ClaimAllArgs(options::OPT_emit_llvm);
8581}
8582
8583Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8584 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8585 // as it is for other tools. Some operations on a Tool actually test
8586 // whether that tool is Clang based on the Tool's Name as a string.
8587 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8588
8590
8591/// Add options related to the Objective-C runtime/ABI.
8592///
8593/// Returns true if the runtime is non-fragile.
8594ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8595 const InputInfoList &inputs,
8596 ArgStringList &cmdArgs,
8597 RewriteKind rewriteKind) const {
8598 // Look for the controlling runtime option.
8599 Arg *runtimeArg =
8600 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8601 options::OPT_fobjc_runtime_EQ);
8602
8603 // Just forward -fobjc-runtime= to the frontend. This supercedes
8604 // options about fragility.
8605 if (runtimeArg &&
8606 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8607 ObjCRuntime runtime;
8608 StringRef value = runtimeArg->getValue();
8609 if (runtime.tryParse(value)) {
8610 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8611 << value;
8612 }
8613 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8614 (runtime.getVersion() >= VersionTuple(2, 0)))
8615 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8616 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8618 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8619 << runtime.getVersion().getMajor();
8620 }
8621
8622 runtimeArg->render(args, cmdArgs);
8623 return runtime;
8624 }
8625
8626 // Otherwise, we'll need the ABI "version". Version numbers are
8627 // slightly confusing for historical reasons:
8628 // 1 - Traditional "fragile" ABI
8629 // 2 - Non-fragile ABI, version 1
8630 // 3 - Non-fragile ABI, version 2
8631 unsigned objcABIVersion = 1;
8632 // If -fobjc-abi-version= is present, use that to set the version.
8633 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8634 StringRef value = abiArg->getValue();
8635 if (value == "1")
8636 objcABIVersion = 1;
8637 else if (value == "2")
8638 objcABIVersion = 2;
8639 else if (value == "3")
8640 objcABIVersion = 3;
8641 else
8642 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8643 } else {
8644 // Otherwise, determine if we are using the non-fragile ABI.
8645 bool nonFragileABIIsDefault =
8646 (rewriteKind == RK_NonFragile ||
8647 (rewriteKind == RK_None &&
8649 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8650 options::OPT_fno_objc_nonfragile_abi,
8651 nonFragileABIIsDefault)) {
8652// Determine the non-fragile ABI version to use.
8653#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8654 unsigned nonFragileABIVersion = 1;
8655#else
8656 unsigned nonFragileABIVersion = 2;
8657#endif
8658
8659 if (Arg *abiArg =
8660 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8661 StringRef value = abiArg->getValue();
8662 if (value == "1")
8663 nonFragileABIVersion = 1;
8664 else if (value == "2")
8665 nonFragileABIVersion = 2;
8666 else
8667 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8668 << value;
8669 }
8670
8671 objcABIVersion = 1 + nonFragileABIVersion;
8672 } else {
8673 objcABIVersion = 1;
8674 }
8675 }
8676
8677 // We don't actually care about the ABI version other than whether
8678 // it's non-fragile.
8679 bool isNonFragile = objcABIVersion != 1;
8680
8681 // If we have no runtime argument, ask the toolchain for its default runtime.
8682 // However, the rewriter only really supports the Mac runtime, so assume that.
8683 ObjCRuntime runtime;
8684 if (!runtimeArg) {
8685 switch (rewriteKind) {
8686 case RK_None:
8687 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8688 break;
8689 case RK_Fragile:
8690 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8691 break;
8692 case RK_NonFragile:
8693 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8694 break;
8695 }
8696
8697 // -fnext-runtime
8698 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8699 // On Darwin, make this use the default behavior for the toolchain.
8700 if (getToolChain().getTriple().isOSDarwin()) {
8701 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8702
8703 // Otherwise, build for a generic macosx port.
8704 } else {
8705 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8706 }
8707
8708 // -fgnu-runtime
8709 } else {
8710 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8711 // Legacy behaviour is to target the gnustep runtime if we are in
8712 // non-fragile mode or the GCC runtime in fragile mode.
8713 if (isNonFragile)
8714 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8715 else
8716 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8717 }
8718
8719 if (llvm::any_of(inputs, [](const InputInfo &input) {
8720 return types::isObjC(input.getType());
8721 }))
8722 cmdArgs.push_back(
8723 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8724 return runtime;
8725}
8726
8727static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8728 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8729 I += HaveDash;
8730 return !HaveDash;
8731}
8732
8733namespace {
8734struct EHFlags {
8735 bool Synch = false;
8736 bool Asynch = false;
8737 bool NoUnwindC = false;
8738};
8739} // end anonymous namespace
8740
8741/// /EH controls whether to run destructor cleanups when exceptions are
8742/// thrown. There are three modifiers:
8743/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8744/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8745/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8746/// - c: Assume that extern "C" functions are implicitly nounwind.
8747/// The default is /EHs-c-, meaning cleanups are disabled.
8748static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8749 bool isWindowsMSVC) {
8750 EHFlags EH;
8751
8752 std::vector<std::string> EHArgs =
8753 Args.getAllArgValues(options::OPT__SLASH_EH);
8754 for (const auto &EHVal : EHArgs) {
8755 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8756 switch (EHVal[I]) {
8757 case 'a':
8758 EH.Asynch = maybeConsumeDash(EHVal, I);
8759 if (EH.Asynch) {
8760 // Async exceptions are Windows MSVC only.
8761 if (!isWindowsMSVC) {
8762 EH.Asynch = false;
8763 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8764 continue;
8765 }
8766 EH.Synch = false;
8767 }
8768 continue;
8769 case 'c':
8770 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8771 continue;
8772 case 's':
8773 EH.Synch = maybeConsumeDash(EHVal, I);
8774 if (EH.Synch)
8775 EH.Asynch = false;
8776 continue;
8777 default:
8778 break;
8779 }
8780 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8781 break;
8782 }
8783 }
8784 // The /GX, /GX- flags are only processed if there are not /EH flags.
8785 // The default is that /GX is not specified.
8786 if (EHArgs.empty() &&
8787 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8788 /*Default=*/false)) {
8789 EH.Synch = true;
8790 EH.NoUnwindC = true;
8791 }
8792
8793 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8794 EH.Synch = false;
8795 EH.NoUnwindC = false;
8796 EH.Asynch = false;
8797 }
8798
8799 return EH;
8800}
8801
8802void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8803 ArgStringList &CmdArgs) const {
8804 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8805
8806 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8807
8808 if (Arg *ShowIncludes =
8809 Args.getLastArg(options::OPT__SLASH_showIncludes,
8810 options::OPT__SLASH_showIncludes_user)) {
8811 CmdArgs.push_back("--show-includes");
8812 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8813 CmdArgs.push_back("-sys-header-deps");
8814 }
8815
8816 // This controls whether or not we emit RTTI data for polymorphic types.
8817 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8818 /*Default=*/false))
8819 CmdArgs.push_back("-fno-rtti-data");
8820
8821 // This controls whether or not we emit stack-protector instrumentation.
8822 // In MSVC, Buffer Security Check (/GS) is on by default.
8823 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8824 /*Default=*/true)) {
8825 CmdArgs.push_back("-stack-protector");
8826 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8827 }
8828
8829 const Driver &D = getToolChain().getDriver();
8830
8831 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8832 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8833 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8834 if (types::isCXX(InputType))
8835 CmdArgs.push_back("-fcxx-exceptions");
8836 CmdArgs.push_back("-fexceptions");
8837 if (EH.Asynch)
8838 CmdArgs.push_back("-fasync-exceptions");
8839 }
8840 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8841 CmdArgs.push_back("-fexternc-nounwind");
8842
8843 // /EP should expand to -E -P.
8844 if (Args.hasArg(options::OPT__SLASH_EP)) {
8845 CmdArgs.push_back("-E");
8846 CmdArgs.push_back("-P");
8847 }
8848
8849 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8850 options::OPT__SLASH_Zc_dllexportInlines,
8851 false)) {
8852 CmdArgs.push_back("-fno-dllexport-inlines");
8853 }
8854
8855 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8856 options::OPT__SLASH_Zc_wchar_t, false)) {
8857 CmdArgs.push_back("-fno-wchar");
8858 }
8859
8860 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8861 llvm::Triple::ArchType Arch = getToolChain().getArch();
8862 std::vector<std::string> Values =
8863 Args.getAllArgValues(options::OPT__SLASH_arch);
8864 if (!Values.empty()) {
8865 llvm::SmallSet<std::string, 4> SupportedArches;
8866 if (Arch == llvm::Triple::x86)
8867 SupportedArches.insert("IA32");
8868
8869 for (auto &V : Values)
8870 if (!SupportedArches.contains(V))
8871 D.Diag(diag::err_drv_argument_not_allowed_with)
8872 << std::string("/arch:").append(V) << "/kernel";
8873 }
8874
8875 CmdArgs.push_back("-fno-rtti");
8876 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8877 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8878 << "/kernel";
8879 }
8880
8881 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8882 options::OPT__SLASH_vlen_EQ_256,
8883 options::OPT__SLASH_vlen_EQ_512)) {
8884 llvm::Triple::ArchType AT = getToolChain().getArch();
8885 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8886 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8887 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8888 "AVX10.2"};
8889
8890 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8891 if (Arch512.contains(Arch))
8892 CmdArgs.push_back("-mprefer-vector-width=512");
8893 else
8894 D.Diag(diag::warn_drv_argument_not_allowed_with)
8895 << "/vlen=512" << std::string("/arch:").append(Arch);
8896 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8897 if (Arch512.contains(Arch))
8898 CmdArgs.push_back("-mprefer-vector-width=256");
8899 else if (Arch != "AVX" && Arch != "AVX2")
8900 D.Diag(diag::warn_drv_argument_not_allowed_with)
8901 << "/vlen=256" << std::string("/arch:").append(Arch);
8902 } else {
8903 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8904 CmdArgs.push_back("-mprefer-vector-width=256");
8905 }
8906 } else {
8907 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8908 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8909 CmdArgs.push_back("-mprefer-vector-width=256");
8910 CmdArgs.push_back("-target-feature");
8911 CmdArgs.push_back("-amx-tile");
8912 }
8913 if (Arch == "AVX10.2") {
8914 CmdArgs.push_back("-target-feature");
8915 CmdArgs.push_back("+avx10.2");
8916 }
8917 }
8918
8919 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8920 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8921 if (MostGeneralArg && BestCaseArg)
8922 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8923 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8924
8925 if (MostGeneralArg) {
8926 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8927 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8928 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8929
8930 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8931 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8932 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8933 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8934 << FirstConflict->getAsString(Args)
8935 << SecondConflict->getAsString(Args);
8936
8937 if (SingleArg)
8938 CmdArgs.push_back("-fms-memptr-rep=single");
8939 else if (MultipleArg)
8940 CmdArgs.push_back("-fms-memptr-rep=multiple");
8941 else
8942 CmdArgs.push_back("-fms-memptr-rep=virtual");
8943 }
8944
8945 if (Args.hasArg(options::OPT_regcall4))
8946 CmdArgs.push_back("-regcall4");
8947
8948 // Parse the default calling convention options.
8949 if (Arg *CCArg =
8950 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8951 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8952 options::OPT__SLASH_Gregcall)) {
8953 unsigned DCCOptId = CCArg->getOption().getID();
8954 const char *DCCFlag = nullptr;
8955 bool ArchSupported = !isNVPTX;
8956 llvm::Triple::ArchType Arch = getToolChain().getArch();
8957 switch (DCCOptId) {
8958 case options::OPT__SLASH_Gd:
8959 DCCFlag = "-fdefault-calling-conv=cdecl";
8960 break;
8961 case options::OPT__SLASH_Gr:
8962 ArchSupported = Arch == llvm::Triple::x86;
8963 DCCFlag = "-fdefault-calling-conv=fastcall";
8964 break;
8965 case options::OPT__SLASH_Gz:
8966 ArchSupported = Arch == llvm::Triple::x86;
8967 DCCFlag = "-fdefault-calling-conv=stdcall";
8968 break;
8969 case options::OPT__SLASH_Gv:
8970 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8971 DCCFlag = "-fdefault-calling-conv=vectorcall";
8972 break;
8973 case options::OPT__SLASH_Gregcall:
8974 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8975 DCCFlag = "-fdefault-calling-conv=regcall";
8976 break;
8977 }
8978
8979 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8980 if (ArchSupported && DCCFlag)
8981 CmdArgs.push_back(DCCFlag);
8982 }
8983
8984 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8985 CmdArgs.push_back("-regcall4");
8986
8987 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8988
8989 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8990 CmdArgs.push_back("-fdiagnostics-format");
8991 CmdArgs.push_back("msvc");
8992 }
8993
8994 if (Args.hasArg(options::OPT__SLASH_kernel))
8995 CmdArgs.push_back("-fms-kernel");
8996
8997 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
8998 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
8999 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9000 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9001 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9002 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9003
9004 // Handle the various /guard options. We don't immediately push back clang
9005 // args since there are /d2 args that can modify the behavior of /guard:cf.
9006 bool HasCFGuard = false;
9007 bool HasCFGuardNoChecks = false;
9008 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9009 StringRef GuardArgs = A->getValue();
9010 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9011 // "ehcont-".
9012 if (GuardArgs.equals_insensitive("cf")) {
9013 // Emit CFG instrumentation and the table of address-taken functions.
9014 HasCFGuard = true;
9015 HasCFGuardNoChecks = false;
9016 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9017 // Emit only the table of address-taken functions.
9018 HasCFGuard = false;
9019 HasCFGuardNoChecks = true;
9020 } else if (GuardArgs.equals_insensitive("ehcont")) {
9021 // Emit EH continuation table.
9022 CmdArgs.push_back("-ehcontguard");
9023 } else if (GuardArgs.equals_insensitive("cf-") ||
9024 GuardArgs.equals_insensitive("ehcont-")) {
9025 // Do nothing, but we might want to emit a security warning in future.
9026 } else {
9027 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9028 }
9029 A->claim();
9030 }
9031
9032 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9033 // If CFG is not enabled, it is a no-op.
9034 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9035 if (HasCFGuard) {
9036 HasCFGuard = false;
9037 HasCFGuardNoChecks = true;
9038 }
9039 }
9040
9041 if (HasCFGuard)
9042 CmdArgs.push_back("-cfguard");
9043 else if (HasCFGuardNoChecks)
9044 CmdArgs.push_back("-cfguard-no-checks");
9045
9046 // Control Flow Guard mechanism for Windows.
9047 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9048 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9049 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9050 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9051
9052 for (const auto &FuncOverride :
9053 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9054 CmdArgs.push_back(Args.MakeArgString(
9055 Twine("-loader-replaceable-function=") + FuncOverride));
9056 }
9057
9058 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9059 CmdArgs.push_back("-Wdate-time");
9060
9061 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9062 D.Diag(diag::err_drv_argument_not_allowed_with)
9063 << "/experimental:deterministic"
9064 << "/Brepro-";
9065 }
9066 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9067 // deterministic result, but we force this timestamp to 0, which also
9068 // produces deterministic result.
9069 CmdArgs.push_back("-mno-incremental-linker-compatible");
9070 }
9071
9072 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9073 options::OPT__SLASH_d1nodatetime_, false);
9074
9075 if (HasNoDateTime)
9076 CmdArgs.push_back("-init-datetime-macros=undefined");
9077
9078 // /Brepro is an alias for -mincremental-linker-compatible option.
9079 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9080 options::OPT_mno_incremental_linker_compatible,
9081 getToolChain()
9082 .getTriple()
9083 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9084 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9085 // This option does not allow the user redefinitions for these macros.
9086 if (!HasNoDateTime)
9087 CmdArgs.push_back("-init-datetime-macros=literalone");
9088 }
9089}
9090
9091const char *Clang::getBaseInputName(const ArgList &Args,
9092 const InputInfo &Input) {
9093 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9094}
9095
9096const char *Clang::getBaseInputStem(const ArgList &Args,
9097 const InputInfoList &Inputs) {
9098 const char *Str = getBaseInputName(Args, Inputs[0]);
9099
9100 if (const char *End = strrchr(Str, '.'))
9101 return Args.MakeArgString(std::string(Str, End));
9102
9103 return Str;
9104}
9105
9106const char *Clang::getDependencyFileName(const ArgList &Args,
9107 const InputInfoList &Inputs) {
9108 // FIXME: Think about this more.
9109
9110 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9111 SmallString<128> OutputFilename(OutputOpt->getValue());
9112 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9113 return Args.MakeArgString(OutputFilename);
9114 }
9115
9116 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9117}
9118
9119// Begin ClangAs
9120
9121void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9122 ArgStringList &CmdArgs) const {
9123 StringRef CPUName;
9124 StringRef ABIName;
9125 const llvm::Triple &Triple = getToolChain().getTriple();
9126 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9127
9128 CmdArgs.push_back("-target-abi");
9129 CmdArgs.push_back(ABIName.data());
9130}
9131
9132void ClangAs::AddX86TargetArgs(const ArgList &Args,
9133 ArgStringList &CmdArgs) const {
9134 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9135 /*IsLTO=*/false);
9136
9137 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9138 StringRef Value = A->getValue();
9139 if (Value == "intel" || Value == "att") {
9140 CmdArgs.push_back("-mllvm");
9141 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9142 } else {
9143 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9144 << A->getSpelling() << Value;
9145 }
9146 }
9147}
9148
9149void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9150 ArgStringList &CmdArgs) const {
9151 CmdArgs.push_back("-target-abi");
9152 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9154 .data());
9155}
9156
9157void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9158 ArgStringList &CmdArgs) const {
9159 const llvm::Triple &Triple = getToolChain().getTriple();
9160 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9161
9162 CmdArgs.push_back("-target-abi");
9163 CmdArgs.push_back(ABIName.data());
9164
9165 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9166 options::OPT_mno_default_build_attributes, true)) {
9167 CmdArgs.push_back("-mllvm");
9168 CmdArgs.push_back("-riscv-add-build-attributes");
9169 }
9170}
9171
9173 const InputInfo &Output, const InputInfoList &Inputs,
9174 const ArgList &Args,
9175 const char *LinkingOutput) const {
9176 ArgStringList CmdArgs;
9177
9178 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9179 const InputInfo &Input = Inputs[0];
9180
9181 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9182 const std::string &TripleStr = Triple.getTriple();
9183 const auto &D = getToolChain().getDriver();
9184
9185 // Don't warn about "clang -w -c foo.s"
9186 Args.ClaimAllArgs(options::OPT_w);
9187 // and "clang -emit-llvm -c foo.s"
9188 Args.ClaimAllArgs(options::OPT_emit_llvm);
9189
9190 claimNoWarnArgs(Args);
9191
9192 // Invoke ourselves in -cc1as mode.
9193 //
9194 // FIXME: Implement custom jobs for internal actions.
9195 CmdArgs.push_back("-cc1as");
9196
9197 // Add the "effective" target triple.
9198 CmdArgs.push_back("-triple");
9199 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9200
9202
9203 // Set the output mode, we currently only expect to be used as a real
9204 // assembler.
9205 CmdArgs.push_back("-filetype");
9206 CmdArgs.push_back("obj");
9207
9208 // Set the main file name, so that debug info works even with
9209 // -save-temps or preprocessed assembly.
9210 CmdArgs.push_back("-main-file-name");
9211 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9212
9213 // Add the target cpu
9214 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9215 if (!CPU.empty()) {
9216 CmdArgs.push_back("-target-cpu");
9217 CmdArgs.push_back(Args.MakeArgString(CPU));
9218 }
9219
9220 // Add the target features
9221 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9222
9223 // Ignore explicit -force_cpusubtype_ALL option.
9224 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9225
9226 // Pass along any -I options so we get proper .include search paths.
9227 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9228
9229 // Pass along any --embed-dir or similar options so we get proper embed paths.
9230 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9231
9232 // Determine the original source input.
9233 auto FindSource = [](const Action *S) -> const Action * {
9234 while (S->getKind() != Action::InputClass) {
9235 assert(!S->getInputs().empty() && "unexpected root action!");
9236 S = S->getInputs()[0];
9237 }
9238 return S;
9239 };
9240 const Action *SourceAction = FindSource(&JA);
9241
9242 // Forward -g and handle debug info related flags, assuming we are dealing
9243 // with an actual assembly file.
9244 bool WantDebug = false;
9245 Args.ClaimAllArgs(options::OPT_g_Group);
9246 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9247 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9248 !A->getOption().matches(options::OPT_ggdb0);
9249
9250 // If a -gdwarf argument appeared, remember it.
9251 bool EmitDwarf = false;
9252 if (const Arg *A = getDwarfNArg(Args))
9253 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9254
9255 bool EmitCodeView = false;
9256 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9257 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9258
9259 // If the user asked for debug info but did not explicitly specify -gcodeview
9260 // or -gdwarf, ask the toolchain for the default format.
9261 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9262 switch (getToolChain().getDefaultDebugFormat()) {
9263 case llvm::codegenoptions::DIF_CodeView:
9264 EmitCodeView = true;
9265 break;
9266 case llvm::codegenoptions::DIF_DWARF:
9267 EmitDwarf = true;
9268 break;
9269 }
9270 }
9271
9272 // If the arguments don't imply DWARF, don't emit any debug info here.
9273 if (!EmitDwarf)
9274 WantDebug = false;
9275
9276 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9277 llvm::codegenoptions::NoDebugInfo;
9278
9279 // Add the -fdebug-compilation-dir flag if needed.
9280 const char *DebugCompilationDir =
9281 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9282
9283 if (SourceAction->getType() == types::TY_Asm ||
9284 SourceAction->getType() == types::TY_PP_Asm) {
9285 // You might think that it would be ok to set DebugInfoKind outside of
9286 // the guard for source type, however there is a test which asserts
9287 // that some assembler invocation receives no -debug-info-kind,
9288 // and it's not clear whether that test is just overly restrictive.
9289 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9290 : llvm::codegenoptions::NoDebugInfo);
9291
9292 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9293 CmdArgs);
9294
9295 // Set the AT_producer to the clang version when using the integrated
9296 // assembler on assembly source files.
9297 CmdArgs.push_back("-dwarf-debug-producer");
9298 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9299
9300 // And pass along -I options
9301 Args.AddAllArgs(CmdArgs, options::OPT_I);
9302 }
9303 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9304 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9305 llvm::DebuggerKind::Default);
9306 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9307 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9308
9309 // Handle -fPIC et al -- the relocation-model affects the assembler
9310 // for some targets.
9311 llvm::Reloc::Model RelocationModel;
9312 unsigned PICLevel;
9313 bool IsPIE;
9314 std::tie(RelocationModel, PICLevel, IsPIE) =
9315 ParsePICArgs(getToolChain(), Args);
9316
9317 const char *RMName = RelocationModelName(RelocationModel);
9318 if (RMName) {
9319 CmdArgs.push_back("-mrelocation-model");
9320 CmdArgs.push_back(RMName);
9321 }
9322
9323 // Optionally embed the -cc1as level arguments into the debug info, for build
9324 // analysis.
9325 if (getToolChain().UseDwarfDebugFlags()) {
9326 ArgStringList OriginalArgs;
9327 for (const auto &Arg : Args)
9328 Arg->render(Args, OriginalArgs);
9329
9330 SmallString<256> Flags;
9331 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9332 escapeSpacesAndBackslashes(Exec, Flags);
9333 for (const char *OriginalArg : OriginalArgs) {
9334 SmallString<128> EscapedArg;
9335 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9336 Flags += " ";
9337 Flags += EscapedArg;
9338 }
9339 CmdArgs.push_back("-dwarf-debug-flags");
9340 CmdArgs.push_back(Args.MakeArgString(Flags));
9341 }
9342
9343 // FIXME: Add -static support, once we have it.
9344
9345 // Add target specific flags.
9346 switch (getToolChain().getArch()) {
9347 default:
9348 break;
9349
9350 case llvm::Triple::mips:
9351 case llvm::Triple::mipsel:
9352 case llvm::Triple::mips64:
9353 case llvm::Triple::mips64el:
9354 AddMIPSTargetArgs(Args, CmdArgs);
9355 break;
9356
9357 case llvm::Triple::x86:
9358 case llvm::Triple::x86_64:
9359 AddX86TargetArgs(Args, CmdArgs);
9360 break;
9361
9362 case llvm::Triple::arm:
9363 case llvm::Triple::armeb:
9364 case llvm::Triple::thumb:
9365 case llvm::Triple::thumbeb:
9366 // This isn't in AddARMTargetArgs because we want to do this for assembly
9367 // only, not C/C++.
9368 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9369 options::OPT_mno_default_build_attributes, true)) {
9370 CmdArgs.push_back("-mllvm");
9371 CmdArgs.push_back("-arm-add-build-attributes");
9372 }
9373 break;
9374
9375 case llvm::Triple::aarch64:
9376 case llvm::Triple::aarch64_32:
9377 case llvm::Triple::aarch64_be:
9378 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9379 CmdArgs.push_back("-mllvm");
9380 CmdArgs.push_back("-aarch64-mark-bti-property");
9381 }
9382 break;
9383
9384 case llvm::Triple::loongarch32:
9385 case llvm::Triple::loongarch64:
9386 AddLoongArchTargetArgs(Args, CmdArgs);
9387 break;
9388
9389 case llvm::Triple::riscv32:
9390 case llvm::Triple::riscv64:
9391 case llvm::Triple::riscv32be:
9392 case llvm::Triple::riscv64be:
9393 AddRISCVTargetArgs(Args, CmdArgs);
9394 break;
9395
9396 case llvm::Triple::hexagon:
9397 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9398 options::OPT_mno_default_build_attributes, true)) {
9399 CmdArgs.push_back("-mllvm");
9400 CmdArgs.push_back("-hexagon-add-build-attributes");
9401 }
9402 break;
9403 }
9404
9405 // Consume all the warning flags. Usually this would be handled more
9406 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9407 // doesn't handle that so rather than warning about unused flags that are
9408 // actually used, we'll lie by omission instead.
9409 // FIXME: Stop lying and consume only the appropriate driver flags
9410 Args.ClaimAllArgs(options::OPT_W_Group);
9411
9412 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9413 getToolChain().getDriver());
9414
9415 // Forward -Xclangas arguments to -cc1as
9416 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9417 Arg->claim();
9418 CmdArgs.push_back(Arg->getValue());
9419 }
9420
9421 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9422
9423 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9424 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9425 Output.getFilename());
9426
9427 // Fixup any previous commands that use -object-file-name because when we
9428 // generated them, the final .obj name wasn't yet known.
9429 for (Command &J : C.getJobs()) {
9430 if (SourceAction != FindSource(&J.getSource()))
9431 continue;
9432 auto &JArgs = J.getArguments();
9433 for (unsigned I = 0; I < JArgs.size(); ++I) {
9434 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9435 Output.isFilename()) {
9436 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9437 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9438 Output.getFilename());
9439 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9440 J.replaceArguments(NewArgs);
9441 break;
9442 }
9443 }
9444 }
9445
9446 assert(Output.isFilename() && "Unexpected lipo output.");
9447 CmdArgs.push_back("-o");
9448 CmdArgs.push_back(Output.getFilename());
9449
9450 const llvm::Triple &T = getToolChain().getTriple();
9451 Arg *A;
9452 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9453 T.isOSBinFormatELF()) {
9454 CmdArgs.push_back("-split-dwarf-output");
9455 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9456 }
9457
9458 if (Triple.isAMDGPU())
9459 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9460
9461 assert(Input.isFilename() && "Invalid input.");
9462 CmdArgs.push_back(Input.getFilename());
9463
9464 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9465 if (D.CC1Main && !D.CCGenDiagnostics) {
9466 // Invoke cc1as directly in this process.
9467 C.addCommand(std::make_unique<CC1Command>(
9468 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9469 Output, D.getPrependArg()));
9470 } else {
9471 C.addCommand(std::make_unique<Command>(
9472 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9473 Output, D.getPrependArg()));
9474 }
9475}
9476
9477// Begin OffloadBundler
9479 const InputInfo &Output,
9480 const InputInfoList &Inputs,
9481 const llvm::opt::ArgList &TCArgs,
9482 const char *LinkingOutput) const {
9483 // The version with only one output is expected to refer to a bundling job.
9484 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9485
9486 // The bundling command looks like this:
9487 // clang-offload-bundler -type=bc
9488 // -targets=host-triple,openmp-triple1,openmp-triple2
9489 // -output=output_file
9490 // -input=unbundle_file_host
9491 // -input=unbundle_file_tgt1
9492 // -input=unbundle_file_tgt2
9493
9494 ArgStringList CmdArgs;
9495
9496 // Get the type.
9497 CmdArgs.push_back(TCArgs.MakeArgString(
9498 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9499
9500 assert(JA.getInputs().size() == Inputs.size() &&
9501 "Not have inputs for all dependence actions??");
9502
9503 // Get the targets.
9504 SmallString<128> Triples;
9505 Triples += "-targets=";
9506 for (unsigned I = 0; I < Inputs.size(); ++I) {
9507 if (I)
9508 Triples += ',';
9509
9510 // Find ToolChain for this input.
9512 const ToolChain *CurTC = &getToolChain();
9513 const Action *CurDep = JA.getInputs()[I];
9514
9515 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9516 CurTC = nullptr;
9517 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9518 assert(CurTC == nullptr && "Expected one dependence!");
9519 CurKind = A->getOffloadingDeviceKind();
9520 CurTC = TC;
9521 });
9522 }
9523 Triples += Action::GetOffloadKindName(CurKind);
9524 Triples += '-';
9525 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9526 TCArgs, CurDep->getOffloadingArch()))
9527 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9528
9529 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9530 Triples += '-';
9531 Triples += CurDep->getOffloadingArch().ArchName;
9532 }
9533 }
9534 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9535
9536 // Get bundled file command.
9537 CmdArgs.push_back(
9538 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9539
9540 // Get unbundled files command.
9541 for (unsigned I = 0; I < Inputs.size(); ++I) {
9543 UB += "-input=";
9544
9545 // Find ToolChain for this input.
9546 const ToolChain *CurTC = &getToolChain();
9547 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9548 CurTC = nullptr;
9549 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9550 assert(CurTC == nullptr && "Expected one dependence!");
9551 CurTC = TC;
9552 });
9553 UB += C.addTempFile(
9554 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9555 } else {
9556 UB += CurTC->getInputFilename(Inputs[I]);
9557 }
9558 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9559 }
9560 addOffloadCompressArgs(TCArgs, CmdArgs);
9561 // All the inputs are encoded as commands.
9562 C.addCommand(std::make_unique<Command>(
9563 JA, *this, ResponseFileSupport::None(),
9564 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9565 CmdArgs, ArrayRef<InputInfo>(), Output));
9566}
9567
9569 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9570 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9571 const char *LinkingOutput) const {
9572 // The version with multiple outputs is expected to refer to a unbundling job.
9573 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9574
9575 // The unbundling command looks like this:
9576 // clang-offload-bundler -type=bc
9577 // -targets=host-triple,openmp-triple1,openmp-triple2
9578 // -input=input_file
9579 // -output=unbundle_file_host
9580 // -output=unbundle_file_tgt1
9581 // -output=unbundle_file_tgt2
9582 // -unbundle
9583
9584 ArgStringList CmdArgs;
9585
9586 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9587 InputInfo Input = Inputs.front();
9588
9589 // Get the type.
9590 CmdArgs.push_back(TCArgs.MakeArgString(
9591 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9592
9593 // Get the targets.
9594 SmallString<128> Triples;
9595 Triples += "-targets=";
9596 auto DepInfo = UA.getDependentActionsInfo();
9597 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9598 if (I)
9599 Triples += ',';
9600
9601 auto &Dep = DepInfo[I];
9602 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9603 Triples += '-';
9604 Triples += llvm::Triple(Dep.DependentToolChain->ComputeEffectiveClangTriple(
9605 TCArgs, Dep.DependentBoundArch))
9606 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9607
9608 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9609 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9610 !Dep.DependentBoundArch.empty()) {
9611 Triples += '-';
9612 Triples += Dep.DependentBoundArch.ArchName;
9613 }
9614 }
9615
9616 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9617
9618 // Get bundled file command.
9619 CmdArgs.push_back(
9620 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9621
9622 // Get unbundled files command.
9623 for (unsigned I = 0; I < Outputs.size(); ++I) {
9625 UB += "-output=";
9626 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9627 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9628 }
9629 CmdArgs.push_back("-unbundle");
9630 CmdArgs.push_back("-allow-missing-bundles");
9631 if (TCArgs.hasArg(options::OPT_v))
9632 CmdArgs.push_back("-verbose");
9633
9634 // All the inputs are encoded as commands.
9635 C.addCommand(std::make_unique<Command>(
9636 JA, *this, ResponseFileSupport::None(),
9637 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9638 CmdArgs, ArrayRef<InputInfo>(), Outputs));
9639}
9640
9642 const InputInfo &Output,
9643 const InputInfoList &Inputs,
9644 const llvm::opt::ArgList &Args,
9645 const char *LinkingOutput) const {
9646 ArgStringList CmdArgs;
9647
9648 // Add the output file name.
9649 assert(Output.isFilename() && "Invalid output.");
9650 CmdArgs.push_back("-o");
9651 CmdArgs.push_back(Output.getFilename());
9652
9653 // Create the inputs to bundle the needed metadata.
9654 for (const InputInfo &Input : Inputs) {
9655 const Action *OffloadAction = Input.getAction();
9657 const ArgList &TCArgs =
9658 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9660 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9662 if (Arch.empty())
9663 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9664
9665 StringRef Kind =
9667
9668 ArgStringList Features;
9669 SmallVector<StringRef> FeatureArgs;
9670 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9671 false);
9672 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9673 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9674
9675 // TODO: We need to pass in the full target-id and handle it properly in the
9676 // linker wrapper.
9678 "file=" + File.str(),
9679 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9680 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9681 "kind=" + Kind.str(),
9682 };
9683
9685 for (StringRef Feature : FeatureArgs)
9686 Parts.emplace_back("feature=" + Feature.str());
9687
9688 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9689 }
9690
9691 C.addCommand(std::make_unique<Command>(
9693 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9694 CmdArgs, Inputs, Output));
9695}
9696
9697// Options that need the profile compiler-rt library on the target toolchain.
9698// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9699// too.
9700static bool requiresProfileRT(unsigned ID) {
9701 switch (ID) {
9702 case options::OPT_fprofile_generate:
9703 case options::OPT_fprofile_generate_EQ:
9704 case options::OPT_fprofile_instr_generate:
9705 case options::OPT_fprofile_instr_generate_EQ:
9706 case options::OPT_fcoverage_mapping:
9707 case options::OPT_fno_coverage_mapping:
9708 case options::OPT_fcoverage_compilation_dir_EQ:
9709 case options::OPT_ffile_compilation_dir_EQ:
9710 case options::OPT_fcoverage_prefix_map_EQ:
9711 return true;
9712 default:
9713 return false;
9714 }
9715}
9716
9717// Options that need the ubsan compiler-rt library on the target toolchain.
9718static bool requiresUBSanRT(unsigned ID) {
9719 switch (ID) {
9720 case options::OPT_fsanitize_EQ:
9721 case options::OPT_fno_sanitize_EQ:
9722 case options::OPT_fsanitize_minimal_runtime:
9723 case options::OPT_fno_sanitize_minimal_runtime:
9724 return true;
9725 default:
9726 return false;
9727 }
9728}
9729
9731 const InputInfo &Output,
9732 const InputInfoList &Inputs,
9733 const ArgList &Args,
9734 const char *LinkingOutput) const {
9735 using namespace options;
9736
9737 // A list of permitted options that will be forwarded to the embedded device
9738 // compilation job.
9739 const llvm::DenseSet<unsigned> CompilerOptions{
9740 OPT_v,
9741 OPT_hip_path_EQ,
9742 OPT_O_Group,
9743 OPT_g_Group,
9744 OPT_g_flags_Group,
9745 OPT_R_value_Group,
9746 OPT_R_Group,
9747 OPT_Xcuda_ptxas,
9748 OPT_ftime_report,
9749 OPT_ftime_trace,
9750 OPT_ftime_trace_EQ,
9751 OPT_ftime_trace_granularity_EQ,
9752 OPT_ftime_trace_verbose,
9753 OPT_opt_record_file,
9754 OPT_opt_record_format,
9755 OPT_opt_record_passes,
9756 OPT_fsave_optimization_record,
9757 OPT_fsave_optimization_record_EQ,
9758 OPT_fno_save_optimization_record,
9759 OPT_foptimization_record_file_EQ,
9760 OPT_foptimization_record_passes_EQ,
9761 OPT_save_temps,
9762 OPT_save_temps_EQ,
9763 OPT_mcode_object_version_EQ,
9764 OPT_load,
9765 OPT_no_canonical_prefixes,
9766 OPT_fno_lto,
9767 OPT_flto,
9768 OPT_flto_partitions_EQ,
9769 OPT_flto_EQ,
9770 OPT_hipspv_pass_plugin_EQ,
9771 OPT_use_spirv_backend,
9772 OPT_no_use_spirv_backend,
9773 OPT_fmultilib_flag,
9774 OPT_fprofile_generate,
9775 OPT_fprofile_generate_EQ,
9776 OPT_fprofile_instr_generate,
9777 OPT_fprofile_instr_generate_EQ,
9778 OPT_fcoverage_mapping,
9779 OPT_fno_coverage_mapping,
9780 OPT_fcoverage_compilation_dir_EQ,
9781 OPT_ffile_compilation_dir_EQ,
9782 OPT_fcoverage_prefix_map_EQ,
9783 OPT_fsanitize_EQ,
9784 OPT_fno_sanitize_EQ,
9785 OPT_fsanitize_minimal_runtime,
9786 OPT_fno_sanitize_minimal_runtime,
9787 OPT_fsanitize_trap_EQ,
9788 OPT_fno_sanitize_trap_EQ,
9789 OPT_fslp_vectorize,
9790 OPT_fno_slp_vectorize};
9791 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9792 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9793 return TC.getVFS().exists(
9794 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9795 };
9796 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9797 unsigned ID = A->getOption().getID();
9798 // Don't forward profiling arguments if the toolchain doesn't support it.
9799 // Without this check using it on the host would result in linker errors.
9800 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9801 // together to avoid a device cc1 diagnostic.
9802 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9803 return false;
9804 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9805 // Without this check using it on the host would result in linker errors.
9806 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9807 return false;
9808 // Don't forward -mllvm to toolchains that don't support LLVM.
9809 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9810 };
9811 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9812 const ToolChain &TC) {
9813 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9814 if (A->getOption().matches(OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9815 return false;
9816 return (Set.contains(A->getOption().getID()) ||
9817 (A->getOption().getGroup().isValid() &&
9818 Set.contains(A->getOption().getGroup().getID()))) &&
9819 ShouldForwardForToolChain(A, TC);
9820 };
9821
9822 ArgStringList CmdArgs;
9825 auto TCRange = C.getOffloadToolChains(Kind);
9826 for (auto &I : llvm::make_range(TCRange)) {
9827 const ToolChain *TC = I.second;
9828
9829 // We do not use a bound architecture here so options passed only to a
9830 // specific architecture via -Xarch_<cpu> will not be forwarded.
9831 ArgStringList CompilerArgs;
9832 ArgStringList LinkerArgs;
9833 const DerivedArgList &ToolChainArgs =
9834 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9835 for (Arg *A : ToolChainArgs) {
9836 if (A->getOption().matches(OPT_Zlinker_input))
9837 LinkerArgs.emplace_back(A->getValue());
9838 else if (ShouldForward(CompilerOptions, A, *TC)) {
9839 A->claim();
9840 A->render(Args, CompilerArgs);
9841 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9842 A->claim();
9843 A->render(Args, LinkerArgs);
9844 }
9845 }
9846
9847 // If the user explicitly requested it via `--offload-arch` we should
9848 // extract it from any static libraries if present.
9849 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9850 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9851
9852 // If this is OpenMP the device linker will need `-lompdevice`.
9853 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9854 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9855 LinkerArgs.emplace_back("-lompdevice");
9856
9857 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9858 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9859 // flags to normal compilation.
9860 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9861 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9862 if (TC->getTriple().isSPIRV() &&
9863 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9864 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9865 // For SPIR-V some functions will be defined by the runtime so allow
9866 // unresolved symbols in `spirv-link`.
9867 LinkerArgs.emplace_back("--allow-partial-linkage");
9868 // Don't optimize out exported symbols.
9869 LinkerArgs.emplace_back("--create-library");
9870 }
9871
9872 // Forward all of these to the appropriate toolchain.
9873 for (StringRef Arg : CompilerArgs)
9874 CmdArgs.push_back(Args.MakeArgString(
9875 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9876 for (StringRef Arg : LinkerArgs)
9877 CmdArgs.push_back(Args.MakeArgString(
9878 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9879
9880 // Forward the LTO mode for this toolchain.
9881 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9882 if (DeviceLTOMode == LTOK_Full)
9883 CmdArgs.push_back(Args.MakeArgString(
9884 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9885 else if (DeviceLTOMode == LTOK_Thin) {
9886 CmdArgs.push_back(Args.MakeArgString(
9887 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9888 if (TC->getTriple().isAMDGPU()) {
9889 CmdArgs.push_back(
9890 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9891 "=-plugin-opt=-force-import-all"));
9892 CmdArgs.push_back(
9893 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9894 "=-plugin-opt=-avail-extern-to-local"));
9895 CmdArgs.push_back(Args.MakeArgString(
9896 "--device-linker=" + TC->getTripleString() +
9897 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9898 if (Kind == Action::OFK_OpenMP) {
9899 CmdArgs.push_back(
9900 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9901 "=-plugin-opt=-amdgpu-internalize-symbols"));
9902 }
9903 }
9904 }
9905
9906 if (JA.getType() == types::TY_HIP_FATBIN && Kind == Action::OFK_HIP) {
9907 // Non-RDC HIP uses the conventional non-LTO pipeline unless the user
9908 // opts into offload LTO.
9909 bool UsesProfileGenerate = Args.hasArg(
9910 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
9911 options::OPT_fprofile_instr_generate,
9912 options::OPT_fprofile_instr_generate_EQ);
9913 if (!Args.hasArg(options::OPT_foffload_lto_EQ,
9914 options::OPT_fno_offload_lto) &&
9915 !UsesProfileGenerate && !TC->getTriple().isSPIRV())
9916 CmdArgs.push_back("--no-lto");
9917 }
9918 }
9919 }
9920
9921 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9922 CmdArgs.push_back(
9923 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
9924 else
9925 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
9926 getToolChain().getTripleString()));
9927
9928 // CMake hack, suppress passing verbose arguments for the special-case HIP
9929 // non-RDC mode compilation. This confuses default CMake implicit linker
9930 // argument parsing when the language is set to HIP and the system linker is
9931 // also `ld.lld`.
9932 if (Args.hasArg(options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9933 CmdArgs.push_back("--wrapper-verbose");
9934 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
9935 CmdArgs.push_back(
9936 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
9937 CmdArgs.push_back(Args.MakeArgString(
9938 Twine("--device-compiler=--cuda-path=") + A->getValue()));
9939 }
9940 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
9941 CmdArgs.push_back(Args.MakeArgString(
9942 Twine("--device-compiler=--rocm-path=") + A->getValue()));
9943 }
9944
9945 // Construct the link job so we can wrap around it.
9946 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9947 const auto &LinkCommand = C.getJobs().getJobs().back();
9948
9949 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9950 // wrapper.
9951 for (Arg *A :
9952 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
9953 StringRef Val = A->getValue(0);
9954 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9955 auto WrapperOption =
9956 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9957 if (Val.empty())
9958 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
9959 else
9960 CmdArgs.push_back(Args.MakeArgString(
9961 WrapperOption +
9962 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
9963 A->getValue(1)));
9964 }
9965 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
9966 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9967
9968 // Embed bitcode instead of an object in JIT mode.
9969 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9970 options::OPT_fno_openmp_target_jit, false))
9971 CmdArgs.push_back("--embed-bitcode");
9972
9973 // Save temporary files created by the linker wrapper.
9974 if (Args.hasArg(options::OPT_save_temps_EQ) ||
9975 Args.hasArg(options::OPT_save_temps))
9976 CmdArgs.push_back("--save-temps");
9977
9978 // Pass in the C library for GPUs if present and not disabled.
9979 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
9980 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
9981 options::OPT_nodefaultlibs, options::OPT_nolibc,
9982 options::OPT_nogpulibc)) {
9983 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
9984 // The device C library is only available for NVPTX and AMDGPU targets
9985 // and we only link it by default for OpenMP currently.
9986 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9988 return;
9989 bool HasLibC = TC.getStdlibIncludePath().has_value();
9990 if (HasLibC) {
9991 CmdArgs.push_back(Args.MakeArgString(
9992 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9993 CmdArgs.push_back(Args.MakeArgString(
9994 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9995 }
9996 auto HasCompilerRT = getToolChain().getVFS().exists(
9997 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
9998 /*IsFortran=*/false));
9999 if (HasCompilerRT)
10000 CmdArgs.push_back(
10001 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10002 "-lclang_rt.builtins"));
10003
10004 bool HasFlangRT = getToolChain().getVFS().exists(
10005 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10006 /*IsFortran=*/true));
10007 if (HasFlangRT && C.getDriver().IsFlangMode())
10008 CmdArgs.push_back(
10009 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10010 "-lflang_rt.runtime"));
10011 });
10012 }
10013
10014 // Add the linker arguments to be forwarded by the wrapper.
10015 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10016 LinkCommand->getExecutable()));
10017
10018 // We use action type to differentiate two use cases of the linker wrapper.
10019 // TY_Image for normal linker wrapper work.
10020 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
10021 assert(JA.getType() == types::TY_HIP_FATBIN ||
10022 JA.getType() == types::TY_Image);
10023 if (JA.getType() == types::TY_HIP_FATBIN) {
10024 CmdArgs.push_back("--emit-fatbin-only");
10025 CmdArgs.append({"-o", Output.getFilename()});
10026 for (auto Input : Inputs)
10027 CmdArgs.push_back(Input.getFilename());
10028 } else {
10029 for (const char *LinkArg : LinkCommand->getArguments())
10030 CmdArgs.push_back(LinkArg);
10031 }
10032
10033 addOffloadCompressArgs(Args, CmdArgs);
10034
10035 if (Arg *A = Args.getLastArg(options::OPT_offload_jobs_EQ)) {
10036 StringRef Val = A->getValue();
10037
10038 if (Val.equals_insensitive("jobserver"))
10039 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10040 else {
10041 int NumThreads;
10042 if (Val.getAsInteger(10, NumThreads) || NumThreads <= 0) {
10043 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10044 << A->getAsString(Args) << Val;
10045 } else {
10046 CmdArgs.push_back(
10047 Args.MakeArgString("--wrapper-jobs=" + Twine(NumThreads)));
10048 }
10049 }
10050 }
10051
10052 // Propagate -no-canonical-prefixes.
10053 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10054 CmdArgs.push_back("--no-canonical-prefixes");
10055
10056 const char *Exec =
10057 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10058
10059 // Replace the executable and arguments of the link job with the
10060 // wrapper.
10061 LinkCommand->replaceExecutable(Exec);
10062 LinkCommand->replaceArguments(CmdArgs);
10063}
#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:734
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3891
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:118
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2280
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:4625
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4296
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:708
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5028
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9700
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4477
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:789
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:71
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1359
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1211
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:8748
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2259
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:806
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3976
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4608
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2530
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1249
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:766
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:338
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4585
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:4332
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:323
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2535
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1260
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2311
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2541
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2252
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4042
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:98
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3571
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:308
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, bool IsDeviceOffloadAction, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition Clang.cpp:138
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1276
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:253
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1395
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3581
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3984
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3803
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3820
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8727
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:233
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:86
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:216
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9718
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:287
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3502
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2286
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2906
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:369
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3935
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:263
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
types::ID getType() const
Definition Action.h:154
const ToolChain * getOffloadingToolChain() const
Definition Action.h:218
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
BoundArch getOffloadingArch() const
Definition Action.h:217
ActionClass getKind() const
Definition Action.h:153
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:164
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:216
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:224
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:227
ActionList & getInputs()
Definition Action.h:156
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:212
bool isOffloading(OffloadKind OKind) const
Definition Action.h:230
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
Distro - Helper class for detecting and classifying Linux distributions.
Definition Distro.h:23
bool IsGentoo() const
Definition Distro.h:134
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
llvm::SmallVector< BoundArch > getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, Action::OffloadKind Kind, const ToolChain &TC) const
Returns the set of bound architectures active for this offload kind.
Definition Driver.cpp:4897
std::string SysRoot
sysroot, if present
Definition Driver.h:195
DiagnosticsEngine & getDiags() const
Definition Driver.h:409
const char * getPrependArg() const
Definition Driver.h:420
CC1ToolFunc CC1Main
Definition Driver.h:291
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:852
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:231
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:269
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4008
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:273
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:159
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:283
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:6947
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2438
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:431
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:219
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:216
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:179
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:411
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:155
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:145
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:252
std::string getTargetTriple() const
Definition Driver.h:428
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:258
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:173
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:225
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:222
bool getProbePrecompiled() const
Definition Driver.h:417
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:274
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:96
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:905
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:658
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual unsigned getMaxDwarfVersion() const
Definition ToolChain.h:667
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:691
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:897
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:649
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:521
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:302
const Driver & getDriver() const
Definition ToolChain.h:286
RTTIMode getRTTIMode() const
Definition ToolChain.h:369
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:680
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:314
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:542
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:513
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:702
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:673
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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:677
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:311
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:536
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:742
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:655
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:643
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:892
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:525
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:488
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:646
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
virtual bool IsEncodeExtendedBlockSignatureDefault() const
IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable -fencode-extended-block-signature...
Definition ToolChain.h:517
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:484
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:295
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:510
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< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:946
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:627
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9149
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9132
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9157
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:9172
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9121
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9091
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8583
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9106
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9096
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:5128
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:9730
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:9568
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:9478
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:9641
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:275
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:401
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)
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
llvm::SmallString< 256 > getCXX20NamedModuleOutputPath(const llvm::opt::ArgList &Args, const char *BaseInput)
void setComplexRange(const Driver &D, StringRef NewOpt, LangOptions::ComplexRangeKind NewRange, StringRef &LastOpt, LangOptions::ComplexRangeKind &Range)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
std::string renderComplexRangeOption(LangOptions::ComplexRangeKind Range)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
void handleVectorizeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fvectorize based on the optimization level selected.
void escapeSpacesAndBackslashes(const char *Arg, llvm::SmallVectorImpl< char > &Res)
Add backslashes to escape spaces and other backslashes.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition Types.cpp:326
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
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:289
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:250
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:328
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:262
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:51
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.
@ Default
Set to the current date and time.
@ 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
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
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
bool empty() const
LangStandard - Information about the properties of a particular language standard.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
static const LangStandard * getLangStandardForName(StringRef Name)
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
clang::Language getLanguage() const
Get the language that this standard describes.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:79
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:86