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

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