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