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