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

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