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