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