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