Thanks to visit codestin.com
Credit goes to clang.llvm.org

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