clang 24.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/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
28#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
30#include "clang/Driver/Action.h"
32#include "clang/Driver/Distro.h"
35#include "clang/Driver/Types.h"
39#include "llvm/ADT/ScopeExit.h"
40#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/BinaryFormat/Magic.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/Frontend/Debug/Options.h"
45#include "llvm/Object/ObjectFile.h"
46#include "llvm/Option/ArgList.h"
47#include "llvm/ProfileData/InstrProfReader.h"
48#include "llvm/Support/CodeGen.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64#include <iterator>
65
66using namespace clang::driver;
67using namespace clang::driver::tools;
68using namespace clang;
69using namespace llvm::opt;
70
71static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
72 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,
73 options::OPT_fminimize_whitespace,
74 options::OPT_fno_minimize_whitespace,
75 options::OPT_fkeep_system_includes,
76 options::OPT_fno_keep_system_includes)) {
77 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
78 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
79 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
80 << A->getBaseArg().getAsString(Args)
81 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
82 }
83 }
84}
85
86static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
87 // In gcc, only ARM checks this, but it seems reasonable to check universally.
88 if (Args.hasArg(options::OPT_static))
89 if (const Arg *A =
90 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
91 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
92 << "-static";
93}
94
95/// Apply \a Work on the current tool chain \a RegularToolChain and any other
96/// offloading tool chain that is associated with the current action \a JA.
97static void
99 const ToolChain &RegularToolChain,
100 llvm::function_ref<void(const ToolChain &)> Work) {
101 // Apply Work on the current/regular tool chain.
102 Work(RegularToolChain);
103
104 // Apply Work on all the offloading tool chains associated with the current
105 // action.
108 if (JA.isHostOffloading(Kind)) {
109 auto TCs = C.getOffloadToolChains(Kind);
110 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
111 Work(*II->second);
112 } else if (JA.isDeviceOffloading(Kind))
113 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
114 }
115}
116
117static bool
119 const llvm::Triple &Triple) {
120 // We use the zero-cost exception tables for Objective-C if the non-fragile
121 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
122 // later.
123 if (runtime.isNonFragile())
124 return true;
125
126 if (!Triple.isMacOSX())
127 return false;
128
129 return (!Triple.isMacOSXVersionLT(10, 5) &&
130 (Triple.getArch() == llvm::Triple::x86_64 ||
131 Triple.getArch() == llvm::Triple::arm));
132}
133
134/// Adds exception related arguments to the driver command arguments. There's a
135/// main flag, -fexceptions and also language specific flags to enable/disable
136/// C++ and Objective-C exceptions. This makes it possible to for example
137/// disable C++ exceptions but enable Objective-C exceptions.
138static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
139 const ToolChain &TC, bool KernelOrKext,
140 bool IsDeviceOffloadAction,
141 const ObjCRuntime &objcRuntime,
142 ArgStringList &CmdArgs) {
143 const llvm::Triple &Triple = TC.getTriple();
144
145 if (KernelOrKext) {
146 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
147 // arguments now to avoid warnings about unused arguments.
148 Args.ClaimAllArgs(options::OPT_fexceptions);
149 Args.ClaimAllArgs(options::OPT_fno_exceptions);
150 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
151 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
152 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
153 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
154 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
155 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
156 return false;
157 }
158
159 // See if the user explicitly enabled exceptions.
160 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
161 false);
162
163 // Async exceptions are Windows MSVC only.
164 if (Triple.isWindowsMSVCEnvironment()) {
165 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
166 options::OPT_fno_async_exceptions, false);
167 if (EHa) {
168 CmdArgs.push_back("-fasync-exceptions");
169 EH = true;
170 }
171 }
172
173 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
174 // is not necessarily sensible, but follows GCC.
175 if (types::isObjC(InputType) &&
176 Args.hasFlag(options::OPT_fobjc_exceptions,
177 options::OPT_fno_objc_exceptions, true)) {
178 CmdArgs.push_back("-fobjc-exceptions");
179
180 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
181 }
182
183 if (types::isCXX(InputType)) {
184 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
185 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
186 !Triple.isPS() && !Triple.isDriverKit() &&
187 !(Triple.isGPU() && !IsDeviceOffloadAction);
188 Arg *ExceptionArg = Args.getLastArg(
189 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
190 options::OPT_fexceptions, options::OPT_fno_exceptions);
191 if (ExceptionArg)
192 CXXExceptionsEnabled =
193 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
194 ExceptionArg->getOption().matches(options::OPT_fexceptions);
195
196 if (CXXExceptionsEnabled) {
197 CmdArgs.push_back("-fcxx-exceptions");
198
199 EH = true;
200 }
201 }
202
203 // OPT_fignore_exceptions means exception could still be thrown,
204 // but no clean up or catch would happen in current module.
205 // So we do not set EH to false.
206 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
207
208 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
209 options::OPT_fno_assume_nothrow_exception_dtor);
210
211 if (EH)
212 CmdArgs.push_back("-fexceptions");
213 return EH;
214}
215
216static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
217 const JobAction &JA) {
218 bool Default = true;
219 if (TC.getTriple().isOSDarwin()) {
220 // The native darwin assembler doesn't support the linker_option directives,
221 // so we disable them if we think the .s file will be passed to it.
223 }
224 // The linker_option directives are intended for host compilation.
227 Default = false;
228 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
229 Default);
230}
231
232/// Add a CC1 option to specify the debug compilation directory.
233static const char *addDebugCompDirArg(const ArgList &Args,
234 ArgStringList &CmdArgs,
235 const llvm::vfs::FileSystem &VFS) {
236 std::string DebugCompDir;
237 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
238 options::OPT_fdebug_compilation_dir_EQ))
239 DebugCompDir = A->getValue();
240
241 if (DebugCompDir.empty()) {
242 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
243 DebugCompDir = std::move(*CWD);
244 else
245 return nullptr;
246 }
247 CmdArgs.push_back(
248 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
249 StringRef Path(CmdArgs.back());
250 return Path.substr(Path.find('=') + 1).data();
251}
252
253static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
254 const char *DebugCompilationDir,
255 const char *OutputFileName) {
256 // No need to generate a value for -object-file-name if it was provided.
257 for (auto *Arg : Args.filtered(options::OPT_Xclang))
258 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
259 return;
260
261 if (Args.hasArg(options::OPT_object_file_name_EQ))
262 return;
263
264 SmallString<128> ObjFileNameForDebug(OutputFileName);
265 if (ObjFileNameForDebug != "-" &&
266 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
267 (!DebugCompilationDir ||
268 llvm::sys::path::is_absolute(DebugCompilationDir))) {
269 // Make the path absolute in the debug infos like MSVC does.
270 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
271 }
272 // If the object file name is a relative path, then always use Windows
273 // backslash style as -object-file-name is used for embedding object file path
274 // in codeview and it can only be generated when targeting on Windows.
275 // Otherwise, just use native absolute path.
276 llvm::sys::path::Style Style =
277 llvm::sys::path::is_absolute(ObjFileNameForDebug)
278 ? llvm::sys::path::Style::native
279 : llvm::sys::path::Style::windows_backslash;
280 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
281 Style);
282 CmdArgs.push_back(
283 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
284}
285
286/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
287static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
288 const ArgList &Args, ArgStringList &CmdArgs) {
289 auto AddOneArg = [&](StringRef Map, StringRef Name) {
290 if (!Map.contains('='))
291 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
292 else
293 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
294 };
295
296 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
297 options::OPT_fdebug_prefix_map_EQ)) {
298 AddOneArg(A->getValue(), A->getOption().getName());
299 A->claim();
300 }
301 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
302 if (GlobalRemapEntry.empty())
303 return;
304 AddOneArg(GlobalRemapEntry, "environment");
305}
306
307/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
308static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
309 ArgStringList &CmdArgs) {
310 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
311 options::OPT_fmacro_prefix_map_EQ)) {
312 StringRef Map = A->getValue();
313 if (!Map.contains('='))
314 D.Diag(diag::err_drv_invalid_argument_to_option)
315 << Map << A->getOption().getName();
316 else
317 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
318 A->claim();
319 }
320}
321
322/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
323static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
324 ArgStringList &CmdArgs) {
325 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
326 options::OPT_fcoverage_prefix_map_EQ)) {
327 StringRef Map = A->getValue();
328 if (!Map.contains('='))
329 D.Diag(diag::err_drv_invalid_argument_to_option)
330 << Map << A->getOption().getName();
331 else
332 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
333 A->claim();
334 }
335}
336
337/// Add -x lang to \p CmdArgs for \p Input.
338static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
339 ArgStringList &CmdArgs) {
340 // When using -verify-pch, we don't want to provide the type
341 // 'precompiled-header' if it was inferred from the file extension
342 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
343 return;
344
345 CmdArgs.push_back("-x");
346 if (Args.hasArg(options::OPT_rewrite_objc))
347 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
348 else {
349 // Map the driver type to the frontend type. This is mostly an identity
350 // mapping, except that the distinction between module interface units
351 // and other source files does not exist at the frontend layer.
352 const char *ClangType;
353 switch (Input.getType()) {
354 case types::TY_CXXModule:
355 case types::TY_CXXStdModule:
356 ClangType = "c++";
357 break;
358 case types::TY_PP_CXXModule:
359 ClangType = "c++-cpp-output";
360 break;
361 case types::TY_CIRBC:
362 ClangType = "cir";
363 break;
364 default:
365 ClangType = types::getTypeName(Input.getType());
366 break;
367 }
368 CmdArgs.push_back(ClangType);
369 }
370}
371
373 const JobAction &JA, const InputInfo &Output,
374 const ArgList &Args, SanitizerArgs &SanArgs,
375 ArgStringList &CmdArgs) {
376 const Driver &D = TC.getDriver();
377 const llvm::Triple &T = TC.getTriple();
378 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
379 options::OPT_fprofile_generate_EQ,
380 options::OPT_fno_profile_generate);
381 if (PGOGenerateArg &&
382 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
383 PGOGenerateArg = nullptr;
384
385 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
386
387 auto *ProfileGenerateArg = Args.getLastArg(
388 options::OPT_fprofile_instr_generate,
389 options::OPT_fprofile_instr_generate_EQ,
390 options::OPT_fno_profile_instr_generate);
391 if (ProfileGenerateArg &&
392 ProfileGenerateArg->getOption().matches(
393 options::OPT_fno_profile_instr_generate))
394 ProfileGenerateArg = nullptr;
395
396 if (PGOGenerateArg && ProfileGenerateArg)
397 D.Diag(diag::err_drv_argument_not_allowed_with)
398 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
399
400 auto *ProfileUseArg = getLastProfileUseArg(Args);
401
402 if (PGOGenerateArg && ProfileUseArg)
403 D.Diag(diag::err_drv_argument_not_allowed_with)
404 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
405
406 if (ProfileGenerateArg && ProfileUseArg)
407 D.Diag(diag::err_drv_argument_not_allowed_with)
408 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
409
410 if (CSPGOGenerateArg && PGOGenerateArg) {
411 D.Diag(diag::err_drv_argument_not_allowed_with)
412 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
413 PGOGenerateArg = nullptr;
414 }
415
416 if (TC.getTriple().isOSAIX()) {
417 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
418 D.Diag(diag::err_drv_unsupported_opt_for_target)
419 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
420 }
421
422 if (ProfileGenerateArg) {
423 if (ProfileGenerateArg->getOption().matches(
424 options::OPT_fprofile_instr_generate_EQ))
425 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
426 ProfileGenerateArg->getValue()));
427 // The default is to use Clang Instrumentation.
428 CmdArgs.push_back("-fprofile-instrument=clang");
429 if (TC.getTriple().isWindowsMSVCEnvironment() &&
430 Args.hasFlag(options::OPT_frtlib_defaultlib,
431 options::OPT_fno_rtlib_defaultlib, true)) {
432 // Add dependent lib for clang_rt.profile
433 CmdArgs.push_back(Args.MakeArgString(
434 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
435 }
436 }
437
438 if (auto *ColdFuncCoverageArg = Args.getLastArg(
439 options::OPT_fprofile_generate_cold_function_coverage,
440 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
441 SmallString<128> Path(
442 ColdFuncCoverageArg->getOption().matches(
443 options::OPT_fprofile_generate_cold_function_coverage_EQ)
444 ? ColdFuncCoverageArg->getValue()
445 : "");
446 llvm::sys::path::append(Path, "default_%m.profraw");
447 // FIXME: Idealy the file path should be passed through
448 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
449 // shared with other profile use path(see PGOOptions), we need to refactor
450 // PGOOptions to make it work.
451 CmdArgs.push_back("-mllvm");
452 CmdArgs.push_back(Args.MakeArgString(
453 Twine("--instrument-cold-function-only-path=") + Path));
454 CmdArgs.push_back("-mllvm");
455 CmdArgs.push_back("--pgo-instrument-cold-function-only");
456 CmdArgs.push_back("-mllvm");
457 CmdArgs.push_back("--pgo-function-entry-coverage");
458 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
459 }
460
461 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
462 if (!PGOGenerateArg && !CSPGOGenerateArg)
463 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
464 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
465 CmdArgs.push_back("-mllvm");
466 CmdArgs.push_back("--pgo-temporal-instrumentation");
467 }
468
469 Arg *PGOGenArg = nullptr;
470 if (PGOGenerateArg) {
471 assert(!CSPGOGenerateArg);
472 PGOGenArg = PGOGenerateArg;
473 CmdArgs.push_back("-fprofile-instrument=llvm");
474 }
475 if (CSPGOGenerateArg) {
476 assert(!PGOGenerateArg);
477 PGOGenArg = CSPGOGenerateArg;
478 CmdArgs.push_back("-fprofile-instrument=csllvm");
479 }
480 if (PGOGenArg) {
481 if (TC.getTriple().isWindowsMSVCEnvironment() &&
482 Args.hasFlag(options::OPT_frtlib_defaultlib,
483 options::OPT_fno_rtlib_defaultlib, true)) {
484 // Add dependent lib for clang_rt.profile
485 CmdArgs.push_back(Args.MakeArgString(
486 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
487 }
488 if (PGOGenArg->getOption().matches(
489 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
490 : options::OPT_fcs_profile_generate_EQ)) {
491 SmallString<128> Path(PGOGenArg->getValue());
492 llvm::sys::path::append(Path, "default_%m.profraw");
493 CmdArgs.push_back(
494 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
495 }
496 }
497
498 if (ProfileUseArg) {
499 SmallString<128> UsePathBuf;
500 StringRef UsePath;
501 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
502 UsePath = ProfileUseArg->getValue();
503 else if ((ProfileUseArg->getOption().matches(
504 options::OPT_fprofile_use_EQ) ||
505 ProfileUseArg->getOption().matches(
506 options::OPT_fprofile_instr_use))) {
507 UsePathBuf =
508 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
509 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
510 llvm::sys::path::append(UsePathBuf, "default.profdata");
511 UsePath = UsePathBuf;
512 }
513 auto ReaderOrErr =
514 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
515 if (auto E = ReaderOrErr.takeError()) {
516 auto DiagID = D.getDiags().getCustomDiagID(
517 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
518 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
519 D.Diag(DiagID) << UsePath.str() << EI.message();
520 });
521 } else {
522 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
523 std::move(ReaderOrErr.get());
524 StringRef UseKind;
525 // Currently memprof profiles are only added at the IR level. Mark the
526 // profile type as IR in that case as well and the subsequent matching
527 // needs to detect which is available (might be one or both).
528 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
529 if (PGOReader->hasCSIRLevelProfile())
530 UseKind = "csllvm";
531 else
532 UseKind = "llvm";
533 } else
534 UseKind = "clang";
535
536 CmdArgs.push_back(
537 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
538 CmdArgs.push_back(
539 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
540 }
541 }
542
543 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
544 options::OPT_fno_test_coverage, false) ||
545 Args.hasArg(options::OPT_coverage);
546 bool EmitCovData = TC.needsGCovInstrumentation(Args);
547
548 if (Args.hasFlag(options::OPT_fcoverage_mapping,
549 options::OPT_fno_coverage_mapping, false)) {
550 if (!ProfileGenerateArg)
551 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
552 << "-fcoverage-mapping"
553 << "-fprofile-instr-generate";
554
555 CmdArgs.push_back("-fcoverage-mapping");
556 }
557
558 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
559 false)) {
560 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
561 options::OPT_fno_coverage_mapping, false))
562 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
563 << "-fcoverage-mcdc"
564 << "-fcoverage-mapping";
565
566 CmdArgs.push_back("-fcoverage-mcdc");
567 }
568
569 StringRef CoverageCompDir;
570 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
571 options::OPT_fcoverage_compilation_dir_EQ))
572 CoverageCompDir = A->getValue();
573 if (CoverageCompDir.empty()) {
574 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
575 CmdArgs.push_back(
576 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
577 } else
578 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
579 CoverageCompDir));
580
581 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
582 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
583 if (!Args.hasArg(options::OPT_coverage))
584 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
585 << "-fprofile-exclude-files="
586 << "--coverage";
587
588 StringRef v = Arg->getValue();
589 CmdArgs.push_back(
590 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
591 }
592
593 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
594 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
595 if (!Args.hasArg(options::OPT_coverage))
596 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
597 << "-fprofile-filter-files="
598 << "--coverage";
599
600 StringRef v = Arg->getValue();
601 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
602 }
603
604 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
605 StringRef Val = A->getValue();
606 if (Val == "atomic" || Val == "prefer-atomic")
607 CmdArgs.push_back("-fprofile-update=atomic");
608 else if (Val != "single")
609 D.Diag(diag::err_drv_unsupported_option_argument)
610 << A->getSpelling() << Val;
611 }
612 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
613 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
614 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
615 << A->getSpelling()
616 << "-fprofile-generate, -fprofile-instr-generate, or "
617 "-fcs-profile-generate";
618 else {
619 CmdArgs.push_back("-fprofile-continuous");
620 // Platforms that require a bias variable:
621 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
622 CmdArgs.push_back("-mllvm");
623 CmdArgs.push_back("-runtime-counter-relocation");
624 }
625 // -fprofile-instr-generate does not decide the profile file name in the
626 // FE, and so it does not define the filename symbol
627 // (__llvm_profile_filename). Instead, the runtime uses the name
628 // "default.profraw" for the profile file. When continuous mode is ON, we
629 // will create the filename symbol so that we can insert the "%c"
630 // modifier.
631 if (ProfileGenerateArg &&
632 (ProfileGenerateArg->getOption().matches(
633 options::OPT_fprofile_instr_generate) ||
634 (ProfileGenerateArg->getOption().matches(
635 options::OPT_fprofile_instr_generate_EQ) &&
636 strlen(ProfileGenerateArg->getValue()) == 0)))
637 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
638 }
639 }
640
641 int FunctionGroups = 1;
642 int SelectedFunctionGroup = 0;
643 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
644 StringRef Val = A->getValue();
645 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
646 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
647 }
648 if (const auto *A =
649 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
650 StringRef Val = A->getValue();
651 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
652 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
653 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
654 }
655 if (FunctionGroups != 1)
656 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
657 Twine(FunctionGroups)));
658 if (SelectedFunctionGroup != 0)
659 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
660 Twine(SelectedFunctionGroup)));
661
662 // Leave -fprofile-dir= an unused argument unless .gcda emission is
663 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
664 // the flag used. There is no -fno-profile-dir, so the user has no
665 // targeted way to suppress the warning.
666 Arg *FProfileDir = nullptr;
667 if (Args.hasArg(options::OPT_fprofile_arcs) ||
668 Args.hasArg(options::OPT_coverage))
669 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
670
671 // Put the .gcno and .gcda files (if needed) next to the primary output file,
672 // or fall back to a file in the current directory for `clang -c --coverage
673 // d/a.c` in the absence of -o.
674 if (EmitCovNotes || EmitCovData) {
675 SmallString<128> CoverageFilename;
676 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
677 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
678 // path separator.
679 CoverageFilename = DumpDir->getValue();
680 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
681 } else if (Arg *FinalOutput =
682 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
683 CoverageFilename = FinalOutput->getValue();
684 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
685 CoverageFilename = FinalOutput->getValue();
686 } else {
687 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
688 }
689 if (llvm::sys::path::is_relative(CoverageFilename))
690 (void)D.getVFS().makeAbsolute(CoverageFilename);
691 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
692 if (EmitCovNotes) {
693 CmdArgs.push_back(
694 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
695
696 bool UseAbsolutePathsInNotes =
697 Args.hasFlag(options::OPT_fprofile_abs_path,
698 options::OPT_fno_profile_abs_path, false);
699 if (UseAbsolutePathsInNotes)
700 CmdArgs.push_back(Args.MakeArgString("-coverage-notes-abs-paths"));
701 }
702
703 if (EmitCovData) {
704 if (FProfileDir) {
705 SmallString<128> Gcno = std::move(CoverageFilename);
706 CoverageFilename = FProfileDir->getValue();
707 llvm::sys::path::append(CoverageFilename, Gcno);
708 }
709 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
710 CmdArgs.push_back(
711 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
712 }
713 }
714}
715
716static void
717RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
718 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
719 unsigned DwarfVersion,
720 llvm::DebuggerKind DebuggerTuning) {
721 addDebugInfoKind(CmdArgs, DebugInfoKind);
722 if (DwarfVersion > 0)
723 CmdArgs.push_back(
724 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
725 switch (DebuggerTuning) {
726 case llvm::DebuggerKind::GDB:
727 CmdArgs.push_back("-debugger-tuning=gdb");
728 break;
729 case llvm::DebuggerKind::LLDB:
730 CmdArgs.push_back("-debugger-tuning=lldb");
731 break;
732 case llvm::DebuggerKind::SCE:
733 CmdArgs.push_back("-debugger-tuning=sce");
734 break;
735 case llvm::DebuggerKind::DBX:
736 CmdArgs.push_back("-debugger-tuning=dbx");
737 break;
738 default:
739 break;
740 }
741}
742
744 const ArgList &Args,
745 ArgStringList &CmdArgs,
746 bool IsCC1As = false) {
747 // If no version was requested by the user, use the default value from the
748 // back end. This is consistent with the value returned from
749 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
750 // requiring the corresponding llvm to have the AMDGPU target enabled,
751 // provided the user (e.g. front end tests) can use the default.
753 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
754 CmdArgs.insert(CmdArgs.begin() + 1,
755 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
756 Twine(CodeObjVer)));
757 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
758 // -cc1as does not accept -mcode-object-version option.
759 if (!IsCC1As)
760 CmdArgs.insert(CmdArgs.begin() + 1,
761 Args.MakeArgString(Twine("-mcode-object-version=") +
762 Twine(CodeObjVer)));
763 }
764}
765
766static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
767 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
768 D.getVFS().getBufferForFile(Path);
769 if (!MemBuf)
770 return false;
771 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
772 if (Magic == llvm::file_magic::unknown)
773 return false;
774 // Return true for both raw Clang AST files and object files which may
775 // contain a __clangast section.
776 if (Magic == llvm::file_magic::clang_ast)
777 return true;
779 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
780 return !Obj.takeError();
781}
782
783static bool gchProbe(const Driver &D, StringRef Path) {
784 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
785 if (!Status)
786 return false;
787
788 if (Status->isDirectory()) {
789 std::error_code EC;
790 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
791 !EC && DI != DE; DI = DI.increment(EC)) {
792 if (maybeHasClangPchSignature(D, DI->path()))
793 return true;
794 }
795 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
796 return false;
797 }
798
799 if (maybeHasClangPchSignature(D, Path))
800 return true;
801 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
802 return false;
803}
804
805void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
806 const Driver &D, const ArgList &Args,
807 ArgStringList &CmdArgs,
808 const InputInfo &Output,
809 const InputInfoList &Inputs) const {
810 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
811
813
814 Args.AddLastArg(CmdArgs, options::OPT_C);
815 Args.AddLastArg(CmdArgs, options::OPT_CC);
816
817 // Handle dependency file generation.
818 Arg *ArgM = Args.getLastArg(options::OPT_MM);
819 if (!ArgM)
820 ArgM = Args.getLastArg(options::OPT_M);
821 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
822 if (!ArgMD)
823 ArgMD = Args.getLastArg(options::OPT_MD);
824
825 // -M and -MM imply -w.
826 if (ArgM)
827 CmdArgs.push_back("-w");
828 else
829 ArgM = ArgMD;
830
831 if (ArgM) {
833 // Determine the output location.
834 const char *DepFile;
835 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
836 DepFile = MF->getValue();
837 C.addFailureResultFile(DepFile, &JA);
838 } else if (Output.getType() == types::TY_Dependencies) {
839 DepFile = Output.getFilename();
840 } else if (!ArgMD) {
841 DepFile = "-";
842 } else {
843 DepFile = getDependencyFileName(Args, Inputs);
844 C.addFailureResultFile(DepFile, &JA);
845 }
846 CmdArgs.push_back("-dependency-file");
847 CmdArgs.push_back(DepFile);
848 }
849 // Cmake generates dependency files using all compilation options specified
850 // by users. Claim those not used for dependency files.
852 Args.ClaimAllArgs(options::OPT_offload_compress);
853 Args.ClaimAllArgs(options::OPT_no_offload_compress);
854 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
855 }
856
857 bool HasTarget = false;
858 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
859 HasTarget = true;
860 A->claim();
861 if (A->getOption().matches(options::OPT_MT)) {
862 A->render(Args, CmdArgs);
863 } else {
864 CmdArgs.push_back("-MT");
865 SmallString<128> Quoted;
866 quoteMakeTarget(A->getValue(), Quoted);
867 CmdArgs.push_back(Args.MakeArgString(Quoted));
868 }
869 }
870
871 // Add a default target if one wasn't specified.
872 if (!HasTarget) {
873 const char *DepTarget;
874
875 // If user provided -o, that is the dependency target, except
876 // when we are only generating a dependency file.
877 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
878 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
879 DepTarget = OutputOpt->getValue();
880 } else {
881 // Otherwise derive from the base input.
882 //
883 // FIXME: This should use the computed output file location.
884 SmallString<128> P(Inputs[0].getBaseInput());
885 llvm::sys::path::replace_extension(P, "o");
886 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
887 }
888
889 CmdArgs.push_back("-MT");
890 SmallString<128> Quoted;
891 quoteMakeTarget(DepTarget, Quoted);
892 CmdArgs.push_back(Args.MakeArgString(Quoted));
893 }
894
895 if (ArgM->getOption().matches(options::OPT_M) ||
896 ArgM->getOption().matches(options::OPT_MD))
897 CmdArgs.push_back("-sys-header-deps");
898
899 // Determine module file deps mode.
900 StringRef ModuleFileDepsVal;
901 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
902 options::OPT_fmodule_file_deps,
903 options::OPT_fno_module_file_deps)) {
904 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
905 ModuleFileDepsVal = A->getValue();
906 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
907 ModuleFileDepsVal = "all";
908 else
909 ModuleFileDepsVal = "none";
910 } else if (isa<PrecompileJobAction>(JA)) {
911 ModuleFileDepsVal = "all";
912 }
913 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
914 CmdArgs.push_back(
915 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
916 }
917
918 if (Args.hasArg(options::OPT_MG)) {
919 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
920 ArgM->getOption().matches(options::OPT_MMD))
921 D.Diag(diag::err_drv_mg_requires_m_or_mm);
922 CmdArgs.push_back("-MG");
923 }
924
925 Args.AddLastArg(CmdArgs, options::OPT_MP);
926 Args.AddLastArg(CmdArgs, options::OPT_MV);
927
928 bool UsesLLVMOffloading = Args.hasFlag(
929 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
930 bool UsesOffloadInclude =
931 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc, true);
932 bool NoBuiltinInc = Args.hasArg(options::OPT_nobuiltininc);
933
934 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
935 // want to pull in our wrappers instead of the vendor headers.
936 if (UsesLLVMOffloading) {
937 if (UsesOffloadInclude && !NoBuiltinInc) {
938 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
939 StringRef RuntimeHeader) {
940 SmallString<128> OffloadInclude(D.Dir);
941 llvm::sys::path::append(OffloadInclude, "..", "include", "offload");
942 if (!IncludeSubdir.empty())
943 llvm::sys::path::append(OffloadInclude, IncludeSubdir);
944 CmdArgs.append({"-internal-isystem", Args.MakeArgString(OffloadInclude),
945 "-include", Args.MakeArgString(RuntimeHeader)});
946 };
947 auto AddForcedInclude = [&](StringRef Header) {
948 CmdArgs.push_back("-include");
949 CmdArgs.push_back(Args.MakeArgString(Header));
950 };
951 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
952 AddForcedInclude("__clang_gpu_builtin_vars.h");
953 AddForcedInclude("__clang_gpu_device_functions.h");
954 AddForcedInclude("__clang_gpu_intrinsics.h");
956 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
958 !Args.hasArg(options::OPT_nohipwrapperinc)) {
959 // HIP code commonly includes this as "hip/hip_runtime.h".
960 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
961 }
962 }
963 } else {
964 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
965 // happen before we -I or -include anything else, because we must pick up
966 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
967 // installation, rather than from e.g. /usr/local/include.
969 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
971 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
973 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
974
975 // If we are offloading to a target via OpenMP we need to include the
976 // openmp_wrappers folder which contains alternative system headers.
978 !Args.hasArg(options::OPT_nostdinc) && UsesOffloadInclude &&
979 getToolChain().getTriple().isGPU()) {
980 if (!NoBuiltinInc) {
981 // Add openmp_wrappers/* to our system include path. This lets us
982 // wrap standard library headers.
983 SmallString<128> P(D.ResourceDir);
984 llvm::sys::path::append(P, "include");
985 llvm::sys::path::append(P, "openmp_wrappers");
986 CmdArgs.push_back("-internal-isystem");
987 CmdArgs.push_back(Args.MakeArgString(P));
988 }
989
990 CmdArgs.push_back("-include");
991 CmdArgs.push_back("__clang_openmp_device_functions.h");
992 }
993 }
994
995 // Add -i* options, and automatically translate to
996 // -include-pch/-include-pth for transparent PCH support. It's
997 // wonky, but we include looking for .gch so we can support seamless
998 // replacement into a build system already set up to be generating
999 // .gch files.
1000
1001 if (getToolChain().getDriver().IsCLMode()) {
1002 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1003 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1004 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1006 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1007 // -fpch-instantiate-templates is the default when creating
1008 // precomp using /Yc
1009 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1010 options::OPT_fno_pch_instantiate_templates, true))
1011 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1012 }
1013 if (YcArg || YuArg) {
1014 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1015 if (!isa<PrecompileJobAction>(JA)) {
1016 CmdArgs.push_back("-include-pch");
1017 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1018 C, !ThroughHeader.empty()
1019 ? ThroughHeader
1020 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1021 }
1022
1023 if (ThroughHeader.empty()) {
1024 CmdArgs.push_back(Args.MakeArgString(
1025 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1026 } else {
1027 CmdArgs.push_back(
1028 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1029 }
1030 }
1031 }
1032
1033 bool RenderedImplicitInclude = false;
1034 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1035 if (A->getOption().matches(options::OPT_include) &&
1036 D.getProbePrecompiled()) {
1037 // Handling of gcc-style gch precompiled headers.
1038 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1039 RenderedImplicitInclude = true;
1040
1041 bool FoundPCH = false;
1042 SmallString<128> P(A->getValue());
1043 // We want the files to have a name like foo.h.pch. Add a dummy extension
1044 // so that replace_extension does the right thing.
1045 P += ".dummy";
1046 llvm::sys::path::replace_extension(P, "pch");
1047 if (D.getVFS().exists(P))
1048 FoundPCH = true;
1049
1050 if (!FoundPCH) {
1051 // For GCC compat, probe for a file or directory ending in .gch instead.
1052 llvm::sys::path::replace_extension(P, "gch");
1053 FoundPCH = gchProbe(D, P.str());
1054 }
1055
1056 if (FoundPCH) {
1057 if (IsFirstImplicitInclude) {
1058 A->claim();
1059 CmdArgs.push_back("-include-pch");
1060 CmdArgs.push_back(Args.MakeArgString(P));
1061 continue;
1062 } else {
1063 // Ignore the PCH if not first on command line and emit warning.
1064 D.Diag(diag::warn_drv_pch_not_first_include) << P
1065 << A->getAsString(Args);
1066 }
1067 }
1068 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1069 // Handling of paths which must come late. These entries are handled by
1070 // the toolchain itself after the resource dir is inserted in the right
1071 // search order.
1072 // Do not claim the argument so that the use of the argument does not
1073 // silently go unnoticed on toolchains which do not honour the option.
1074 continue;
1075 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1076 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1077 continue;
1078 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1079 // This is used only by the driver. No need to pass to cc1.
1080 continue;
1081 }
1082
1083 // Not translated, render as usual.
1084 A->claim();
1085 A->render(Args, CmdArgs);
1086 }
1087
1088 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1090 // Collect all enabled NVPTX architectures.
1091 std::set<unsigned> ArchIDs;
1092 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1093 const ToolChain *TC = I.second;
1094 for (BoundArch Arch :
1095 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1096 if (Arch.Arch.isNVPTX())
1097 ArchIDs.insert(CudaArchToID(Arch.Arch));
1098 }
1099 }
1100
1101 if (!ArchIDs.empty()) {
1102 SmallString<128> List;
1103 llvm::raw_svector_ostream OS(List);
1104 llvm::interleave(ArchIDs, OS, ",");
1105 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1106 }
1107 }
1108
1109 Args.addAllArgs(CmdArgs,
1110 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1111 options::OPT_F, options::OPT_embed_dir_EQ});
1112
1113 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1114
1115 // FIXME: There is a very unfortunate problem here, some troubled
1116 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1117 // really support that we would have to parse and then translate
1118 // those options. :(
1119 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1120 options::OPT_Xpreprocessor);
1121
1122 // -I- is a deprecated GCC feature, reject it.
1123 if (Arg *A = Args.getLastArg(options::OPT_I_))
1124 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1125
1126 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1127 // -isysroot to the CC1 invocation.
1128 StringRef sysroot = C.getSysRoot();
1129 if (sysroot != "") {
1130 if (!Args.hasArg(options::OPT_isysroot)) {
1131 CmdArgs.push_back("-isysroot");
1132 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1133 }
1134 }
1135
1136 // Parse additional include paths from environment variables.
1137 // FIXME: We should probably sink the logic for handling these from the
1138 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1139 // CPATH - included following the user specified includes (but prior to
1140 // builtin and standard includes).
1141 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1142 // C_INCLUDE_PATH - system includes enabled when compiling C.
1143 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1144 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1145 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1146 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1147 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1148 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1149 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1150
1151 // While adding the include arguments, we also attempt to retrieve the
1152 // arguments of related offloading toolchains or arguments that are specific
1153 // of an offloading programming model.
1154
1155 // Add C++ include arguments, if needed.
1156 if (types::isCXX(Inputs[0].getType())) {
1157 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1159 C, JA, getToolChain(),
1160 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1161 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1162 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1163 });
1164 }
1165
1166 // If we are compiling for a GPU target with the LLVM environment we want to
1167 // override the system headers with ones created by the 'libc' project if
1168 // present.
1169 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1170 // OffloadKind as an argument.
1171 bool OffloadUsesLLVMLibc =
1172 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1173 (C.getActiveOffloadKinds() != Action::OFK_None &&
1174 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1175 if (!Args.hasArg(options::OPT_nostdinc) &&
1176 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1177 true) &&
1178 !Args.hasArg(options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1179 SmallString<128> P(D.ResourceDir);
1180 llvm::sys::path::append(P, "include");
1181 llvm::sys::path::append(P, "llvm_libc_wrappers");
1182 CmdArgs.push_back("-internal-isystem");
1183 CmdArgs.push_back(Args.MakeArgString(P));
1184 }
1185
1186 // Add system include arguments for all targets but IAMCU.
1187 if (!IsIAMCU)
1189 [&Args, &CmdArgs](const ToolChain &TC) {
1190 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1191 });
1192 else {
1193 // For IAMCU add special include arguments.
1194 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1195 }
1196
1197 addMacroPrefixMapArg(D, Args, CmdArgs);
1198 addCoveragePrefixMapArg(D, Args, CmdArgs);
1199
1200 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1201 options::OPT_fno_file_reproducible);
1202
1203 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1204 CmdArgs.push_back("-source-date-epoch");
1205 CmdArgs.push_back(Args.MakeArgString(Epoch));
1206 }
1207
1208 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1209 options::OPT_fno_define_target_os_macros);
1210}
1211
1212// FIXME: Move to target hook.
1213static bool isSignedCharDefault(const llvm::Triple &Triple) {
1214 switch (Triple.getArch()) {
1215 default:
1216 return true;
1217
1218 case llvm::Triple::aarch64:
1219 case llvm::Triple::aarch64_32:
1220 case llvm::Triple::aarch64_be:
1221 case llvm::Triple::arm:
1222 case llvm::Triple::armeb:
1223 case llvm::Triple::thumb:
1224 case llvm::Triple::thumbeb:
1225 if (Triple.isOSDarwin() || Triple.isOSWindowsOrUEFI())
1226 return true;
1227 return false;
1228
1229 case llvm::Triple::ppc:
1230 case llvm::Triple::ppc64:
1231 if (Triple.isOSDarwin())
1232 return true;
1233 return false;
1234
1235 case llvm::Triple::csky:
1236 case llvm::Triple::hexagon:
1237 case llvm::Triple::msp430:
1238 case llvm::Triple::ppcle:
1239 case llvm::Triple::ppc64le:
1240 case llvm::Triple::riscv32:
1241 case llvm::Triple::riscv64:
1242 case llvm::Triple::riscv32be:
1243 case llvm::Triple::riscv64be:
1244 case llvm::Triple::systemz:
1245 case llvm::Triple::xcore:
1246 case llvm::Triple::xtensa:
1247 return false;
1248 }
1249}
1250
1251static bool hasMultipleInvocations(const llvm::Triple &Triple,
1252 const ArgList &Args) {
1253 // Supported only on Darwin where we invoke the compiler multiple times
1254 // followed by an invocation to lipo.
1255 if (!Triple.isOSDarwin())
1256 return false;
1257 // If more than one "-arch <arch>" is specified, we're targeting multiple
1258 // architectures resulting in a fat binary.
1259 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1260}
1261
1262static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1263 const llvm::Triple &Triple) {
1264 // When enabling remarks, we need to error if:
1265 // * The remark file is specified but we're targeting multiple architectures,
1266 // which means more than one remark file is being generated.
1268 bool hasExplicitOutputFile =
1269 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1270 if (hasMultipleInvocations && hasExplicitOutputFile) {
1271 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1272 << "-foptimization-record-file";
1273 return false;
1274 }
1275 return true;
1276}
1277
1278static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1279 const llvm::Triple &Triple,
1280 const InputInfo &Input,
1281 const InputInfo &Output, const JobAction &JA) {
1282 StringRef Format = "yaml";
1283 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1284 Format = A->getValue();
1285
1286 CmdArgs.push_back("-opt-record-file");
1287
1288 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1289 if (A) {
1290 CmdArgs.push_back(A->getValue());
1291 } else {
1292 bool hasMultipleArchs =
1293 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1294 Args.getAllArgValues(options::OPT_arch).size() > 1;
1295
1297
1298 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1299 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1300 F = FinalOutput->getValue();
1301 } else {
1302 if (Format != "yaml" && // For YAML, keep the original behavior.
1303 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1304 Output.isFilename())
1305 F = Output.getFilename();
1306 }
1307
1308 if (F.empty()) {
1309 // Use the input filename.
1310 F = llvm::sys::path::stem(Input.getBaseInput());
1311
1312 // If we're compiling for an offload architecture (i.e. a CUDA device),
1313 // we need to make the file name for the device compilation different
1314 // from the host compilation.
1317 llvm::sys::path::replace_extension(F, "");
1319 Triple.str());
1320 F += "-";
1321 F += JA.getOffloadingArch().ArchName;
1322 }
1323 }
1324
1325 // If we're having more than one "-arch", we should name the files
1326 // differently so that every cc1 invocation writes to a different file.
1327 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1328 // name from the triple.
1329 if (hasMultipleArchs) {
1330 // First, remember the extension.
1331 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1332 // then, remove it.
1333 llvm::sys::path::replace_extension(F, "");
1334 // attach -<arch> to it.
1335 F += "-";
1336 F += Triple.getArchName();
1337 // put back the extension.
1338 llvm::sys::path::replace_extension(F, OldExtension);
1339 }
1340
1341 SmallString<32> Extension;
1342 Extension += "opt.";
1343 Extension += Format;
1344
1345 llvm::sys::path::replace_extension(F, Extension);
1346 CmdArgs.push_back(Args.MakeArgString(F));
1347 }
1348
1349 if (const Arg *A =
1350 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1351 CmdArgs.push_back("-opt-record-passes");
1352 CmdArgs.push_back(A->getValue());
1353 }
1354
1355 if (!Format.empty()) {
1356 CmdArgs.push_back("-opt-record-format");
1357 CmdArgs.push_back(Format.data());
1358 }
1359}
1360
1361void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1362 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1363 options::OPT_fno_aapcs_bitfield_width, true))
1364 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1365
1366 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1367 CmdArgs.push_back("-faapcs-bitfield-load");
1368}
1369
1370namespace {
1371void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1372 const ArgList &Args, ArgStringList &CmdArgs) {
1373 // Select the ABI to use.
1374 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1375 const char *ABIName = nullptr;
1376 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1377 ABIName = A->getValue();
1378 else
1379 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1380
1381 CmdArgs.push_back("-target-abi");
1382 CmdArgs.push_back(ABIName);
1383}
1384
1385void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1386 auto StrictAlignIter =
1387 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1388 return Arg == "+strict-align" || Arg == "-strict-align";
1389 });
1390 if (StrictAlignIter != CmdArgs.rend() &&
1391 StringRef(*StrictAlignIter) == "+strict-align")
1392 CmdArgs.push_back("-Wunaligned-access");
1393}
1394}
1395
1396static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1397 ArgStringList &CmdArgs, bool isAArch64) {
1398 const llvm::Triple &Triple = TC.getEffectiveTriple();
1399 const Arg *A = isAArch64
1400 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1401 options::OPT_mbranch_protection_EQ)
1402 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1403 const Arg *HardenPACRetArg = Args.getLastArg(options::OPT_mharden_pac_ret_EQ);
1404 const Driver &D = TC.getDriver();
1405
1406 if (HardenPACRetArg) {
1407 if (!isAArch64) {
1408 D.Diag(diag::err_drv_unsupported_opt_for_target)
1409 << HardenPACRetArg->getSpelling() << TC.getTriple().str();
1410 return;
1411 }
1412 StringRef ArgValue = HardenPACRetArg->getValue();
1413 if (ArgValue != "none" && ArgValue != "load-return-address") {
1414 D.Diag(diag::err_drv_unsupported_option_argument)
1415 << HardenPACRetArg->getSpelling() << ArgValue;
1416 return;
1417 }
1418 if (ArgValue != "none" &&
1419 Args.hasFlagNoClaim(options::OPT_mexecute_only,
1420 options::OPT_mno_execute_only, false)) {
1421 D.Diag(diag::err_drv_incompatible_options)
1422 << HardenPACRetArg->getAsString(Args) << "-mexecute-only";
1423 return;
1424 }
1425 }
1426
1427 // Check CmdArgs because some toolchains bypass the driver args and add to
1428 // the frontend args directly.
1429 bool HasPtrauthReturns =
1430 llvm::is_contained(CmdArgs, StringRef("-fptrauth-returns")) ||
1431 Args.hasFlagNoClaim(options::OPT_fptrauth_returns,
1432 options::OPT_fno_ptrauth_returns, false);
1433
1434 auto RenderHardenPACRet = [&](StringRef Scope) {
1435 if (!HardenPACRetArg)
1436 return;
1437 if (Scope == "none" && !HasPtrauthReturns)
1438 D.Diag(diag::warn_harden_pac_ret_requires_pac_ret);
1439 else
1440 CmdArgs.push_back(Args.MakeArgString(Twine("-mharden-pac-ret=") +
1441 HardenPACRetArg->getValue()));
1442 };
1443
1444 if (!A) {
1445 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1446 CmdArgs.push_back("-msign-return-address=non-leaf");
1447 CmdArgs.push_back("-msign-return-address-key=a_key");
1448 CmdArgs.push_back("-mbranch-target-enforce");
1449 RenderHardenPACRet("non-leaf");
1450 } else {
1451 RenderHardenPACRet("none");
1452 }
1453 return;
1454 }
1455
1456 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1457 D.Diag(diag::warn_incompatible_branch_protection_option)
1458 << Triple.getArchName();
1459
1460 StringRef Scope, Key;
1461 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1462
1463 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1464 Scope = A->getValue();
1465 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1466 D.Diag(diag::err_drv_unsupported_option_argument)
1467 << A->getSpelling() << Scope;
1468 // This spelling cannot express a key, and AArch64 Windows and UEFI only
1469 // support B-key, so default to it there as parseBranchProtection() does.
1470 Key = isAArch64 && Triple.isOSWindowsOrUEFI() ? "b_key" : "a_key";
1471 IndirectBranches =
1472 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1473 BranchProtectionPAuthLR = false;
1474 GuardedControlStack = false;
1475 } else {
1476 StringRef DiagMsg;
1477 llvm::ARM::ParsedBranchProtection PBP;
1478 bool EnablePAuthLR = false;
1479
1480 // To know if we need to enable PAuth-LR As part of the standard branch
1481 // protection option, it needs to be determined if the feature has been
1482 // activated in the `march` argument. This information is stored within the
1483 // CmdArgs variable and can be found using a search.
1484 if (isAArch64) {
1485 auto isPAuthLR = [](const char *member) {
1486 llvm::AArch64::ExtensionInfo pauthlr_extension =
1487 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1488 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1489 member;
1490 };
1491
1492 if (llvm::any_of(CmdArgs, isPAuthLR))
1493 EnablePAuthLR = true;
1494 }
1495 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1496 EnablePAuthLR))
1497 D.Diag(diag::err_drv_unsupported_option_argument)
1498 << A->getSpelling() << DiagMsg;
1499 if (!isAArch64 && PBP.Key == "b_key")
1500 D.Diag(diag::warn_unsupported_branch_protection)
1501 << "b-key" << A->getAsString(Args);
1502 Scope = PBP.Scope;
1503 Key = PBP.Key;
1504 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1505 IndirectBranches = PBP.BranchTargetEnforcement;
1506 GuardedControlStack = PBP.GuardedControlStack;
1507 }
1508
1509 // GCS is currently untested with ptrauth-returns, but enabling this could be
1510 // allowed in future after testing with a suitable system.
1511 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1512 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1513 D.Diag(diag::err_drv_unsupported_opt_for_target)
1514 << A->getAsString(Args) << Triple.getTriple();
1515 else if (HasPtrauthReturns)
1516 D.Diag(diag::err_drv_incompatible_options)
1517 << A->getAsString(Args) << "-fptrauth-returns";
1518 }
1519
1520 CmdArgs.push_back(
1521 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1522 if (Scope != "none")
1523 CmdArgs.push_back(
1524 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1525 if (BranchProtectionPAuthLR)
1526 CmdArgs.push_back(
1527 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1528 if (IndirectBranches)
1529 CmdArgs.push_back("-mbranch-target-enforce");
1530
1531 if (GuardedControlStack)
1532 CmdArgs.push_back("-mguarded-control-stack");
1533
1534 RenderHardenPACRet(Scope);
1535}
1536
1537void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1538 ArgStringList &CmdArgs, bool KernelOrKext) const {
1539 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1540
1541 // Determine floating point ABI from the options & target defaults.
1543 if (ABI == arm::FloatABI::Soft) {
1544 // Floating point operations and argument passing are soft.
1545 // FIXME: This changes CPP defines, we need -target-soft-float.
1546 CmdArgs.push_back("-msoft-float");
1547 CmdArgs.push_back("-mfloat-abi");
1548 CmdArgs.push_back("soft");
1549 } else if (ABI == arm::FloatABI::SoftFP) {
1550 // Floating point operations are hard, but argument passing is soft.
1551 CmdArgs.push_back("-mfloat-abi");
1552 CmdArgs.push_back("soft");
1553 } else {
1554 // Floating point operations and argument passing are hard.
1555 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1556 CmdArgs.push_back("-mfloat-abi");
1557 CmdArgs.push_back("hard");
1558 }
1559
1560 // Forward the -mglobal-merge option for explicit control over the pass.
1561 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1562 options::OPT_mno_global_merge)) {
1563 CmdArgs.push_back("-mllvm");
1564 if (A->getOption().matches(options::OPT_mno_global_merge))
1565 CmdArgs.push_back("-arm-global-merge=false");
1566 else
1567 CmdArgs.push_back("-arm-global-merge=true");
1568 }
1569
1570 if (!Args.hasFlag(options::OPT_mimplicit_float,
1571 options::OPT_mno_implicit_float, true))
1572 CmdArgs.push_back("-no-implicit-float");
1573
1574 if (Args.getLastArg(options::OPT_mcmse))
1575 CmdArgs.push_back("-mcmse");
1576
1577 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1578
1579 // Enable/disable return address signing and indirect branch targets.
1580 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1581
1582 AddUnalignedAccessWarning(CmdArgs);
1583}
1584
1585void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1586 ArgStringList &CmdArgs) const {
1587 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1588 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1589 A->render(Args, CmdArgs);
1590 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1591 A->render(Args, CmdArgs);
1592}
1593
1594void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1595 const ArgList &Args, bool KernelOrKext,
1596 ArgStringList &CmdArgs) const {
1597 const ToolChain &TC = getToolChain();
1598
1599 // Add the target features
1600 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1601
1602 // Add target specific flags.
1603 switch (TC.getArch()) {
1604 default:
1605 break;
1606
1607 case llvm::Triple::arm:
1608 case llvm::Triple::armeb:
1609 case llvm::Triple::thumb:
1610 case llvm::Triple::thumbeb:
1611 // Use the effective triple, which takes into account the deployment target.
1612 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1613 break;
1614
1615 case llvm::Triple::aarch64:
1616 case llvm::Triple::aarch64_32:
1617 case llvm::Triple::aarch64_be:
1618 AddAArch64TargetArgs(Args, CmdArgs);
1619 break;
1620
1621 case llvm::Triple::amdgpu:
1622 AddAMDGPUTargetArgs(Args, CmdArgs);
1623 break;
1624
1625 case llvm::Triple::loongarch32:
1626 case llvm::Triple::loongarch64:
1627 AddLoongArchTargetArgs(Args, CmdArgs);
1628 break;
1629
1630 case llvm::Triple::mips:
1631 case llvm::Triple::mipsel:
1632 case llvm::Triple::mips64:
1633 case llvm::Triple::mips64el:
1634 AddMIPSTargetArgs(Args, CmdArgs);
1635 break;
1636
1637 case llvm::Triple::ppc:
1638 case llvm::Triple::ppcle:
1639 case llvm::Triple::ppc64:
1640 case llvm::Triple::ppc64le:
1641 AddPPCTargetArgs(Args, CmdArgs);
1642 break;
1643
1644 case llvm::Triple::riscv32:
1645 case llvm::Triple::riscv64:
1646 case llvm::Triple::riscv32be:
1647 case llvm::Triple::riscv64be:
1648 AddRISCVTargetArgs(Args, CmdArgs);
1649 break;
1650
1651 case llvm::Triple::sparc:
1652 case llvm::Triple::sparcel:
1653 case llvm::Triple::sparcv9:
1654 AddSparcTargetArgs(Args, CmdArgs);
1655 break;
1656
1657 case llvm::Triple::systemz:
1658 AddSystemZTargetArgs(Args, CmdArgs);
1659 break;
1660
1661 case llvm::Triple::x86:
1662 case llvm::Triple::x86_64:
1663 AddX86TargetArgs(Args, CmdArgs);
1664 break;
1665
1666 case llvm::Triple::lanai:
1667 AddLanaiTargetArgs(Args, CmdArgs);
1668 break;
1669
1670 case llvm::Triple::hexagon:
1671 AddHexagonTargetArgs(Args, CmdArgs);
1672 break;
1673
1674 case llvm::Triple::wasm32:
1675 case llvm::Triple::wasm64:
1676 AddWebAssemblyTargetArgs(Args, CmdArgs);
1677 break;
1678
1679 case llvm::Triple::ve:
1680 AddVETargetArgs(Args, CmdArgs);
1681 break;
1682 }
1683}
1684
1685namespace {
1686void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1687 ArgStringList &CmdArgs) {
1688 const char *ABIName = nullptr;
1689 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1690 ABIName = A->getValue();
1691 else if (Triple.isOSDarwin())
1692 ABIName = "darwinpcs";
1693 // TODO: we probably want to have some target hook here.
1694 else if (Triple.isOSLinux() &&
1695 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1696 ABIName = "pauthtest";
1697 else
1698 ABIName = "aapcs";
1699
1700 CmdArgs.push_back("-target-abi");
1701 CmdArgs.push_back(ABIName);
1702}
1703}
1704
1705void Clang::AddAArch64TargetArgs(const ArgList &Args,
1706 ArgStringList &CmdArgs) const {
1707 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1708
1709 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1710 Args.hasArg(options::OPT_mkernel) ||
1711 Args.hasArg(options::OPT_fapple_kext))
1712 CmdArgs.push_back("-disable-red-zone");
1713
1714 if (!Args.hasFlag(options::OPT_mimplicit_float,
1715 options::OPT_mno_implicit_float, true))
1716 CmdArgs.push_back("-no-implicit-float");
1717
1718 RenderAArch64ABI(Triple, Args, CmdArgs);
1719
1720 // Forward the -mglobal-merge option for explicit control over the pass.
1721 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1722 options::OPT_mno_global_merge)) {
1723 CmdArgs.push_back("-mllvm");
1724 if (A->getOption().matches(options::OPT_mno_global_merge))
1725 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1726 else
1727 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1728 }
1729
1730 // Handle -msve_vector_bits=<bits>
1731 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1732 StringRef VScaleMax) {
1733 StringRef Val = A->getValue();
1734 const Driver &D = getToolChain().getDriver();
1735 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1736 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1737 Val == "1024+" || Val == "2048+") {
1738 unsigned Bits = 0;
1739 if (!Val.consume_back("+")) {
1740 bool Invalid = Val.getAsInteger(10, Bits);
1741 (void)Invalid;
1742 assert(!Invalid && "Failed to parse value");
1743 CmdArgs.push_back(
1744 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1745 }
1746
1747 bool Invalid = Val.getAsInteger(10, Bits);
1748 (void)Invalid;
1749 assert(!Invalid && "Failed to parse value");
1750
1751 CmdArgs.push_back(
1752 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1753 } else if (Val == "scalable") {
1754 // Silently drop requests for vector-length agnostic code as it's implied.
1755 } else {
1756 // Handle the unsupported values passed to msve-vector-bits.
1757 D.Diag(diag::err_drv_unsupported_option_argument)
1758 << A->getSpelling() << Val;
1759 }
1760 };
1761 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1762 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1763 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1764 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1765
1766 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1767
1768 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1769 CmdArgs.push_back("-tune-cpu");
1770 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1771 }
1772
1773 AddUnalignedAccessWarning(CmdArgs);
1774
1775 if (Triple.isOSDarwin() ||
1776 (Triple.isOSLinux() &&
1777 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1778 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1779 options::OPT_fno_ptrauth_intrinsics);
1780 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1781 options::OPT_fno_ptrauth_calls);
1782 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1783 options::OPT_fno_ptrauth_returns);
1784 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1785 options::OPT_fno_ptrauth_auth_traps);
1786 Args.addOptInFlag(
1787 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1788 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1789 Args.addOptInFlag(
1790 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1791 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1792 Args.addOptInFlag(
1793 CmdArgs, options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1794 options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1795 Args.addOptInFlag(
1796 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1797 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1798 Args.addOptInFlag(
1799 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1800 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1801 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1802 options::OPT_fno_ptrauth_indirect_gotos);
1803 }
1804 if (Triple.isOSLinux() &&
1805 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1806 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1807 options::OPT_fno_ptrauth_init_fini);
1808 Args.addOptInFlag(
1809 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1810 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1811 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1812 options::OPT_fno_ptrauth_elf_got);
1813 }
1814 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1815 options::OPT_fno_aarch64_jump_table_hardening);
1816
1817 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1818 options::OPT_fno_ptrauth_objc_isa);
1819 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1820 options::OPT_fno_ptrauth_objc_interface_sel);
1821 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1822 options::OPT_fno_ptrauth_objc_class_ro);
1823
1824 // Enable/disable return address signing and indirect branch targets.
1825 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1826}
1827
1828void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1829 ArgStringList &CmdArgs) const {
1830 const llvm::Triple &Triple = getToolChain().getTriple();
1831
1832 CmdArgs.push_back("-target-abi");
1833 CmdArgs.push_back(
1834 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1835 .data());
1836
1837 // Handle -mtune.
1838 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1839 std::string TuneCPU = A->getValue();
1840 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1841 CmdArgs.push_back("-tune-cpu");
1842 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1843 }
1844
1845 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1846 options::OPT_mno_annotate_tablejump)) {
1847 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1848 CmdArgs.push_back("-mllvm");
1849 CmdArgs.push_back("-loongarch-annotate-tablejump");
1850 }
1851 }
1852}
1853
1854void Clang::AddMIPSTargetArgs(const ArgList &Args,
1855 ArgStringList &CmdArgs) const {
1856 const Driver &D = getToolChain().getDriver();
1857 StringRef CPUName;
1858 StringRef ABIName;
1859 const llvm::Triple &Triple = getToolChain().getTriple();
1860 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1861
1862 CmdArgs.push_back("-target-abi");
1863 CmdArgs.push_back(ABIName.data());
1864
1865 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1866 if (ABI == mips::FloatABI::Soft) {
1867 // Floating point operations and argument passing are soft.
1868 CmdArgs.push_back("-msoft-float");
1869 CmdArgs.push_back("-mfloat-abi");
1870 CmdArgs.push_back("soft");
1871 } else {
1872 // Floating point operations and argument passing are hard.
1873 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1874 CmdArgs.push_back("-mfloat-abi");
1875 CmdArgs.push_back("hard");
1876 }
1877
1878 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1879 options::OPT_mno_ldc1_sdc1)) {
1880 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1881 CmdArgs.push_back("-mllvm");
1882 CmdArgs.push_back("-mno-ldc1-sdc1");
1883 }
1884 }
1885
1886 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1887 options::OPT_mno_check_zero_division)) {
1888 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1889 CmdArgs.push_back("-mllvm");
1890 CmdArgs.push_back("-mno-check-zero-division");
1891 }
1892 }
1893
1894 if (Args.getLastArg(options::OPT_mfix4300)) {
1895 CmdArgs.push_back("-mllvm");
1896 CmdArgs.push_back("-mfix4300");
1897 }
1898
1899 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1900 StringRef v = A->getValue();
1901 CmdArgs.push_back("-mllvm");
1902 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1903 A->claim();
1904 }
1905
1906 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1907 Arg *ABICalls =
1908 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1909
1910 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1911 // -mgpopt is the default for static, -fno-pic environments but these two
1912 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1913 // the only case where -mllvm -mgpopt is passed.
1914 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1915 // passed explicitly when compiling something with -mabicalls
1916 // (implictly) in affect. Currently the warning is in the backend.
1917 //
1918 // When the ABI in use is N64, we also need to determine the PIC mode that
1919 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1920 bool NoABICalls =
1921 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1922
1923 llvm::Reloc::Model RelocationModel;
1924 unsigned PICLevel;
1925 bool IsPIE;
1926 std::tie(RelocationModel, PICLevel, IsPIE) =
1927 ParsePICArgs(getToolChain(), Args);
1928
1929 NoABICalls = NoABICalls ||
1930 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1931
1932 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1933 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1934 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1935 CmdArgs.push_back("-mllvm");
1936 CmdArgs.push_back("-mgpopt");
1937
1938 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1939 options::OPT_mno_local_sdata);
1940 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1941 options::OPT_mno_extern_sdata);
1942 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1943 options::OPT_mno_embedded_data);
1944 if (LocalSData) {
1945 CmdArgs.push_back("-mllvm");
1946 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1947 CmdArgs.push_back("-mlocal-sdata=1");
1948 } else {
1949 CmdArgs.push_back("-mlocal-sdata=0");
1950 }
1951 LocalSData->claim();
1952 }
1953
1954 if (ExternSData) {
1955 CmdArgs.push_back("-mllvm");
1956 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1957 CmdArgs.push_back("-mextern-sdata=1");
1958 } else {
1959 CmdArgs.push_back("-mextern-sdata=0");
1960 }
1961 ExternSData->claim();
1962 }
1963
1964 if (EmbeddedData) {
1965 CmdArgs.push_back("-mllvm");
1966 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1967 CmdArgs.push_back("-membedded-data=1");
1968 } else {
1969 CmdArgs.push_back("-membedded-data=0");
1970 }
1971 EmbeddedData->claim();
1972 }
1973
1974 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1975 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1976
1977 if (GPOpt)
1978 GPOpt->claim();
1979
1980 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1981 StringRef Val = StringRef(A->getValue());
1982 if (mips::hasCompactBranches(CPUName)) {
1983 if (Val == "never" || Val == "always" || Val == "optimal") {
1984 CmdArgs.push_back("-mllvm");
1985 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1986 } else
1987 D.Diag(diag::err_drv_unsupported_option_argument)
1988 << A->getSpelling() << Val;
1989 } else
1990 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1991 }
1992
1993 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1994 options::OPT_mno_relax_pic_calls)) {
1995 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1996 CmdArgs.push_back("-mllvm");
1997 CmdArgs.push_back("-mips-jalr-reloc=0");
1998 }
1999 }
2000}
2001
2002void Clang::AddPPCTargetArgs(const ArgList &Args,
2003 ArgStringList &CmdArgs) const {
2004 const Driver &D = getToolChain().getDriver();
2005 const llvm::Triple &T = getToolChain().getTriple();
2006 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2007 CmdArgs.push_back("-tune-cpu");
2008 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
2009 CmdArgs.push_back(Args.MakeArgString(CPU));
2010 }
2011
2012 // Select the ABI to use.
2013 const char *ABIName = nullptr;
2014 if (T.isOSBinFormatELF()) {
2015 switch (getToolChain().getArch()) {
2016 case llvm::Triple::ppc64: {
2017 if (T.isPPC64ELFv2ABI())
2018 ABIName = "elfv2";
2019 else
2020 ABIName = "elfv1";
2021 break;
2022 }
2023 case llvm::Triple::ppc64le:
2024 ABIName = "elfv2";
2025 break;
2026 default:
2027 break;
2028 }
2029 }
2030
2031 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2032 bool VecExtabi = false;
2033 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2034 StringRef V = A->getValue();
2035 if (V == "ieeelongdouble") {
2036 IEEELongDouble = true;
2037 A->claim();
2038 } else if (V == "ibmlongdouble") {
2039 IEEELongDouble = false;
2040 A->claim();
2041 } else if (V == "vec-default") {
2042 VecExtabi = false;
2043 A->claim();
2044 } else if (V == "vec-extabi") {
2045 VecExtabi = true;
2046 A->claim();
2047 } else if (V == "elfv1") {
2048 ABIName = "elfv1";
2049 A->claim();
2050 } else if (V == "elfv2") {
2051 ABIName = "elfv2";
2052 A->claim();
2053 } else if (V != "altivec")
2054 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2055 // the option if given as we don't have backend support for any targets
2056 // that don't use the altivec abi.
2057 ABIName = A->getValue();
2058 }
2059 if (IEEELongDouble)
2060 CmdArgs.push_back("-mabi=ieeelongdouble");
2061 if (VecExtabi) {
2062 if (!T.isOSAIX())
2063 D.Diag(diag::err_drv_unsupported_opt_for_target)
2064 << "-mabi=vec-extabi" << T.str();
2065 CmdArgs.push_back("-mabi=vec-extabi");
2066 }
2067
2068 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2069 CmdArgs.push_back("-disable-red-zone");
2070
2072 if (FloatABI == ppc::FloatABI::Soft) {
2073 // Floating point operations and argument passing are soft.
2074 CmdArgs.push_back("-msoft-float");
2075 CmdArgs.push_back("-mfloat-abi");
2076 CmdArgs.push_back("soft");
2077 } else {
2078 // Floating point operations and argument passing are hard.
2079 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2080 CmdArgs.push_back("-mfloat-abi");
2081 CmdArgs.push_back("hard");
2082 }
2083
2084 if (ABIName) {
2085 CmdArgs.push_back("-target-abi");
2086 CmdArgs.push_back(ABIName);
2087 }
2088}
2089
2090void Clang::AddRISCVTargetArgs(const ArgList &Args,
2091 ArgStringList &CmdArgs) const {
2092 const llvm::Triple &Triple = getToolChain().getTriple();
2093 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2094
2095 CmdArgs.push_back("-target-abi");
2096 CmdArgs.push_back(ABIName.data());
2097
2098 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2099 CmdArgs.push_back("-msmall-data-limit");
2100 CmdArgs.push_back(A->getValue());
2101 }
2102
2103 if (!Args.hasFlag(options::OPT_mimplicit_float,
2104 options::OPT_mno_implicit_float, true))
2105 CmdArgs.push_back("-no-implicit-float");
2106
2107 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2108 if (!TuneCPU)
2109 return;
2110 if (!TuneCPU->empty()) {
2111 CmdArgs.push_back("-tune-cpu");
2112 // TuneCPU might or might not be the original -mtune string, so we
2113 // have to create a new copy here.
2114 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2115 }
2116
2117 // Handle -mrvv-vector-bits=<bits>
2118 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2119 StringRef Val = A->getValue();
2120 const Driver &D = getToolChain().getDriver();
2121
2122 // Get minimum VLen from march.
2123 unsigned MinVLen = 0;
2124 std::string Arch = riscv::getRISCVArch(Args, Triple);
2125 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2126 Arch, /*EnableExperimentalExtensions*/ true);
2127 // Ignore parsing error.
2128 if (!errorToBool(ISAInfo.takeError()))
2129 MinVLen = (*ISAInfo)->getMinVLen();
2130
2131 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2132 // as integer as long as we have a MinVLen.
2133 unsigned Bits = 0;
2134 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2135 Bits = MinVLen;
2136 } else if (!Val.getAsInteger(10, Bits)) {
2137 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2138 // at least MinVLen.
2139 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2140 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2141 Bits = 0;
2142 }
2143
2144 // If we got a valid value try to use it.
2145 if (Bits != 0) {
2146 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2147 CmdArgs.push_back(
2148 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2149 CmdArgs.push_back(
2150 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2151 } else if (Val != "scalable") {
2152 // Handle the unsupported values passed to mrvv-vector-bits.
2153 D.Diag(diag::err_drv_unsupported_option_argument)
2154 << A->getSpelling() << Val;
2155 }
2156 }
2157}
2158
2159void Clang::AddSparcTargetArgs(const ArgList &Args,
2160 ArgStringList &CmdArgs) const {
2162 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2163
2164 if (FloatABI == sparc::FloatABI::Soft) {
2165 // Floating point operations and argument passing are soft.
2166 CmdArgs.push_back("-msoft-float");
2167 CmdArgs.push_back("-mfloat-abi");
2168 CmdArgs.push_back("soft");
2169 } else {
2170 // Floating point operations and argument passing are hard.
2171 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2172 CmdArgs.push_back("-mfloat-abi");
2173 CmdArgs.push_back("hard");
2174 }
2175
2176 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2177 StringRef Name = A->getValue();
2178 std::string TuneCPU;
2179 if (Name == "native")
2180 TuneCPU = std::string(llvm::sys::getHostCPUName());
2181 else
2182 TuneCPU = std::string(Name);
2183
2184 CmdArgs.push_back("-tune-cpu");
2185 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2186 }
2187}
2188
2189void Clang::AddSystemZTargetArgs(const ArgList &Args,
2190 ArgStringList &CmdArgs) const {
2191 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2192 CmdArgs.push_back("-tune-cpu");
2193 if (strcmp(A->getValue(), "native") == 0)
2194 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2195 else
2196 CmdArgs.push_back(A->getValue());
2197 }
2198
2199 bool HasBackchain =
2200 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2201 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2202 options::OPT_mno_packed_stack, false);
2204 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2205 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2206
2207 // Only hard float ABI (-mhard-float) is supported on z/OS.
2208 const Driver &D = getToolChain().getDriver();
2209 const llvm::Triple &Triple = getToolChain().getTriple();
2210 if (HasSoftFloat && Triple.isOSzOS()) {
2211 D.Diag(diag::err_drv_unsupported_opt_for_target)
2212 << "-msoft-float" << Triple.str();
2213 }
2214 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2215 D.Diag(diag::err_drv_unsupported_opt)
2216 << "-mpacked-stack -mbackchain -mhard-float";
2217 }
2218 if (HasBackchain)
2219 CmdArgs.push_back("-mbackchain");
2220 if (HasPackedStack)
2221 CmdArgs.push_back("-mpacked-stack");
2222 if (HasSoftFloat) {
2223 // Floating point operations and argument passing are soft.
2224 CmdArgs.push_back("-msoft-float");
2225 CmdArgs.push_back("-mfloat-abi");
2226 CmdArgs.push_back("soft");
2227 }
2228
2229 if (Triple.isOSzOS())
2230 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2231 options::OPT_mno_zos_ppa1_name);
2232}
2233
2234void Clang::AddX86TargetArgs(const ArgList &Args,
2235 ArgStringList &CmdArgs) const {
2236 const Driver &D = getToolChain().getDriver();
2237 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2238
2239 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2240 Args.hasArg(options::OPT_mkernel) ||
2241 Args.hasArg(options::OPT_fapple_kext))
2242 CmdArgs.push_back("-disable-red-zone");
2243
2244 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2245 options::OPT_mno_tls_direct_seg_refs, true))
2246 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2247
2248 // Default to avoid implicit floating-point for kernel/kext code, but allow
2249 // that to be overridden with -mno-soft-float.
2250 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2251 Args.hasArg(options::OPT_fapple_kext));
2252 if (Arg *A = Args.getLastArg(
2253 options::OPT_msoft_float, options::OPT_mno_soft_float,
2254 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2255 const Option &O = A->getOption();
2256 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2257 O.matches(options::OPT_msoft_float));
2258 }
2259 if (NoImplicitFloat)
2260 CmdArgs.push_back("-no-implicit-float");
2261
2262 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2263 StringRef Value = A->getValue();
2264 if (Value == "intel" || Value == "att") {
2265 CmdArgs.push_back("-mllvm");
2266 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2267 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2268 } else {
2269 D.Diag(diag::err_drv_unsupported_option_argument)
2270 << A->getSpelling() << Value;
2271 }
2272 } else if (D.IsCLMode()) {
2273 CmdArgs.push_back("-mllvm");
2274 CmdArgs.push_back("-x86-asm-syntax=intel");
2275 }
2276
2277 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2278 options::OPT_mno_skip_rax_setup))
2279 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2280 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2281
2282 // Set flags to support MCU ABI.
2283 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2284 CmdArgs.push_back("-mfloat-abi");
2285 CmdArgs.push_back("soft");
2286 CmdArgs.push_back("-mstack-alignment=4");
2287 }
2288
2289 // Handle -mtune.
2290
2291 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2292 std::string TuneCPU;
2293 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2294 TuneCPU = "generic";
2295
2296 // Override based on -mtune.
2297 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2298 StringRef Name = A->getValue();
2299
2300 if (Name == "native") {
2301 Name = llvm::sys::getHostCPUName();
2302 if (!Name.empty())
2303 TuneCPU = std::string(Name);
2304 } else
2305 TuneCPU = std::string(Name);
2306 }
2307
2308 if (!TuneCPU.empty()) {
2309 CmdArgs.push_back("-tune-cpu");
2310 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2311 }
2312}
2313
2314static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2315 size_t Index = Option.find(Delimiter);
2316 if (Index != StringRef::npos)
2317 Option = Option.substr(0, Index);
2318 return Option;
2319}
2320
2321static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2322 Opt = getOptionName(Opt);
2323 if (CmdArgs.size() < 2)
2324 return;
2325
2326 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2327 StringRef Option = *It;
2328 if (!Option.starts_with(Opt))
2329 continue;
2330 Option = getOptionName(Option);
2331 if (Option != Opt)
2332 continue;
2333 if (StringRef(*(It - 1)) != "-mllvm")
2334 continue;
2335
2336 It = CmdArgs.erase(It);
2337 CmdArgs.erase(It - 1);
2338 return;
2339 }
2340}
2341
2342static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2343 checkAndRemoveLLVMArg(CmdArgs, A);
2344 CmdArgs.push_back("-mllvm");
2345 CmdArgs.push_back(A);
2346}
2347
2348static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2349 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2350 StringRef Option = *It;
2351 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2352 It = CmdArgs.erase(It);
2353 Ie = CmdArgs.end();
2354 } else {
2355 ++It;
2356 }
2357 }
2358
2359 CmdArgs.push_back("-menable-no-infs");
2360 CmdArgs.push_back("-menable-no-nans");
2361 CmdArgs.push_back("-fapprox-func");
2362 CmdArgs.push_back("-funsafe-math-optimizations");
2363 CmdArgs.push_back("-fno-signed-zeros");
2364 CmdArgs.push_back("-mreassociate");
2365 CmdArgs.push_back("-freciprocal-math");
2366 CmdArgs.push_back("-ffp-contract=fast");
2367 CmdArgs.push_back("-ffast-math");
2368 CmdArgs.push_back("-ffinite-math-only");
2369 CmdArgs.push_back("-D__FAST_MATH__");
2370 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2371}
2372
2373static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2374 ArgStringList &CmdArgs) {
2375 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2376 bool HasHVX = HvxVerOpt.has_value();
2377 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2378 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2379 options::OPT_mhexagon_hvx_ieee_fp) ||
2380 !HasHVX)
2381 return;
2382 unsigned HvxVerNum = 0;
2383 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2384 HvxVerNum = 0;
2385
2386 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2387 options::OPT_mhexagon_hvx_qfloat_EQ,
2388 options::OPT_mhexagon_hvx_ieee_fp)) {
2389 if (HvxVerNum >= 79) {
2390 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2391 const char *Mode =
2392 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2393 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2394 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2395 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2396 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2397 .Default(nullptr);
2398 if (!Mode) {
2399 D.Diag(diag::err_drv_invalid_value)
2400 << A->getAsString(Args) << A->getValue();
2401 return;
2402 }
2403 pushBackLLVMArg(CmdArgs, Mode);
2404 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2406 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2407 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2409 } else {
2410 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2411 }
2412 } else {
2413 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2414 options::OPT_mhexagon_hvx_qfloat_EQ,
2415 options::OPT_mno_hexagon_hvx_qfloat);
2416 QFloatArg &&
2417 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2418 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2419 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2420 << (std::string("HVX ") + HvxVer +
2421 "; falling back to legacy qfloat mode");
2422 }
2423 }
2424 }
2425}
2426
2427void Clang::AddHexagonTargetArgs(const ArgList &Args,
2428 ArgStringList &CmdArgs) const {
2429 CmdArgs.push_back("-mqdsp6-compat");
2430 CmdArgs.push_back("-Wreturn-type");
2431
2433 CmdArgs.push_back("-mllvm");
2434 CmdArgs.push_back(
2435 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2436 }
2437
2438 if (!Args.hasArg(options::OPT_fno_short_enums))
2439 CmdArgs.push_back("-fshort-enums");
2440 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2441 CmdArgs.push_back("-mllvm");
2442 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2443 }
2444 CmdArgs.push_back("-mllvm");
2445 CmdArgs.push_back("-machine-sink-split=0");
2446
2447 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2448}
2449
2450void Clang::AddLanaiTargetArgs(const ArgList &Args,
2451 ArgStringList &CmdArgs) const {
2452 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2453 StringRef CPUName = A->getValue();
2454
2455 CmdArgs.push_back("-target-cpu");
2456 CmdArgs.push_back(Args.MakeArgString(CPUName));
2457 }
2458 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2459 StringRef Value = A->getValue();
2460 // Only support mregparm=4 to support old usage. Report error for all other
2461 // cases.
2462 int Mregparm;
2463 if (Value.getAsInteger(10, Mregparm)) {
2464 if (Mregparm != 4) {
2466 diag::err_drv_unsupported_option_argument)
2467 << A->getSpelling() << Value;
2468 }
2469 }
2470 }
2471}
2472
2473void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2474 ArgStringList &CmdArgs) const {
2475 // Default to "hidden" visibility.
2476 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2477 options::OPT_fvisibility_ms_compat))
2478 CmdArgs.push_back("-fvisibility=hidden");
2479}
2480
2481void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2482 // Floating point operations and argument passing are hard.
2483 CmdArgs.push_back("-mfloat-abi");
2484 CmdArgs.push_back("hard");
2485}
2486
2487void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2488 StringRef Target, const InputInfo &Output,
2489 const InputInfo &Input, const ArgList &Args) const {
2490 // If this is a dry run, do not create the compilation database file.
2491 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2492 return;
2493
2494 using llvm::yaml::escape;
2495 const Driver &D = getToolChain().getDriver();
2496
2497 if (!CompilationDatabase) {
2498 std::error_code EC;
2499 auto File = std::make_unique<llvm::raw_fd_ostream>(
2500 Filename, EC,
2501 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2502 if (EC) {
2503 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2504 << EC.message();
2505 return;
2506 }
2507 CompilationDatabase = std::move(File);
2508 }
2509 auto &CDB = *CompilationDatabase;
2510 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2511 if (!CWD)
2512 CWD = ".";
2513 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2514 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2515 if (Output.isFilename())
2516 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2517 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2518 SmallString<128> Buf;
2519 Buf = "-x";
2520 Buf += types::getTypeName(Input.getType());
2521 CDB << ", \"" << escape(Buf) << "\"";
2522 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2523 Buf = "--sysroot=";
2524 Buf += D.SysRoot;
2525 CDB << ", \"" << escape(Buf) << "\"";
2526 }
2527 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2528 if (Output.isFilename())
2529 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2530 for (auto &A: Args) {
2531 auto &O = A->getOption();
2532 // Skip language selection, which is positional.
2533 if (O.getID() == options::OPT_x)
2534 continue;
2535 // Skip writing dependency output and the compilation database itself.
2536 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2537 continue;
2538 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2539 continue;
2540 // Skip inputs.
2541 if (O.getKind() == Option::InputClass)
2542 continue;
2543 // Skip output.
2544 if (O.getID() == options::OPT_o)
2545 continue;
2546 // All other arguments are quoted and appended.
2547 ArgStringList ASL;
2548 A->render(Args, ASL);
2549 for (auto &it: ASL)
2550 CDB << ", \"" << escape(it) << "\"";
2551 }
2552 Buf = "--target=";
2553 Buf += Target;
2554 CDB << ", \"" << escape(Buf) << "\"]},\n";
2555}
2556
2557void Clang::DumpCompilationDatabaseFragmentToDir(
2558 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2559 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2560 // If this is a dry run, do not create the compilation database file.
2561 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2562 return;
2563
2564 if (CompilationDatabase)
2565 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2566
2567 SmallString<256> Path = Dir;
2568 const auto &Driver = C.getDriver();
2569 Driver.getVFS().makeAbsolute(Path);
2570 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2571 if (Err) {
2572 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2573 return;
2574 }
2575
2576 llvm::sys::path::append(
2577 Path,
2578 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2579 int FD;
2580 SmallString<256> TempPath;
2581 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2582 llvm::sys::fs::OF_Text);
2583 if (Err) {
2584 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2585 return;
2586 }
2587 CompilationDatabase =
2588 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2589 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2590}
2591
2592static bool CheckARMImplicitITArg(StringRef Value) {
2593 return Value == "always" || Value == "never" || Value == "arm" ||
2594 Value == "thumb";
2595}
2596
2597static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2598 StringRef Value) {
2599 CmdArgs.push_back("-mllvm");
2600 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2601}
2602
2604 const ArgList &Args,
2605 ArgStringList &CmdArgs,
2606 const Driver &D) {
2607 // Default to -mno-relax-all.
2608 //
2609 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2610 // cannot be done by assembler branch relaxation as it needs a free temporary
2611 // register. Because of this, branch relaxation is handled by a MachineIR pass
2612 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2613 // MachineIR branch relaxation inaccurate and it will miss cases where an
2614 // indirect branch is necessary.
2615 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2616 options::OPT_mno_relax_all);
2617
2618 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2619 options::OPT_mno_incremental_linker_compatible);
2620
2621 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2622
2623 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2624 options::OPT_fno_emit_compact_unwind_non_canonical);
2625
2626 // If you add more args here, also add them to the block below that
2627 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2628
2629 // When passing -I arguments to the assembler we sometimes need to
2630 // unconditionally take the next argument. For example, when parsing
2631 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2632 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2633 // arg after parsing the '-I' arg.
2634 bool TakeNextArg = false;
2635
2636 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2637 bool IsELF = Triple.isOSBinFormatELF();
2638 bool Crel = false, ExperimentalCrel = false;
2639 StringRef RelocSectionSym;
2640 bool SFrame = false, ExperimentalSFrame = false;
2641 bool ImplicitMapSyms = false;
2642 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2643 bool UseNoExecStack = false;
2644 bool Msa = false;
2645 const char *MipsTargetFeature = nullptr;
2646 llvm::SmallVector<const char *> SparcTargetFeatures;
2647 StringRef ImplicitIt;
2648 for (const Arg *A :
2649 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2650 options::OPT_mimplicit_it_EQ)) {
2651 A->claim();
2652
2653 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2654 switch (C.getDefaultToolChain().getArch()) {
2655 case llvm::Triple::arm:
2656 case llvm::Triple::armeb:
2657 case llvm::Triple::thumb:
2658 case llvm::Triple::thumbeb:
2659 // Only store the value; the last value set takes effect.
2660 ImplicitIt = A->getValue();
2661 if (!CheckARMImplicitITArg(ImplicitIt))
2662 D.Diag(diag::err_drv_unsupported_option_argument)
2663 << A->getSpelling() << ImplicitIt;
2664 continue;
2665 default:
2666 break;
2667 }
2668 }
2669
2670 for (StringRef Value : A->getValues()) {
2671 if (TakeNextArg) {
2672 CmdArgs.push_back(Value.data());
2673 TakeNextArg = false;
2674 continue;
2675 }
2676
2677 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2678 Value == "-mbig-obj")
2679 continue; // LLVM handles bigobj automatically
2680
2681 auto Equal = Value.split('=');
2682 auto checkArg = [&](bool ValidTarget,
2683 std::initializer_list<const char *> Set) {
2684 if (!ValidTarget) {
2685 D.Diag(diag::err_drv_unsupported_opt_for_target)
2686 << (Twine("-Wa,") + Equal.first + "=").str()
2687 << Triple.getTriple();
2688 } else if (!llvm::is_contained(Set, Equal.second)) {
2689 D.Diag(diag::err_drv_unsupported_option_argument)
2690 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2691 }
2692 };
2693 switch (C.getDefaultToolChain().getArch()) {
2694 default:
2695 break;
2696 case llvm::Triple::x86:
2697 case llvm::Triple::x86_64:
2698 if (Equal.first == "-mrelax-relocations" ||
2699 Equal.first == "--mrelax-relocations") {
2700 UseRelaxRelocations = Equal.second == "yes";
2701 checkArg(IsELF, {"yes", "no"});
2702 continue;
2703 }
2704 if (Value == "-msse2avx") {
2705 CmdArgs.push_back("-msse2avx");
2706 continue;
2707 }
2708 break;
2709 case llvm::Triple::wasm32:
2710 case llvm::Triple::wasm64:
2711 if (Value == "--no-type-check") {
2712 CmdArgs.push_back("-mno-type-check");
2713 continue;
2714 }
2715 break;
2716 case llvm::Triple::thumb:
2717 case llvm::Triple::thumbeb:
2718 case llvm::Triple::arm:
2719 case llvm::Triple::armeb:
2720 if (Equal.first == "-mimplicit-it") {
2721 // Only store the value; the last value set takes effect.
2722 ImplicitIt = Equal.second;
2723 checkArg(true, {"always", "never", "arm", "thumb"});
2724 continue;
2725 }
2726 if (Value == "-mthumb")
2727 // -mthumb has already been processed in ComputeLLVMTriple()
2728 // recognize but skip over here.
2729 continue;
2730 break;
2731 case llvm::Triple::aarch64:
2732 case llvm::Triple::aarch64_be:
2733 case llvm::Triple::aarch64_32:
2734 if (Equal.first == "-mmapsyms") {
2735 ImplicitMapSyms = Equal.second == "implicit";
2736 checkArg(IsELF, {"default", "implicit"});
2737 continue;
2738 }
2739 break;
2740 case llvm::Triple::mips:
2741 case llvm::Triple::mipsel:
2742 case llvm::Triple::mips64:
2743 case llvm::Triple::mips64el:
2744 if (Value == "--trap") {
2745 CmdArgs.push_back("-target-feature");
2746 CmdArgs.push_back("+use-tcc-in-div");
2747 continue;
2748 }
2749 if (Value == "--break") {
2750 CmdArgs.push_back("-target-feature");
2751 CmdArgs.push_back("-use-tcc-in-div");
2752 continue;
2753 }
2754 if (Value.starts_with("-msoft-float")) {
2755 CmdArgs.push_back("-target-feature");
2756 CmdArgs.push_back("+soft-float");
2757 continue;
2758 }
2759 if (Value.starts_with("-mhard-float")) {
2760 CmdArgs.push_back("-target-feature");
2761 CmdArgs.push_back("-soft-float");
2762 continue;
2763 }
2764 if (Value == "-mmsa") {
2765 Msa = true;
2766 continue;
2767 }
2768 if (Value == "-mno-msa") {
2769 Msa = false;
2770 continue;
2771 }
2772 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2773 .Case("-mips1", "+mips1")
2774 .Case("-mips2", "+mips2")
2775 .Case("-mips3", "+mips3")
2776 .Case("-mips4", "+mips4")
2777 .Case("-mips5", "+mips5")
2778 .Case("-mips32", "+mips32")
2779 .Case("-mips32r2", "+mips32r2")
2780 .Case("-mips32r3", "+mips32r3")
2781 .Case("-mips32r5", "+mips32r5")
2782 .Case("-mips32r6", "+mips32r6")
2783 .Case("-mips64", "+mips64")
2784 .Case("-mips64r2", "+mips64r2")
2785 .Case("-mips64r3", "+mips64r3")
2786 .Case("-mips64r5", "+mips64r5")
2787 .Case("-mips64r6", "+mips64r6")
2788 .Default(nullptr);
2789 if (MipsTargetFeature)
2790 continue;
2791 break;
2792
2793 case llvm::Triple::sparc:
2794 case llvm::Triple::sparcel:
2795 case llvm::Triple::sparcv9:
2796 if (Value == "--undeclared-regs") {
2797 // LLVM already allows undeclared use of G registers, so this option
2798 // becomes a no-op. This solely exists for GNU compatibility.
2799 // TODO implement --no-undeclared-regs
2800 continue;
2801 }
2802 SparcTargetFeatures =
2803 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2804 .Case("-Av8", {"-v8plus"})
2805 .Case("-Av8plus", {"+v8plus", "+v9"})
2806 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2807 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2808 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3",
2809 "+ua2005", "+ua2007"})
2810 .Case("-Av9", {"+v9"})
2811 .Case("-Av9a", {"+v9", "+vis"})
2812 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2813 .Case("-Av9d",
2814 {"+v9", "+vis", "+vis2", "+vis3", "+ua2005", "+ua2007"})
2815 .Default({});
2816 if (!SparcTargetFeatures.empty())
2817 continue;
2818 break;
2819 }
2820
2821 if (Value == "-force_cpusubtype_ALL") {
2822 // Do nothing, this is the default and we don't support anything else.
2823 } else if (Value == "-L") {
2824 CmdArgs.push_back("-msave-temp-labels");
2825 } else if (Value == "--fatal-warnings") {
2826 CmdArgs.push_back("-massembler-fatal-warnings");
2827 } else if (Value == "--no-warn" || Value == "-W") {
2828 CmdArgs.push_back("-massembler-no-warn");
2829 } else if (Value == "--noexecstack") {
2830 UseNoExecStack = true;
2831 } else if (Value.starts_with("-compress-debug-sections") ||
2832 Value.starts_with("--compress-debug-sections") ||
2833 Value == "-nocompress-debug-sections" ||
2834 Value == "--nocompress-debug-sections") {
2835 CmdArgs.push_back(Value.data());
2836 } else if (Value == "--crel") {
2837 Crel = true;
2838 } else if (Value == "--no-crel") {
2839 Crel = false;
2840 } else if (Value == "--allow-experimental-crel") {
2841 ExperimentalCrel = true;
2842 } else if (Value.starts_with("--reloc-section-sym=")) {
2843 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2844 } else if (Value.starts_with("-I")) {
2845 CmdArgs.push_back(Value.data());
2846 // We need to consume the next argument if the current arg is a plain
2847 // -I. The next arg will be the include directory.
2848 if (Value == "-I")
2849 TakeNextArg = true;
2850 } else if (Value.starts_with("-gdwarf-")) {
2851 // "-gdwarf-N" options are not cc1as options.
2852 unsigned DwarfVersion = DwarfVersionNum(Value);
2853 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2854 CmdArgs.push_back(Value.data());
2855 } else {
2856 RenderDebugEnablingArgs(Args, CmdArgs,
2857 llvm::codegenoptions::DebugInfoConstructor,
2858 DwarfVersion, llvm::DebuggerKind::Default);
2859 }
2860 } else if (Value == "--gsframe") {
2861 SFrame = true;
2862 } else if (Value == "--allow-experimental-sframe") {
2863 ExperimentalSFrame = true;
2864 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2865 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2866 // Do nothing, we'll validate it later.
2867 } else if (Value == "-defsym" || Value == "--defsym") {
2868 if (A->getNumValues() != 2) {
2869 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2870 break;
2871 }
2872 const char *S = A->getValue(1);
2873 auto Pair = StringRef(S).split('=');
2874 auto Sym = Pair.first;
2875 auto SVal = Pair.second;
2876
2877 if (Sym.empty() || SVal.empty()) {
2878 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2879 break;
2880 }
2881 int64_t IVal;
2882 if (SVal.getAsInteger(0, IVal)) {
2883 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2884 break;
2885 }
2886 CmdArgs.push_back("--defsym");
2887 TakeNextArg = true;
2888 } else if (Value == "-fdebug-compilation-dir") {
2889 CmdArgs.push_back("-fdebug-compilation-dir");
2890 TakeNextArg = true;
2891 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2892 // The flag is a -Wa / -Xassembler argument and Options doesn't
2893 // parse the argument, so this isn't automatically aliased to
2894 // -fdebug-compilation-dir (without '=') here.
2895 CmdArgs.push_back("-fdebug-compilation-dir");
2896 CmdArgs.push_back(Value.data());
2897 } else if (Value == "--version") {
2898 D.PrintVersion(C, llvm::outs());
2899 } else {
2900 D.Diag(diag::err_drv_unsupported_option_argument)
2901 << A->getSpelling() << Value;
2902 }
2903 }
2904 }
2905 if (ImplicitIt.size())
2906 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2907 if (Crel) {
2908 if (!ExperimentalCrel)
2909 D.Diag(diag::err_drv_experimental_crel);
2910 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2911 CmdArgs.push_back("--crel");
2912 } else {
2913 D.Diag(diag::err_drv_unsupported_opt_for_target)
2914 << "-Wa,--crel" << D.getTargetTriple();
2915 }
2916 }
2917 if (!RelocSectionSym.empty()) {
2918 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2919 RelocSectionSym != "none")
2920 D.Diag(diag::err_drv_invalid_value)
2921 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2922 << RelocSectionSym;
2923 else if (Triple.isOSBinFormatELF())
2924 CmdArgs.push_back(
2925 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2926 else
2927 D.Diag(diag::err_drv_unsupported_opt_for_target)
2928 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2929 }
2930 if (SFrame) {
2931 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2932 if (!ExperimentalSFrame)
2933 D.Diag(diag::err_drv_experimental_sframe);
2934 else
2935 CmdArgs.push_back("--gsframe");
2936 } else {
2937 D.Diag(diag::err_drv_unsupported_opt_for_target)
2938 << "-Wa,--gsframe" << D.getTargetTriple();
2939 }
2940 }
2941 if (ImplicitMapSyms)
2942 CmdArgs.push_back("-mmapsyms=implicit");
2943 if (Msa)
2944 CmdArgs.push_back("-mmsa");
2945 if (!UseRelaxRelocations)
2946 CmdArgs.push_back("-mrelax-relocations=no");
2947 if (UseNoExecStack)
2948 CmdArgs.push_back("-mnoexecstack");
2949 if (MipsTargetFeature != nullptr) {
2950 CmdArgs.push_back("-target-feature");
2951 CmdArgs.push_back(MipsTargetFeature);
2952 }
2953
2954 for (const char *Feature : SparcTargetFeatures) {
2955 CmdArgs.push_back("-target-feature");
2956 CmdArgs.push_back(Feature);
2957 }
2958
2959 // forward -fembed-bitcode to assmebler
2960 if (C.getDriver().embedBitcodeEnabled() ||
2961 C.getDriver().embedBitcodeMarkerOnly())
2962 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2963
2964 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2965 CmdArgs.push_back("-as-secure-log-file");
2966 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2967 }
2968}
2969
2970static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2971 bool OFastEnabled, const ArgList &Args,
2972 ArgStringList &CmdArgs,
2973 const JobAction &JA) {
2974 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2975 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2976 llvm::StringLiteral("SLEEF")};
2977 bool NoMathErrnoWasImpliedByVecLib = false;
2978 const Arg *VecLibArg = nullptr;
2979 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2980 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2981
2982 // Handle various floating point optimization flags, mapping them to the
2983 // appropriate LLVM code generation flags. This is complicated by several
2984 // "umbrella" flags, so we do this by stepping through the flags incrementally
2985 // adjusting what we think is enabled/disabled, then at the end setting the
2986 // LLVM flags based on the final state.
2987 bool HonorINFs = true;
2988 bool HonorNaNs = true;
2989 bool ApproxFunc = false;
2990 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2991 bool MathErrno = TC.IsMathErrnoDefault();
2992 bool AssociativeMath = false;
2993 bool ReciprocalMath = false;
2994 bool SignedZeros = true;
2995 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2996 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2997 // overriden by ffp-exception-behavior?
2998 bool RoundingFPMath = false;
2999 // -ffp-model values: strict, fast, precise
3000 StringRef FPModel = "";
3001 // -ffp-exception-behavior options: strict, maytrap, ignore
3002 StringRef FPExceptionBehavior = "";
3003 // -ffp-eval-method options: double, extended, source
3004 StringRef FPEvalMethod = "";
3005 llvm::DenormalMode DenormalFPMath =
3006 TC.getDefaultDenormalModeForType(Args, JA);
3007 llvm::DenormalMode DenormalFP32Math =
3008 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
3009
3010 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3011 // If one wasn't given by the user, don't pass it here.
3012 StringRef FPContract;
3013 StringRef LastSeenFfpContractOption;
3014 StringRef LastFpContractOverrideOption;
3015 bool SeenUnsafeMathModeOption = false;
3018 FPContract = "on";
3019 bool StrictFPModel = false;
3020 StringRef Float16ExcessPrecision = "";
3021 StringRef BFloat16ExcessPrecision = "";
3023 std::string ComplexRangeStr;
3024 StringRef LastComplexRangeOption;
3025
3026 // Lambda to set fast-math options. This is also used by -ffp-model=fast
3027 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
3028 if (Aggressive) {
3029 HonorINFs = false;
3030 HonorNaNs = false;
3032 LastComplexRangeOption, Range);
3033 } else {
3034 HonorINFs = true;
3035 HonorNaNs = true;
3036 setComplexRange(D, CallerOption,
3038 LastComplexRangeOption, Range);
3039 }
3040 MathErrno = false;
3041 AssociativeMath = true;
3042 ReciprocalMath = true;
3043 ApproxFunc = true;
3044 SignedZeros = false;
3045 TrappingMath = false;
3046 RoundingFPMath = false;
3047 FPExceptionBehavior = "";
3048 FPContract = "fast";
3049 SeenUnsafeMathModeOption = true;
3050 };
3051
3052 // Lambda to consolidate common handling for fp-contract
3053 auto restoreFPContractState = [&]() {
3054 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3055 // For other targets, if the state has been changed by one of the
3056 // unsafe-math umbrella options a subsequent -fno-fast-math or
3057 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3058 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3059 // option. If we have not seen an unsafe-math option or -ffp-contract,
3060 // we leave the FPContract state unchanged.
3063 if (LastSeenFfpContractOption != "")
3064 FPContract = LastSeenFfpContractOption;
3065 else if (SeenUnsafeMathModeOption)
3066 FPContract = "on";
3067 }
3068 // In this case, we're reverting to the last explicit fp-contract option
3069 // or the platform default
3070 LastFpContractOverrideOption = "";
3071 };
3072
3073 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3074 CmdArgs.push_back("-mlimit-float-precision");
3075 CmdArgs.push_back(A->getValue());
3076 }
3077
3078 for (const Arg *A : Args) {
3079 llvm::scope_exit CheckMathErrnoForVecLib(
3080 [&, MathErrnoBeforeArg = MathErrno] {
3081 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3082 ArgThatEnabledMathErrnoAfterVecLib = A;
3083 });
3084
3085 switch (A->getOption().getID()) {
3086 // If this isn't an FP option skip the claim below
3087 default: continue;
3088
3089 case options::OPT_fcx_limited_range:
3090 setComplexRange(D, A->getSpelling(),
3092 LastComplexRangeOption, Range);
3093 break;
3094 case options::OPT_fno_cx_limited_range:
3095 setComplexRange(D, A->getSpelling(),
3097 LastComplexRangeOption, Range);
3098 break;
3099 case options::OPT_fcx_fortran_rules:
3100 setComplexRange(D, A->getSpelling(),
3102 LastComplexRangeOption, Range);
3103 break;
3104 case options::OPT_fno_cx_fortran_rules:
3105 setComplexRange(D, A->getSpelling(),
3107 LastComplexRangeOption, Range);
3108 break;
3109 case options::OPT_fcomplex_arithmetic_EQ: {
3111 StringRef Val = A->getValue();
3112 if (Val == "full")
3114 else if (Val == "improved")
3116 else if (Val == "promoted")
3118 else if (Val == "basic")
3120 else {
3121 D.Diag(diag::err_drv_unsupported_option_argument)
3122 << A->getSpelling() << Val;
3123 break;
3124 }
3125 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3126 LastComplexRangeOption, Range);
3127 break;
3128 }
3129 case options::OPT_ffp_model_EQ: {
3130 // If -ffp-model= is seen, reset to fno-fast-math
3131 HonorINFs = true;
3132 HonorNaNs = true;
3133 ApproxFunc = false;
3134 // Turning *off* -ffast-math restores the toolchain default.
3135 MathErrno = TC.IsMathErrnoDefault();
3136 AssociativeMath = false;
3137 ReciprocalMath = false;
3138 SignedZeros = true;
3139
3140 StringRef Val = A->getValue();
3141 if (OFastEnabled && Val != "aggressive") {
3142 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3143 D.Diag(clang::diag::warn_drv_overriding_option)
3144 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3145 break;
3146 }
3147 StrictFPModel = false;
3148 if (!FPModel.empty() && FPModel != Val)
3149 D.Diag(clang::diag::warn_drv_overriding_option)
3150 << Args.MakeArgString("-ffp-model=" + FPModel)
3151 << Args.MakeArgString("-ffp-model=" + Val);
3152 if (Val == "fast") {
3153 FPModel = Val;
3154 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3155 // applyFastMath sets fp-contract="fast"
3156 LastFpContractOverrideOption = "-ffp-model=fast";
3157 } else if (Val == "aggressive") {
3158 FPModel = Val;
3159 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3160 // applyFastMath sets fp-contract="fast"
3161 LastFpContractOverrideOption = "-ffp-model=aggressive";
3162 } else if (Val == "precise") {
3163 FPModel = Val;
3164 FPContract = "on";
3165 LastFpContractOverrideOption = "-ffp-model=precise";
3166 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3168 LastComplexRangeOption, Range);
3169 } else if (Val == "strict") {
3170 StrictFPModel = true;
3171 FPExceptionBehavior = "strict";
3172 FPModel = Val;
3173 FPContract = "off";
3174 LastFpContractOverrideOption = "-ffp-model=strict";
3175 TrappingMath = true;
3176 RoundingFPMath = true;
3177 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3179 LastComplexRangeOption, Range);
3180 } else
3181 D.Diag(diag::err_drv_unsupported_option_argument)
3182 << A->getSpelling() << Val;
3183 break;
3184 }
3185
3186 // Options controlling individual features
3187 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3188 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3189 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3190 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3191 case options::OPT_fapprox_func: ApproxFunc = true; break;
3192 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3193 case options::OPT_fmath_errno: MathErrno = true; break;
3194 case options::OPT_fno_math_errno: MathErrno = false; break;
3195 case options::OPT_fassociative_math: AssociativeMath = true; break;
3196 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3197 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3198 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3199 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3200 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3201 case options::OPT_ftrapping_math:
3202 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3203 FPExceptionBehavior != "strict")
3204 // Warn that previous value of option is overridden.
3205 D.Diag(clang::diag::warn_drv_overriding_option)
3206 << Args.MakeArgString("-ffp-exception-behavior=" +
3207 FPExceptionBehavior)
3208 << "-ftrapping-math";
3209 TrappingMath = true;
3210 TrappingMathPresent = true;
3211 FPExceptionBehavior = "strict";
3212 break;
3213 case options::OPT_fveclib:
3214 VecLibArg = A;
3215 NoMathErrnoWasImpliedByVecLib =
3216 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3217 if (NoMathErrnoWasImpliedByVecLib)
3218 MathErrno = false;
3219 break;
3220 case options::OPT_fno_trapping_math:
3221 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3222 FPExceptionBehavior != "ignore")
3223 // Warn that previous value of option is overridden.
3224 D.Diag(clang::diag::warn_drv_overriding_option)
3225 << Args.MakeArgString("-ffp-exception-behavior=" +
3226 FPExceptionBehavior)
3227 << "-fno-trapping-math";
3228 TrappingMath = false;
3229 TrappingMathPresent = true;
3230 FPExceptionBehavior = "ignore";
3231 break;
3232
3233 case options::OPT_frounding_math:
3234 RoundingFPMath = true;
3235 break;
3236
3237 case options::OPT_fno_rounding_math:
3238 RoundingFPMath = false;
3239 break;
3240
3241 case options::OPT_fdenormal_fp_math_EQ:
3242 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3243 DenormalFP32Math = DenormalFPMath;
3244 if (!DenormalFPMath.isValid()) {
3245 D.Diag(diag::err_drv_invalid_value)
3246 << A->getAsString(Args) << A->getValue();
3247 }
3248 break;
3249
3250 case options::OPT_fdenormal_fp_math_f32_EQ:
3251 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3252 if (!DenormalFP32Math.isValid()) {
3253 D.Diag(diag::err_drv_invalid_value)
3254 << A->getAsString(Args) << A->getValue();
3255 }
3256 break;
3257
3258 // Validate and pass through -ffp-contract option.
3259 case options::OPT_ffp_contract: {
3260 StringRef Val = A->getValue();
3261 if (Val == "fast" || Val == "on" || Val == "off" ||
3262 Val == "fast-honor-pragmas") {
3263 if (Val != FPContract && LastFpContractOverrideOption != "") {
3264 D.Diag(clang::diag::warn_drv_overriding_option)
3265 << LastFpContractOverrideOption
3266 << Args.MakeArgString("-ffp-contract=" + Val);
3267 }
3268
3269 FPContract = Val;
3270 LastSeenFfpContractOption = Val;
3271 LastFpContractOverrideOption = "";
3272 } else
3273 D.Diag(diag::err_drv_unsupported_option_argument)
3274 << A->getSpelling() << Val;
3275 break;
3276 }
3277
3278 // Validate and pass through -ffp-exception-behavior option.
3279 case options::OPT_ffp_exception_behavior_EQ: {
3280 StringRef Val = A->getValue();
3281 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3282 FPExceptionBehavior != Val)
3283 // Warn that previous value of option is overridden.
3284 D.Diag(clang::diag::warn_drv_overriding_option)
3285 << Args.MakeArgString("-ffp-exception-behavior=" +
3286 FPExceptionBehavior)
3287 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3288 TrappingMath = TrappingMathPresent = false;
3289 if (Val == "ignore" || Val == "maytrap")
3290 FPExceptionBehavior = Val;
3291 else if (Val == "strict") {
3292 FPExceptionBehavior = Val;
3293 TrappingMath = TrappingMathPresent = true;
3294 } else
3295 D.Diag(diag::err_drv_unsupported_option_argument)
3296 << A->getSpelling() << Val;
3297 break;
3298 }
3299
3300 // Validate and pass through -ffp-eval-method option.
3301 case options::OPT_ffp_eval_method_EQ: {
3302 StringRef Val = A->getValue();
3303 if (Val == "double" || Val == "extended" || Val == "source")
3304 FPEvalMethod = Val;
3305 else
3306 D.Diag(diag::err_drv_unsupported_option_argument)
3307 << A->getSpelling() << Val;
3308 break;
3309 }
3310
3311 case options::OPT_fexcess_precision_EQ: {
3312 StringRef Val = A->getValue();
3313 const llvm::Triple::ArchType Arch = TC.getArch();
3314 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3315 if (Val == "standard" || Val == "fast")
3316 Float16ExcessPrecision = Val;
3317 // To make it GCC compatible, allow the value of "16" which
3318 // means disable excess precision, the same meaning than clang's
3319 // equivalent value "none".
3320 else if (Val == "16")
3321 Float16ExcessPrecision = "none";
3322 else
3323 D.Diag(diag::err_drv_unsupported_option_argument)
3324 << A->getSpelling() << Val;
3325 } else {
3326 if (!(Val == "standard" || Val == "fast"))
3327 D.Diag(diag::err_drv_unsupported_option_argument)
3328 << A->getSpelling() << Val;
3329 }
3330 BFloat16ExcessPrecision = Float16ExcessPrecision;
3331 break;
3332 }
3333 case options::OPT_ffinite_math_only:
3334 HonorINFs = false;
3335 HonorNaNs = false;
3336 break;
3337 case options::OPT_fno_finite_math_only:
3338 HonorINFs = true;
3339 HonorNaNs = true;
3340 break;
3341
3342 case options::OPT_funsafe_math_optimizations:
3343 AssociativeMath = true;
3344 ReciprocalMath = true;
3345 SignedZeros = false;
3346 ApproxFunc = true;
3347 TrappingMath = false;
3348 FPExceptionBehavior = "";
3349 FPContract = "fast";
3350 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3351 SeenUnsafeMathModeOption = true;
3352 break;
3353 case options::OPT_fno_unsafe_math_optimizations:
3354 AssociativeMath = false;
3355 ReciprocalMath = false;
3356 SignedZeros = true;
3357 ApproxFunc = false;
3358 restoreFPContractState();
3359 break;
3360
3361 case options::OPT_cl_fast_relaxed_math:
3362 applyFastMath(true, A->getSpelling());
3363 break;
3364
3365 case options::OPT_Ofast:
3366 // If -Ofast is the optimization level, then -ffast-math should be enabled
3367 if (!OFastEnabled)
3368 continue;
3369 [[fallthrough]];
3370 case options::OPT_ffast_math:
3371 applyFastMath(true, A->getSpelling());
3372 if (A->getOption().getID() == options::OPT_Ofast)
3373 LastFpContractOverrideOption = "-Ofast";
3374 else
3375 LastFpContractOverrideOption = "-ffast-math";
3376 break;
3377 case options::OPT_fno_fast_math:
3378 HonorINFs = true;
3379 HonorNaNs = true;
3380 // Turning on -ffast-math (with either flag) removes the need for
3381 // MathErrno. However, turning *off* -ffast-math merely restores the
3382 // toolchain default (which may be false).
3383 MathErrno = TC.IsMathErrnoDefault();
3384 AssociativeMath = false;
3385 ReciprocalMath = false;
3386 ApproxFunc = false;
3387 SignedZeros = true;
3388 restoreFPContractState();
3390 setComplexRange(D, A->getSpelling(),
3392 LastComplexRangeOption, Range);
3393 else
3395 LastComplexRangeOption = "";
3396 LastFpContractOverrideOption = "";
3397 break;
3398 } // End switch (A->getOption().getID())
3399
3400 // The StrictFPModel local variable is needed to report warnings
3401 // in the way we intend. If -ffp-model=strict has been used, we
3402 // want to report a warning for the next option encountered that
3403 // takes us out of the settings described by fp-model=strict, but
3404 // we don't want to continue issuing warnings for other conflicting
3405 // options after that.
3406 if (StrictFPModel) {
3407 // If -ffp-model=strict has been specified on command line but
3408 // subsequent options conflict then emit warning diagnostic.
3409 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3410 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3411 FPContract == "off")
3412 // OK: Current Arg doesn't conflict with -ffp-model=strict
3413 ;
3414 else {
3415 StrictFPModel = false;
3416 FPModel = "";
3417 // The warning for -ffp-contract would have been reported by the
3418 // OPT_ffp_contract_EQ handler above. A special check here is needed
3419 // to avoid duplicating the warning.
3420 auto RHS = (A->getNumValues() == 0)
3421 ? A->getSpelling()
3422 : Args.MakeArgString(A->getSpelling() + A->getValue());
3423 if (A->getSpelling() != "-ffp-contract=") {
3424 if (RHS != "-ffp-model=strict")
3425 D.Diag(clang::diag::warn_drv_overriding_option)
3426 << "-ffp-model=strict" << RHS;
3427 }
3428 }
3429 }
3430
3431 // If we handled this option claim it
3432 A->claim();
3433 }
3434
3435 if (!HonorINFs)
3436 CmdArgs.push_back("-menable-no-infs");
3437
3438 if (!HonorNaNs)
3439 CmdArgs.push_back("-menable-no-nans");
3440
3441 if (ApproxFunc)
3442 CmdArgs.push_back("-fapprox-func");
3443
3444 if (MathErrno) {
3445 CmdArgs.push_back("-fmath-errno");
3446 if (NoMathErrnoWasImpliedByVecLib)
3447 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3448 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3449 << VecLibArg->getAsString(Args);
3450 }
3451
3452 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3453 !TrappingMath)
3454 CmdArgs.push_back("-funsafe-math-optimizations");
3455
3456 if (!SignedZeros)
3457 CmdArgs.push_back("-fno-signed-zeros");
3458
3459 if (AssociativeMath && !SignedZeros && !TrappingMath)
3460 CmdArgs.push_back("-mreassociate");
3461
3462 if (ReciprocalMath)
3463 CmdArgs.push_back("-freciprocal-math");
3464
3465 if (TrappingMath) {
3466 // FP Exception Behavior is also set to strict
3467 assert(FPExceptionBehavior == "strict");
3468 }
3469
3470 // The default is IEEE.
3471 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3472 llvm::SmallString<64> DenormFlag;
3473 llvm::raw_svector_ostream ArgStr(DenormFlag);
3474 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3475 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3476 }
3477
3478 // Add f32 specific denormal mode flag if it's different.
3479 if (DenormalFP32Math != DenormalFPMath) {
3480 llvm::SmallString<64> DenormFlag;
3481 llvm::raw_svector_ostream ArgStr(DenormFlag);
3482 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3483 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3484 }
3485
3486 if (!FPContract.empty())
3487 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3488
3489 if (RoundingFPMath)
3490 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3491 else
3492 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3493
3494 if (!FPExceptionBehavior.empty())
3495 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3496 FPExceptionBehavior));
3497
3498 if (!FPEvalMethod.empty())
3499 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3500
3501 if (!Float16ExcessPrecision.empty())
3502 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3503 Float16ExcessPrecision));
3504 if (!BFloat16ExcessPrecision.empty())
3505 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3506 BFloat16ExcessPrecision));
3507
3508 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3509 if (!Recip.empty())
3510 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3511
3512 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3513 // individual features enabled by -ffast-math instead of the option itself as
3514 // that's consistent with gcc's behaviour.
3515 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3516 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3517 CmdArgs.push_back("-ffast-math");
3518
3519 // Handle __FINITE_MATH_ONLY__ similarly.
3520 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3521 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3522 // -menable-no-nans are set by the user.
3523 bool shouldAddFiniteMathOnly = false;
3524 if (!HonorINFs && !HonorNaNs) {
3525 shouldAddFiniteMathOnly = true;
3526 } else {
3527 bool InfValues = true;
3528 bool NanValues = true;
3529 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3530 StringRef ArgValue = Arg->getValue();
3531 if (ArgValue == "-menable-no-nans")
3532 NanValues = false;
3533 else if (ArgValue == "-menable-no-infs")
3534 InfValues = false;
3535 }
3536 if (!NanValues && !InfValues)
3537 shouldAddFiniteMathOnly = true;
3538 }
3539 if (shouldAddFiniteMathOnly) {
3540 CmdArgs.push_back("-ffinite-math-only");
3541 }
3542 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3543 CmdArgs.push_back("-mfpmath");
3544 CmdArgs.push_back(A->getValue());
3545 }
3546
3547 // Disable a codegen optimization for floating-point casts.
3548 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3549 options::OPT_fstrict_float_cast_overflow, false))
3550 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3551
3553 ComplexRangeStr = renderComplexRangeOption(Range);
3554 if (!ComplexRangeStr.empty()) {
3555 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3556 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3557 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3558 complexRangeKindToStr(Range)));
3559 }
3560 if (Args.hasArg(options::OPT_fcx_limited_range))
3561 CmdArgs.push_back("-fcx-limited-range");
3562 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3563 CmdArgs.push_back("-fcx-fortran-rules");
3564 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3565 CmdArgs.push_back("-fno-cx-limited-range");
3566 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3567 CmdArgs.push_back("-fno-cx-fortran-rules");
3568}
3569
3570static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3571 const llvm::Triple &Triple,
3572 const InputInfo &Input) {
3573 // Add default argument set.
3574 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3575 CmdArgs.push_back("-analyzer-checker=core");
3576 CmdArgs.push_back("-analyzer-checker=apiModeling");
3577
3578 if (!Triple.isWindowsMSVCEnvironment()) {
3579 CmdArgs.push_back("-analyzer-checker=unix");
3580 } else {
3581 // Enable "unix" checkers that also work on Windows.
3582 CmdArgs.push_back("-analyzer-checker=unix.API");
3583 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3584 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3585 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3586 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3587 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3588 }
3589
3590 // Disable some unix checkers for PS4/PS5.
3591 if (Triple.isPS()) {
3592 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3593 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3594 }
3595
3596 if (Triple.isOSDarwin()) {
3597 CmdArgs.push_back("-analyzer-checker=osx");
3598 CmdArgs.push_back(
3599 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3600 }
3601 else if (Triple.isOSFuchsia())
3602 CmdArgs.push_back("-analyzer-checker=fuchsia");
3603
3604 CmdArgs.push_back("-analyzer-checker=deadcode");
3605
3606 if (types::isCXX(Input.getType()))
3607 CmdArgs.push_back("-analyzer-checker=cplusplus");
3608
3609 if (!Triple.isPS()) {
3610 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3611 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3612 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3613 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3614 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3615 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3616 }
3617
3618 // Default nullability checks.
3619 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3620 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3621 }
3622
3623 // Set the output format. The default is plist, for (lame) historical reasons.
3624 CmdArgs.push_back("-analyzer-output");
3625 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3626 CmdArgs.push_back(A->getValue());
3627 else
3628 CmdArgs.push_back("plist");
3629
3630 // Disable the presentation of standard compiler warnings when using
3631 // --analyze. We only want to show static analyzer diagnostics or frontend
3632 // errors.
3633 CmdArgs.push_back("-w");
3634
3635 // Add -Xanalyzer arguments when running as analyzer.
3636 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3637}
3638
3639static bool isValidSymbolName(StringRef S) {
3640 if (S.empty())
3641 return false;
3642
3643 if (std::isdigit(S[0]))
3644 return false;
3645
3646 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3647}
3648
3649static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3650 const ArgList &Args, ArgStringList &CmdArgs,
3651 bool KernelOrKext) {
3652 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3653
3654 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3655 // doesn't even have a stack!
3656 if (EffectiveTriple.isNVPTX())
3657 return;
3658
3659 // -stack-protector=0 is default.
3661 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3662 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3663
3664 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3665 options::OPT_fstack_protector_all,
3666 options::OPT_fstack_protector_strong,
3667 options::OPT_fstack_protector)) {
3668 if (A->getOption().matches(options::OPT_fstack_protector))
3669 StackProtectorLevel =
3670 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3671 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3672 StackProtectorLevel = LangOptions::SSPStrong;
3673 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3674 StackProtectorLevel = LangOptions::SSPReq;
3675
3676 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3677 D.Diag(diag::warn_drv_unsupported_option_for_target)
3678 << A->getSpelling() << EffectiveTriple.getTriple();
3679 StackProtectorLevel = DefaultStackProtectorLevel;
3680 }
3681 } else {
3682 StackProtectorLevel = DefaultStackProtectorLevel;
3683 }
3684
3685 if (StackProtectorLevel) {
3686 CmdArgs.push_back("-stack-protector");
3687 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3688 }
3689
3690 // --param ssp-buffer-size=
3691 for (const Arg *A : Args.filtered(options::OPT__param)) {
3692 StringRef Str(A->getValue());
3693 if (Str.consume_front("ssp-buffer-size=")) {
3694 if (StackProtectorLevel) {
3695 CmdArgs.push_back("-stack-protector-buffer-size");
3696 // FIXME: Verify the argument is a valid integer.
3697 CmdArgs.push_back(Args.MakeArgString(Str));
3698 }
3699 A->claim();
3700 }
3701 }
3702
3703 const std::string &TripleStr = EffectiveTriple.getTriple();
3704 StringRef GuardValue;
3705 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3706 GuardValue = A->getValue();
3707 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3708 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3709 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3710 !EffectiveTriple.isSystemZ())
3711 D.Diag(diag::err_drv_unsupported_opt_for_target)
3712 << A->getAsString(Args) << TripleStr;
3713 // z/OS only supports the tls mode.
3714 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3715 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3716 << A->getOption().getName() << GuardValue << "tls";
3717 return;
3718 }
3719 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3720 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3721 GuardValue != "tls" && GuardValue != "global") {
3722 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3723 << A->getOption().getName() << GuardValue << "tls global";
3724 return;
3725 }
3726 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3727 GuardValue == "tls") {
3728 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3729 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3730 << A->getAsString(Args);
3731 return;
3732 }
3733 // Check whether the target subarch supports the hardware TLS register
3734 if (!arm::isHardTPSupported(EffectiveTriple)) {
3735 D.Diag(diag::err_target_unsupported_tp_hard)
3736 << EffectiveTriple.getArchName();
3737 return;
3738 }
3739 // Check whether the user asked for something other than -mtp=cp15
3740 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3741 StringRef Value = A->getValue();
3742 if (Value != "cp15") {
3743 D.Diag(diag::err_drv_argument_not_allowed_with)
3744 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3745 return;
3746 }
3747 }
3748 CmdArgs.push_back("-target-feature");
3749 CmdArgs.push_back("+read-tp-tpidruro");
3750 }
3751 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3752 GuardValue != "global") {
3753 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3754 << A->getOption().getName() << GuardValue << "sysreg global";
3755 return;
3756 }
3757 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3758 if (GuardValue != "tls" && GuardValue != "global") {
3759 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3760 << A->getOption().getName() << GuardValue << "tls global";
3761 return;
3762 }
3763 if (GuardValue == "tls") {
3764 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3765 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3766 << A->getAsString(Args);
3767 return;
3768 }
3769 }
3770 }
3771 A->render(Args, CmdArgs);
3772 }
3773
3774 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3775 StringRef Value = A->getValue();
3776 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3777 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3778 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3779 D.Diag(diag::err_drv_unsupported_opt_for_target)
3780 << A->getAsString(Args) << TripleStr;
3781 int Offset;
3782 if (Value.getAsInteger(10, Offset)) {
3783 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3784 return;
3785 }
3786 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3787 (Offset < 0 || Offset > 0xfffff)) {
3788 D.Diag(diag::err_drv_invalid_int_value)
3789 << A->getOption().getName() << Value;
3790 return;
3791 }
3792 A->render(Args, CmdArgs);
3793 }
3794
3795 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3796 StringRef Value = A->getValue();
3797 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3798 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3799 D.Diag(diag::err_drv_unsupported_opt_for_target)
3800 << A->getAsString(Args) << TripleStr;
3801 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3802 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3803 << A->getOption().getName() << Value << "fs gs";
3804 return;
3805 }
3806 if (EffectiveTriple.isAArch64() &&
3807 llvm::StringSwitch<bool>(Value)
3808 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3809 "tpidr_el2", "far_el1", "far_el2"},
3810 false)
3811 .Default(true)) {
3812 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3813 << A->getOption().getName() << Value
3814 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3815 return;
3816 }
3817 if (EffectiveTriple.isRISCV() && Value != "tp") {
3818 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3819 << A->getOption().getName() << Value << "tp";
3820 return;
3821 }
3822 if (EffectiveTriple.isPPC64() && Value != "r13") {
3823 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3824 << A->getOption().getName() << Value << "r13";
3825 return;
3826 }
3827 if (EffectiveTriple.isPPC32() && Value != "r2") {
3828 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3829 << A->getOption().getName() << Value << "r2";
3830 return;
3831 }
3832 A->render(Args, CmdArgs);
3833 }
3834
3835 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3836 StringRef Value = A->getValue();
3837 if (!isValidSymbolName(Value)) {
3838 D.Diag(diag::err_drv_argument_only_allowed_with)
3839 << A->getOption().getName() << "legal symbol name";
3840 return;
3841 }
3842 A->render(Args, CmdArgs);
3843 }
3844
3845 if (Arg *A =
3846 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3847 if (!EffectiveTriple.isAArch64())
3848 D.Diag(diag::err_drv_unsupported_opt_for_target)
3849 << A->getAsString(Args) << TripleStr;
3850 StringRef Value = A->getValue();
3851 unsigned Width;
3852 if (Value.getAsInteger(10, Width)) {
3853 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3854 return;
3855 }
3856 if (Width != 4 && Width != 8) {
3857 D.Diag(diag::err_drv_invalid_int_value)
3858 << A->getOption().getName() << Value;
3859 }
3860 }
3861 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3862 if (!EffectiveTriple.isSystemZ()) {
3863 D.Diag(diag::err_drv_unsupported_opt_for_target)
3864 << A->getAsString(Args) << TripleStr;
3865 return;
3866 }
3867 if (GuardValue != "global") {
3868 D.Diag(diag::err_drv_argument_only_allowed_with)
3869 << "-mstack-protector-guard-record"
3870 << "-mstack-protector-guard=global";
3871 return;
3872 }
3873 A->render(Args, CmdArgs);
3874 }
3875}
3876
3877static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3878 ArgStringList &CmdArgs) {
3879 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3880
3881 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3882 !EffectiveTriple.isOSFuchsia())
3883 return;
3884
3885 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3886 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3887 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3888 return;
3889
3890 if (Args.hasFlag(options::OPT_fstack_clash_protection,
3891 options::OPT_fno_stack_clash_protection,
3892 EffectiveTriple.isAndroid()))
3893 CmdArgs.push_back("-fstack-clash-protection");
3894}
3895
3897 const ToolChain &TC,
3898 const ArgList &Args,
3899 ArgStringList &CmdArgs) {
3900 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3901 StringRef TrivialAutoVarInit = "";
3902
3903 for (const Arg *A : Args) {
3904 switch (A->getOption().getID()) {
3905 default:
3906 continue;
3907 case options::OPT_ftrivial_auto_var_init: {
3908 A->claim();
3909 StringRef Val = A->getValue();
3910 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3911 TrivialAutoVarInit = Val;
3912 else
3913 D.Diag(diag::err_drv_unsupported_option_argument)
3914 << A->getSpelling() << Val;
3915 break;
3916 }
3917 }
3918 }
3919
3920 if (TrivialAutoVarInit.empty())
3921 switch (DefaultTrivialAutoVarInit) {
3923 break;
3925 TrivialAutoVarInit = "pattern";
3926 break;
3928 TrivialAutoVarInit = "zero";
3929 break;
3930 }
3931
3932 if (!TrivialAutoVarInit.empty()) {
3933 CmdArgs.push_back(
3934 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3935 }
3936
3937 if (Arg *A =
3938 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3939 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3940 StringRef(
3941 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3942 "uninitialized")
3943 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3944 A->claim();
3945 StringRef Val = A->getValue();
3946 if (std::stoi(Val.str()) <= 0)
3947 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3948 CmdArgs.push_back(
3949 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3950 }
3951
3952 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3953 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3954 StringRef(
3955 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3956 "uninitialized")
3957 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3958 A->claim();
3959 StringRef Val = A->getValue();
3960 if (std::stoi(Val.str()) <= 0)
3961 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3962 CmdArgs.push_back(
3963 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3964 }
3965}
3966
3967static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3968 types::ID InputType) {
3969 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3970 // for denormal flushing handling based on the target.
3971 const unsigned ForwardedArguments[] = {
3972 options::OPT_cl_opt_disable,
3973 options::OPT_cl_strict_aliasing,
3974 options::OPT_cl_single_precision_constant,
3975 options::OPT_cl_finite_math_only,
3976 options::OPT_cl_kernel_arg_info,
3977 options::OPT_cl_unsafe_math_optimizations,
3978 options::OPT_cl_fast_relaxed_math,
3979 options::OPT_cl_mad_enable,
3980 options::OPT_cl_no_signed_zeros,
3981 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3982 options::OPT_cl_uniform_work_group_size
3983 };
3984
3985 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3986 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3987 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3988 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3989 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3990 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3991 }
3992
3993 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3994 CmdArgs.push_back("-menable-no-infs");
3995 CmdArgs.push_back("-menable-no-nans");
3996 }
3997
3998 for (const auto &Arg : ForwardedArguments)
3999 if (const auto *A = Args.getLastArg(Arg))
4000 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
4001
4002 // Only add the default headers if we are compiling OpenCL sources.
4003 if ((types::isOpenCL(InputType) ||
4004 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
4005 !Args.hasArg(options::OPT_cl_no_stdinc)) {
4006 CmdArgs.push_back("-finclude-default-header");
4007 CmdArgs.push_back("-fdeclare-opencl-builtins");
4008 }
4009}
4010
4011static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
4012 ArgStringList &CmdArgs, types::ID InputType) {
4013 const unsigned ForwardedArguments[] = {
4014 options::OPT_hlsl_all_resources_bound,
4015 options::OPT_dxil_validator_version,
4016 options::OPT_res_may_alias,
4017 options::OPT_D,
4018 options::OPT_I,
4019 options::OPT_O,
4020 options::OPT_emit_llvm,
4021 options::OPT_emit_obj,
4022 options::OPT_disable_llvm_passes,
4023 options::OPT_fnative_half_type,
4024 options::OPT_fnative_int16_type,
4025 options::OPT_fmatrix_memory_layout_EQ,
4026 options::OPT_hlsl_entrypoint,
4027 options::OPT_fdx_rootsignature_define,
4028 options::OPT_fdx_rootsignature_version,
4029 options::OPT_fdx_semantic_signature_packing_mode_EQ,
4030 options::OPT_fhlsl_spv_use_unknown_image_format,
4031 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
4032 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
4033 options::OPT_fhlsl_spv_preserve_interface,
4034 options::OPT_fhlsl_spv_support_nonzero_base_instance};
4035 if (!types::isHLSL(InputType))
4036 return;
4037 for (const auto &Arg : ForwardedArguments)
4038 if (const auto *A = Args.getLastArg(Arg))
4039 A->renderAsInput(Args, CmdArgs);
4040 // Add the default headers if dxc_no_stdinc is not set.
4041 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
4042 !Args.hasArg(options::OPT_nostdinc))
4043 CmdArgs.push_back("-finclude-default-header");
4044
4045 if (Args.hasArg(options::OPT_dxc_Zss)) {
4046 if (Args.hasArg(options::OPT_dxc_Zsb))
4047 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
4048 CmdArgs.push_back("-mllvm");
4049 CmdArgs.push_back("-dx-Zss");
4050 }
4051 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
4052 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
4053 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
4054 CmdArgs.push_back("-mllvm");
4055 CmdArgs.push_back("--dx-source-in-debug-module");
4056 }
4057 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
4058 CmdArgs.push_back("-mllvm");
4059 CmdArgs.push_back("--dx-strip-debug");
4060 }
4061 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
4062 CmdArgs.push_back("-mllvm");
4063 CmdArgs.push_back("--dx-pdb-in-private");
4064 }
4065 CmdArgs.push_back("-load-bool-from-mem=nonzero");
4066}
4067
4068static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4069 ArgStringList &CmdArgs, types::ID InputType) {
4070 if (!Args.hasArg(options::OPT_fopenacc))
4071 return;
4072
4073 CmdArgs.push_back("-fopenacc");
4074}
4075
4076static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4077 const ArgList &Args, ArgStringList &CmdArgs) {
4078 // -fbuiltin is default unless -mkernel is used.
4079 bool UseBuiltins =
4080 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4081 !Args.hasArg(options::OPT_mkernel));
4082 if (!UseBuiltins)
4083 CmdArgs.push_back("-fno-builtin");
4084
4085 // -ffreestanding implies -fno-builtin.
4086 if (Args.hasArg(options::OPT_ffreestanding))
4087 UseBuiltins = false;
4088
4089 // Process the -fno-builtin-* options.
4090 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4091 A->claim();
4092
4093 // If -fno-builtin is specified, then there's no need to pass the option to
4094 // the frontend.
4095 if (UseBuiltins)
4096 A->render(Args, CmdArgs);
4097 }
4098}
4099
4101 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4102 Twine Path{Str};
4103 Path.toVector(Result);
4104 return Path.getSingleStringRef() != "";
4105 }
4106 if (llvm::sys::path::cache_directory(Result)) {
4107 llvm::sys::path::append(Result, "clang");
4108 llvm::sys::path::append(Result, "ModuleCache");
4109 return true;
4110 }
4111 return false;
4112}
4113
4116 const char *BaseInput) {
4117 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4118 return StringRef(ModuleOutputEQ->getValue());
4119
4120 SmallString<256> OutputPath;
4121 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4122 FinalOutput && Args.hasArg(options::OPT_c))
4123 OutputPath = FinalOutput->getValue();
4124 else {
4125 llvm::sys::fs::current_path(OutputPath);
4126 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4127 }
4128
4129 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4130 llvm::sys::path::replace_extension(OutputPath, Extension);
4131 return OutputPath;
4132}
4133
4135 const ArgList &Args, const InputInfo &Input,
4136 const InputInfo &Output, bool HaveStd20,
4137 ArgStringList &CmdArgs) {
4138 const bool IsCXX = types::isCXX(Input.getType());
4139 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4140 bool HaveModules = HaveStdCXXModules;
4141
4142 // -fmodules enables the use of precompiled modules (off by default).
4143 // Users can pass -fno-cxx-modules to turn off modules support for
4144 // C++/Objective-C++ programs.
4145 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4146 options::OPT_fno_cxx_modules, true);
4147 bool HaveClangModules = false;
4148 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4149 if (AllowedInCXX || !IsCXX) {
4150 CmdArgs.push_back("-fmodules");
4151 HaveClangModules = true;
4152 }
4153 }
4154
4155 HaveModules |= HaveClangModules;
4156
4157 if (HaveModules && !AllowedInCXX)
4158 CmdArgs.push_back("-fno-cxx-modules");
4159
4160 // -fmodule-maps enables implicit reading of module map files. By default,
4161 // this is enabled if we are using Clang's flavor of precompiled modules.
4162 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4163 options::OPT_fno_implicit_module_maps, HaveClangModules))
4164 CmdArgs.push_back("-fimplicit-module-maps");
4165
4166 // -fmodules-decluse checks that modules used are declared so (off by default)
4167 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4168 options::OPT_fno_modules_decluse);
4169
4170 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4171 // all #included headers are part of modules.
4172 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4173 options::OPT_fno_modules_strict_decluse, false))
4174 CmdArgs.push_back("-fmodules-strict-decluse");
4175
4176 Args.addOptInFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4177 options::OPT_fno_modulemap_allow_subdirectory_search);
4178
4179 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4180 bool ImplicitModules = false;
4181 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4182 options::OPT_fno_implicit_modules, HaveClangModules)) {
4183 if (HaveModules)
4184 CmdArgs.push_back("-fno-implicit-modules");
4185 } else if (HaveModules) {
4186 ImplicitModules = true;
4187 // -fmodule-cache-path specifies where our implicitly-built module files
4188 // should be written.
4189 SmallString<128> Path;
4190 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4191 Path = A->getValue();
4192
4193 bool HasPath = true;
4194 if (C.isForDiagnostics()) {
4195 // When generating crash reports, we want to emit the modules along with
4196 // the reproduction sources, so we ignore any provided module path.
4197 Path = Output.getFilename();
4198 llvm::sys::path::replace_extension(Path, ".cache");
4199 llvm::sys::path::append(Path, "modules");
4200 } else if (Path.empty()) {
4201 // No module path was provided: use the default.
4202 HasPath = Driver::getDefaultModuleCachePath(Path);
4203 }
4204
4205 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4206 // That being said, that failure is unlikely and not caching is harmless.
4207 if (HasPath) {
4208 const char Arg[] = "-fmodules-cache-path=";
4209 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4210 CmdArgs.push_back(Args.MakeArgString(Path));
4211 }
4212
4213 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4214 }
4215
4216 if (HaveModules) {
4217 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4218 options::OPT_fno_prebuilt_implicit_modules, false))
4219 CmdArgs.push_back("-fprebuilt-implicit-modules");
4220 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4221 options::OPT_fno_modules_validate_input_files_content,
4222 false))
4223 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4224 }
4225
4226 // -fmodule-name specifies the module that is currently being built (or
4227 // used for header checking by -fmodule-maps).
4228 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4229
4230 // -fmodule-map-file can be used to specify files containing module
4231 // definitions.
4232 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4233
4234 // -fbuiltin-module-map can be used to load the clang
4235 // builtin headers modulemap file.
4236 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4237 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4238 llvm::sys::path::append(BuiltinModuleMap, "include");
4239 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4240 if (llvm::sys::fs::exists(BuiltinModuleMap))
4241 CmdArgs.push_back(
4242 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4243 }
4244
4245 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4246 // names to precompiled module files (the module is loaded only if used).
4247 // The -fmodule-file=<file> form can be used to unconditionally load
4248 // precompiled module files (whether used or not).
4249 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4250 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4251
4252 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4253 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4254 CmdArgs.push_back(Args.MakeArgString(
4255 std::string("-fprebuilt-module-path=") + A->getValue()));
4256 A->claim();
4257 }
4258 } else
4259 Args.ClaimAllArgs(options::OPT_fmodule_file);
4260
4261 // When building modules and generating crashdumps, we need to dump a module
4262 // dependency VFS alongside the output.
4263 if (HaveClangModules && C.isForDiagnostics()) {
4264 SmallString<128> VFSDir(Output.getFilename());
4265 llvm::sys::path::replace_extension(VFSDir, ".cache");
4266 // Add the cache directory as a temp so the crash diagnostics pick it up.
4267 C.addTempFile(Args.MakeArgString(VFSDir));
4268
4269 llvm::sys::path::append(VFSDir, "vfs");
4270 CmdArgs.push_back("-module-dependency-dir");
4271 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4272 }
4273
4274 if (HaveClangModules)
4275 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4276
4277 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4278 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_search_path);
4279 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4280 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4281
4282 if (HaveClangModules) {
4283 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4284
4285 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4286 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4287 D.Diag(diag::err_drv_argument_not_allowed_with)
4288 << A->getAsString(Args) << "-fbuild-session-timestamp";
4289
4290 llvm::sys::fs::file_status Status;
4291 if (llvm::sys::fs::status(A->getValue(), Status))
4292 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4293 CmdArgs.push_back(Args.MakeArgString(
4294 "-fbuild-session-timestamp=" +
4295 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4296 Status.getLastModificationTime().time_since_epoch())
4297 .count())));
4298 }
4299
4300 if (Args.getLastArg(
4301 options::OPT_fmodules_validate_once_per_build_session)) {
4302 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4303 options::OPT_fbuild_session_file))
4304 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4305
4306 Args.AddLastArg(CmdArgs,
4307 options::OPT_fmodules_validate_once_per_build_session);
4308 }
4309
4310 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4311 options::OPT_fno_modules_validate_system_headers,
4312 ImplicitModules))
4313 CmdArgs.push_back("-fmodules-validate-system-headers");
4314
4315 if (Args.hasFlag(options::OPT_fmodules_validate_directory_dependencies,
4316 options::OPT_fno_modules_validate_directory_dependencies,
4317 false))
4318 CmdArgs.push_back("-fmodules-validate-directory-dependencies");
4319
4320 Args.AddLastArg(CmdArgs,
4321 options::OPT_fmodules_disable_diagnostic_validation);
4322 } else {
4323 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4324 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4325 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4326 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4327 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4328 Args.ClaimAllArgs(options::OPT_fmodules_validate_directory_dependencies);
4329 Args.ClaimAllArgs(options::OPT_fno_modules_validate_directory_dependencies);
4330 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4331 }
4332
4333 // FIXME: We provisionally don't check ODR violations for decls in the global
4334 // module fragment.
4335 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4336
4337 if (Input.getType() == driver::types::TY_CXXModule ||
4338 Input.getType() == driver::types::TY_PP_CXXModule) {
4339 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4340 CmdArgs.push_back("-fmodules-reduced-bmi");
4341
4342 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4343 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4344 else if (!(Args.hasArg(options::OPT__precompile) ||
4345 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4346 Args.hasArg(options::OPT_fmodule_output))
4347 // If --precompile is specified, we will always generate a module file if
4348 // we're compiling an importable module unit. This is fine even if the
4349 // compilation process won't reach the point of generating the module file
4350 // (e.g., in the preprocessing mode), since the attached flag
4351 // '-fmodule-output' is useless.
4352 //
4353 // But if '--precompile' is specified, it might be annoying to always
4354 // generate the module file as '--precompile' will generate the module
4355 // file anyway.
4356 CmdArgs.push_back(Args.MakeArgString(
4357 "-fmodule-output=" +
4359 }
4360
4361 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4362 Args.hasArg(options::OPT__precompile) &&
4363 (!Args.hasArg(options::OPT_o) ||
4364 Args.getLastArg(options::OPT_o)->getValue() ==
4366 D.Diag(diag::err_drv_reduced_module_output_overrided);
4367 }
4368
4369 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4370 // other translation units than module units. This is more user friendly to
4371 // allow end uers to enable this feature without asking for help from build
4372 // systems.
4373 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4374 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4375
4376 // We need to include the case the input file is a module file here.
4377 // Since the default compilation model for C++ module interface unit will
4378 // create temporary module file and compile the temporary module file
4379 // to get the object file. Then the `-fmodule-output` flag will be
4380 // brought to the second compilation process. So we have to claim it for
4381 // the case too.
4382 if (Input.getType() == driver::types::TY_CXXModule ||
4383 Input.getType() == driver::types::TY_PP_CXXModule ||
4384 Input.getType() == driver::types::TY_ModuleFile) {
4385 Args.ClaimAllArgs(options::OPT_fmodule_output);
4386 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4387 }
4388
4389 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4390 CmdArgs.push_back("-fmodules-embed-all-files");
4391
4392 return HaveModules;
4393}
4394
4395static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4396 ArgStringList &CmdArgs) {
4397 // -fsigned-char is default.
4398 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4399 options::OPT_fno_signed_char,
4400 options::OPT_funsigned_char,
4401 options::OPT_fno_unsigned_char)) {
4402 if (A->getOption().matches(options::OPT_funsigned_char) ||
4403 A->getOption().matches(options::OPT_fno_signed_char)) {
4404 CmdArgs.push_back("-fno-signed-char");
4405 }
4406 } else if (!isSignedCharDefault(T)) {
4407 CmdArgs.push_back("-fno-signed-char");
4408 }
4409
4410 // The default depends on the language standard.
4411 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4412
4413 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4414 options::OPT_fno_short_wchar)) {
4415 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4416 CmdArgs.push_back("-fwchar-type=short");
4417 CmdArgs.push_back("-fno-signed-wchar");
4418 } else {
4419 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4420 CmdArgs.push_back("-fwchar-type=int");
4421 if (T.isOSzOS() ||
4422 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4423 CmdArgs.push_back("-fno-signed-wchar");
4424 else
4425 CmdArgs.push_back("-fsigned-wchar");
4426 }
4427 } else if (T.isOSzOS())
4428 CmdArgs.push_back("-fno-signed-wchar");
4429}
4430
4431static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4432 const llvm::Triple &T, const ArgList &Args,
4433 ObjCRuntime &Runtime, bool InferCovariantReturns,
4434 const InputInfo &Input, ArgStringList &CmdArgs) {
4435 const llvm::Triple::ArchType Arch = TC.getArch();
4436
4437 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4438 // is the default. Except for deployment target of 10.5, next runtime is
4439 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4440 if (Runtime.isNonFragile()) {
4441 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4442 options::OPT_fno_objc_legacy_dispatch,
4444 if (TC.UseObjCMixedDispatch())
4445 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4446 else
4447 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4448 }
4449 }
4450
4451 // Forward -fobjc-direct-precondition-thunk to cc1
4452 // Defaults to false and needs explict turn on for now
4453 // TODO: switch to default true and needs explict turn off in the future.
4454 // TODO: add support for other runtimes
4455 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4456 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4457 if (Runtime.isNeXTFamily()) {
4458 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4459 } else {
4460 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4461 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4462 }
4463 }
4464
4465 if (types::isObjC(Input.getType())) {
4466 // Pass down -fobjc-msgsend-selector-stubs if present.
4467 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4468 options::OPT_fno_objc_msgsend_selector_stubs, false))
4469 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4470
4471 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4472 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4473 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4474 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4475 }
4476
4477 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4478 // to do Array/Dictionary subscripting by default.
4479 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4480 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4481 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4482
4483 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4484 // NOTE: This logic is duplicated in ToolChains.cpp.
4485 if (isObjCAutoRefCount(Args)) {
4486 TC.CheckObjCARC();
4487
4488 CmdArgs.push_back("-fobjc-arc");
4489
4490 // FIXME: It seems like this entire block, and several around it should be
4491 // wrapped in isObjC, but for now we just use it here as this is where it
4492 // was being used previously.
4493 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4495 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4496 else
4497 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4498 }
4499
4500 // Allow the user to enable full exceptions code emission.
4501 // We default off for Objective-C, on for Objective-C++.
4502 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4503 options::OPT_fno_objc_arc_exceptions,
4504 /*Default=*/types::isCXX(Input.getType())))
4505 CmdArgs.push_back("-fobjc-arc-exceptions");
4506 }
4507
4508 // Silence warning for full exception code emission options when explicitly
4509 // set to use no ARC.
4510 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4511 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4512 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4513 }
4514
4515 // Allow the user to control whether messages can be converted to runtime
4516 // functions.
4517 if (types::isObjC(Input.getType())) {
4518 auto *Arg = Args.getLastArg(
4519 options::OPT_fobjc_convert_messages_to_runtime_calls,
4520 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4521 if (Arg &&
4522 Arg->getOption().matches(
4523 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4524 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4525 }
4526
4527 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4528 // rewriter.
4529 if (InferCovariantReturns)
4530 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4531
4532 // Pass down -fobjc-weak or -fno-objc-weak if present.
4533 if (types::isObjC(Input.getType())) {
4534 auto WeakArg =
4535 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4536 if (!WeakArg) {
4537 // nothing to do
4538 } else if (!Runtime.allowsWeak()) {
4539 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4540 D.Diag(diag::err_objc_weak_unsupported);
4541 } else {
4542 WeakArg->render(Args, CmdArgs);
4543 }
4544 }
4545
4546 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4547 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4548
4549 // Forward constant literal flags to cc1.
4550 if (types::isObjC(Input.getType())) {
4551 bool EnableConstantLiterals =
4552 Args.hasFlag(options::OPT_fobjc_constant_literals,
4553 options::OPT_fno_objc_constant_literals,
4554 /*default=*/true) &&
4555 Runtime.hasConstantLiteralClasses();
4556 if (EnableConstantLiterals)
4557 CmdArgs.push_back("-fobjc-constant-literals");
4558 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4559 options::OPT_fno_constant_nsnumber_literals,
4560 /*default=*/true) &&
4561 EnableConstantLiterals)
4562 CmdArgs.push_back("-fconstant-nsnumber-literals");
4563 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4564 options::OPT_fno_constant_nsarray_literals,
4565 /*default=*/true) &&
4566 EnableConstantLiterals)
4567 CmdArgs.push_back("-fconstant-nsarray-literals");
4568 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4569 options::OPT_fno_constant_nsdictionary_literals,
4570 /*default=*/true) &&
4571 EnableConstantLiterals)
4572 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4573 }
4574}
4575
4576static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4577 ArgStringList &CmdArgs) {
4578 bool CaretDefault = true;
4579 bool ColumnDefault = true;
4580
4581 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4582 options::OPT__SLASH_diagnostics_column,
4583 options::OPT__SLASH_diagnostics_caret)) {
4584 switch (A->getOption().getID()) {
4585 case options::OPT__SLASH_diagnostics_caret:
4586 CaretDefault = true;
4587 ColumnDefault = true;
4588 break;
4589 case options::OPT__SLASH_diagnostics_column:
4590 CaretDefault = false;
4591 ColumnDefault = true;
4592 break;
4593 case options::OPT__SLASH_diagnostics_classic:
4594 CaretDefault = false;
4595 ColumnDefault = false;
4596 break;
4597 }
4598 }
4599
4600 // -fcaret-diagnostics is default.
4601 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4602 options::OPT_fno_caret_diagnostics, CaretDefault))
4603 CmdArgs.push_back("-fno-caret-diagnostics");
4604
4605 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4606 options::OPT_fno_diagnostics_fixit_info);
4607 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4608 options::OPT_fno_diagnostics_show_option);
4609
4610 if (const Arg *A =
4611 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4612 CmdArgs.push_back("-fdiagnostics-show-category");
4613 CmdArgs.push_back(A->getValue());
4614 }
4615
4616 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4617 options::OPT_fno_diagnostics_show_hotness);
4618
4619 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_safety_c,
4620 options::OPT_fno_lifetime_safety_c);
4621
4622 if (const Arg *A =
4623 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4624 std::string Opt =
4625 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4626 CmdArgs.push_back(Args.MakeArgString(Opt));
4627 }
4628
4629 if (const Arg *A =
4630 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4631 std::string Opt =
4632 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4633 CmdArgs.push_back(Args.MakeArgString(Opt));
4634 }
4635
4636 if (const Arg *A =
4637 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4638 options::OPT_fno_diagnostics_show_inlining_chain)) {
4639 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4640 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4641 else
4642 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4643 }
4644
4645 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4646 CmdArgs.push_back("-fdiagnostics-format");
4647 CmdArgs.push_back(A->getValue());
4648 if (StringRef(A->getValue()) == "sarif" ||
4649 StringRef(A->getValue()) == "SARIF")
4650 D.Diag(diag::warn_drv_sarif_format_unstable);
4651 }
4652
4653 if (const Arg *A = Args.getLastArg(
4654 options::OPT_fdiagnostics_show_note_include_stack,
4655 options::OPT_fno_diagnostics_show_note_include_stack)) {
4656 const Option &O = A->getOption();
4657 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4658 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4659 else
4660 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4661 }
4662
4663 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4664
4665 if (Args.hasArg(options::OPT_fansi_escape_codes))
4666 CmdArgs.push_back("-fansi-escape-codes");
4667
4668 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4669 options::OPT_fno_show_source_location);
4670
4671 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4672 options::OPT_fno_diagnostics_show_line_numbers);
4673
4674 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4675 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4676
4677 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4678 ColumnDefault))
4679 CmdArgs.push_back("-fno-show-column");
4680
4681 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4682 options::OPT_fno_spell_checking);
4683
4684 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4685}
4686
4687static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4688 const ArgList &Args, ArgStringList &CmdArgs,
4689 unsigned DwarfVersion) {
4690 auto *DwarfFormatArg =
4691 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4692 if (!DwarfFormatArg)
4693 return;
4694
4695 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4696 if (DwarfVersion < 3)
4697 D.Diag(diag::err_drv_argument_only_allowed_with)
4698 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4699 else if (!T.isArch64Bit())
4700 D.Diag(diag::err_drv_argument_only_allowed_with)
4701 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4702 else if (!T.isOSBinFormatELF())
4703 D.Diag(diag::err_drv_argument_only_allowed_with)
4704 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4705 }
4706
4707 DwarfFormatArg->render(Args, CmdArgs);
4708}
4709
4710static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4711 const ArgList &Args) {
4712 bool NeedsSimpleTemplateNames =
4713 Args.hasFlag(options::OPT_gsimple_template_names,
4714 options::OPT_gno_simple_template_names,
4716 if (!NeedsSimpleTemplateNames)
4717 return false;
4718
4719 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4720 if (!checkDebugInfoOption(A, Args, D, TC))
4721 return false;
4722
4723 return true;
4724}
4725
4726static void
4727renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4728 const ArgList &Args, types::ID InputType,
4729 ArgStringList &CmdArgs, const InputInfo &Output,
4730 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4731 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4732 bool IRInput = isLLVMIR(InputType);
4733 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4734 !isHIP(InputType) && !isObjC(InputType) &&
4735 !isOpenCL(InputType);
4736
4737 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4738
4739 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4740 options::OPT_fno_debug_record_sysroot, true))
4741 CmdArgs.push_back("-fno-debug-record-sysroot");
4742
4743 // The 'g' groups options involve a somewhat intricate sequence of decisions
4744 // about what to pass from the driver to the frontend, but by the time they
4745 // reach cc1 they've been factored into three well-defined orthogonal choices:
4746 // * what level of debug info to generate
4747 // * what dwarf version to write
4748 // * what debugger tuning to use
4749 // This avoids having to monkey around further in cc1 other than to disable
4750 // codeview if not running in a Windows environment. Perhaps even that
4751 // decision should be made in the driver as well though.
4752 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4753
4754 bool SplitDWARFInlining =
4755 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4756 options::OPT_fno_split_dwarf_inlining, false);
4757
4758 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4759 // object file generation and no IR generation, -gN should not be needed. So
4760 // allow -gsplit-dwarf with either -gN or IR input.
4761 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4762 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4763 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4764 D.Diag(diag::err_drv_unsupported_opt_for_target)
4765 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4766 << TC.getTripleString();
4767 return;
4768 }
4769 Arg *SplitDWARFArg;
4770 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4771 if (DwarfFission != DwarfFissionKind::None &&
4772 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4773 DwarfFission = DwarfFissionKind::None;
4774 SplitDWARFInlining = false;
4775 }
4776 }
4777 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4778 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4779
4780 // If the last option explicitly specified a debug-info level, use it.
4781 if (checkDebugInfoOption(A, Args, D, TC) &&
4782 A->getOption().matches(options::OPT_gN_Group)) {
4783 DebugInfoKind = debugLevelToInfoKind(*A);
4784 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4785 // complicated if you've disabled inline info in the skeleton CUs
4786 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4787 // line-tables-only, so let those compose naturally in that case.
4788 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4789 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4790 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4791 SplitDWARFInlining))
4792 DwarfFission = DwarfFissionKind::None;
4793 }
4794 }
4795
4796 // If a debugger tuning argument appeared, remember it.
4797 bool HasDebuggerTuning = false;
4798 if (const Arg *A =
4799 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4800 HasDebuggerTuning = true;
4801 if (checkDebugInfoOption(A, Args, D, TC)) {
4802 if (A->getOption().matches(options::OPT_glldb))
4803 DebuggerTuning = llvm::DebuggerKind::LLDB;
4804 else if (A->getOption().matches(options::OPT_gsce))
4805 DebuggerTuning = llvm::DebuggerKind::SCE;
4806 else if (A->getOption().matches(options::OPT_gdbx))
4807 DebuggerTuning = llvm::DebuggerKind::DBX;
4808 else
4809 DebuggerTuning = llvm::DebuggerKind::GDB;
4810 }
4811 }
4812
4813 // If a -gdwarf argument appeared, remember it.
4814 bool EmitDwarf = false;
4815 if (const Arg *A = getDwarfNArg(Args))
4816 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4817
4818 bool EmitCodeView = false;
4819 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4820 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4821
4822 // If the user asked for debug info but did not explicitly specify -gcodeview
4823 // or -gdwarf, ask the toolchain for the default format.
4824 if (!EmitCodeView && !EmitDwarf &&
4825 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4826 switch (TC.getDefaultDebugFormat()) {
4827 case llvm::codegenoptions::DIF_CodeView:
4828 EmitCodeView = true;
4829 break;
4830 case llvm::codegenoptions::DIF_DWARF:
4831 EmitDwarf = true;
4832 break;
4833 }
4834 }
4835
4836 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4837 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4838 // be lower than what the user wanted.
4839 if (EmitDwarf) {
4840 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4841 // Clamp effective DWARF version to the max supported by the toolchain.
4842 EffectiveDWARFVersion =
4843 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4844 } else {
4845 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4846 }
4847
4848 // -gline-directives-only supported only for the DWARF debug info.
4849 if (RequestedDWARFVersion == 0 &&
4850 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4851 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4852
4853 // strict DWARF is set to false by default. But for DBX, we need it to be set
4854 // as true by default.
4855 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4856 (void)checkDebugInfoOption(A, Args, D, TC);
4857 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4858 DebuggerTuning == llvm::DebuggerKind::DBX))
4859 CmdArgs.push_back("-gstrict-dwarf");
4860
4861 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4862 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4863
4864 // Column info is included by default for everything except SCE and
4865 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4866 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4867 // practice, however, the Microsoft debuggers don't handle missing end columns
4868 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4869 // it's better not to include any column info.
4870 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4871 (void)checkDebugInfoOption(A, Args, D, TC);
4872 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4873 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4874 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4875 DebuggerTuning != llvm::DebuggerKind::DBX)))
4876 CmdArgs.push_back("-gno-column-info");
4877
4878 if (!Args.hasFlag(options::OPT_gcall_site_info,
4879 options::OPT_gno_call_site_info, true))
4880 CmdArgs.push_back("-gno-call-site-info");
4881
4882 // FIXME: Move backend command line options to the module.
4883 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4884 // If -gline-tables-only or -gline-directives-only is the last option it
4885 // wins.
4886 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4887 TC)) {
4888 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4889 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4890 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4891 CmdArgs.push_back("-dwarf-ext-refs");
4892 CmdArgs.push_back("-fmodule-format=obj");
4893 }
4894 }
4895 }
4896
4897 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4898 CmdArgs.push_back("-fsplit-dwarf-inlining");
4899
4900 // After we've dealt with all combinations of things that could
4901 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4902 // figure out if we need to "upgrade" it to standalone debug info.
4903 // We parse these two '-f' options whether or not they will be used,
4904 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4905 bool NeedFullDebug = Args.hasFlag(
4906 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4907 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4909 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4910 (void)checkDebugInfoOption(A, Args, D, TC);
4911
4912 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4913 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4914 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4915 options::OPT_feliminate_unused_debug_types, false))
4916 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4917 else if (NeedFullDebug)
4918 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4919 }
4920
4921 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4922 false)) {
4923 // Source embedding is a vendor extension to DWARF v5. By now we have
4924 // checked if a DWARF version was stated explicitly, and have otherwise
4925 // fallen back to the target default, so if this is still not at least 5
4926 // we emit an error.
4927 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4928 if (RequestedDWARFVersion < 5)
4929 D.Diag(diag::err_drv_argument_only_allowed_with)
4930 << A->getAsString(Args) << "-gdwarf-5";
4931 else if (EffectiveDWARFVersion < 5)
4932 // The toolchain has reduced allowed dwarf version, so we can't enable
4933 // -gembed-source.
4934 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4935 << A->getAsString(Args) << TC.getTripleString() << 5
4936 << EffectiveDWARFVersion;
4937 else if (checkDebugInfoOption(A, Args, D, TC))
4938 CmdArgs.push_back("-gembed-source");
4939 }
4940
4941 // Enable Key Instructions by default if we're emitting DWARF, the language is
4942 // plain C or C++, and optimisations are enabled.
4943 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4944 bool KeyInstructionsOnByDefault =
4945 EmitDwarf && PlainCOrCXX && OptLevel &&
4946 !OptLevel->getOption().matches(options::OPT_O0);
4947 if (Args.hasFlag(options::OPT_gkey_instructions,
4948 options::OPT_gno_key_instructions,
4949 KeyInstructionsOnByDefault))
4950 CmdArgs.push_back("-gkey-instructions");
4951
4952 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4953 options::OPT_gno_structor_decl_linkage_names, true))
4954 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4955
4956 if (Args.hasFlag(options::OPT_fdynamic_debugging,
4957 options::OPT_fno_dynamic_debugging, false)) {
4958 // As this is an experimental feature we can afford to be strict about
4959 // supported configurations.
4960 // NOTE on adding target support, consider adding "tail-pad-to-size"
4961 // support in `llvm::prepareForDynamicDebugging`.
4962 if (!TC.getTriple().isX86())
4963 D.Diag(diag::err_drv_unsupported_opt_for_target)
4964 << Args.getLastArg(options::OPT_fdynamic_debugging)->getAsString(Args)
4965 << T.getTriple();
4966 if (IsUsingLTO)
4967 D.Diag(diag::err_drv_dyndbg_lto);
4968 if (DwarfFission != DwarfFissionKind::None)
4969 D.Diag(diag::err_drv_dyndbg_incompatible)
4970 << Args.getLastArg(options::OPT_gsplit_dwarf)->getAsString(Args);
4971 // There's no fundamental reason why IR input should be incompatible, but
4972 // it would add some complexity, and reducing the test matrix is valuable.
4973 if (IRInput)
4974 D.Diag(diag::err_drv_dyndbg_ir);
4975
4976 // Disable composition with sanitizers for now.
4977 if (auto *San = Args.getLastArg(options::OPT_fsanitize_EQ))
4978 D.Diag(diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4979
4980 if (!EmitDwarf)
4981 D.Diag(diag::warn_drv_dyndbg_req_debug);
4982 else
4983 CmdArgs.push_back("-fdynamic-debugging");
4984 }
4985
4986 if (EmitCodeView) {
4987 CmdArgs.push_back("-gcodeview");
4988
4989 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4990 options::OPT_gno_codeview_ghash);
4991
4992 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4993 options::OPT_gno_codeview_command_line);
4994 }
4995
4996 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4997 options::OPT_gno_inline_line_tables);
4998
4999 // When emitting remarks, we need at least debug lines in the output.
5000 if (willEmitRemarks(Args) &&
5001 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
5002 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
5003
5004 // Adjust the debug info kind for the given toolchain.
5005 TC.adjustDebugInfoKind(DebugInfoKind, Args);
5006
5007 // On AIX, the debugger tuning option can be omitted if it is not explicitly
5008 // set.
5009 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
5010 T.isOSAIX() && !HasDebuggerTuning
5011 ? llvm::DebuggerKind::Default
5012 : DebuggerTuning);
5013
5014 // -fdebug-macro turns on macro debug info generation.
5015 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
5016 false))
5017 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
5018 D, TC))
5019 CmdArgs.push_back("-debug-info-macro");
5020
5021 // -ggnu-pubnames turns on gnu style pubnames in the backend.
5022 const auto *PubnamesArg =
5023 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
5024 options::OPT_gpubnames, options::OPT_gno_pubnames);
5025 if (DwarfFission != DwarfFissionKind::None ||
5026 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
5027 const bool OptionSet =
5028 (PubnamesArg &&
5029 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
5030 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
5031 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
5032 (!PubnamesArg ||
5033 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
5034 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
5035 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
5036 options::OPT_gpubnames)
5037 ? "-gpubnames"
5038 : "-ggnu-pubnames");
5039 }
5040
5041 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
5042 if (getDebugSimpleTemplateNames(TC, D, Args)) {
5043 ForwardTemplateParams = true;
5044 CmdArgs.push_back("-gsimple-template-names=simple");
5045 }
5046
5047 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
5048 bool UseDebugTemplateAlias =
5049 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
5050 if (const auto *DebugTemplateAlias = Args.getLastArg(
5051 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
5052 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
5053 // asks for it we should let them have it (if the target supports it).
5054 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
5055 const auto &Opt = DebugTemplateAlias->getOption();
5056 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
5057 }
5058 }
5059 if (UseDebugTemplateAlias)
5060 CmdArgs.push_back("-gtemplate-alias");
5061
5062 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
5063 StringRef v = A->getValue();
5064 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
5065 }
5066
5067 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
5068 options::OPT_fno_debug_ranges_base_address);
5069
5070 // -gdwarf-aranges turns on the emission of the aranges section in the
5071 // backend.
5072 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
5073 A && checkDebugInfoOption(A, Args, D, TC)) {
5074 CmdArgs.push_back("-mllvm");
5075 CmdArgs.push_back("-generate-arange-section");
5076 }
5077
5078 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
5079 options::OPT_fno_force_dwarf_frame);
5080
5081 bool EnableTypeUnits = false;
5082 if (Args.hasFlag(options::OPT_fdebug_types_section,
5083 options::OPT_fno_debug_types_section, false)) {
5084 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5085 D.Diag(diag::err_drv_unsupported_opt_for_target)
5086 << Args.getLastArg(options::OPT_fdebug_types_section)
5087 ->getAsString(Args)
5088 << T.getTriple();
5089 } else if (checkDebugInfoOption(
5090 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
5091 TC)) {
5092 EnableTypeUnits = true;
5093 CmdArgs.push_back("-mllvm");
5094 CmdArgs.push_back("-generate-type-units");
5095 }
5096 }
5097
5098 if (const Arg *A =
5099 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
5100 options::OPT_gno_omit_unreferenced_methods))
5101 (void)checkDebugInfoOption(A, Args, D, TC);
5102 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
5103 options::OPT_gno_omit_unreferenced_methods, false) &&
5104 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5105 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5106 !EnableTypeUnits) {
5107 CmdArgs.push_back("-gomit-unreferenced-methods");
5108 }
5109
5110 // To avoid join/split of directory+filename, the integrated assembler prefers
5111 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5112 // form before DWARF v5.
5113 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5114 options::OPT_fno_dwarf_directory_asm,
5115 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5116 CmdArgs.push_back("-fno-dwarf-directory-asm");
5117
5118 // Decide how to render forward declarations of template instantiations.
5119 // SCE wants full descriptions, others just get them in the name.
5120 if (ForwardTemplateParams)
5121 CmdArgs.push_back("-debug-forward-template-params");
5122
5123 // Do we need to explicitly import anonymous namespaces into the parent
5124 // scope?
5125 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5126 CmdArgs.push_back("-dwarf-explicit-import");
5127
5128 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5129 if (useMachORelocatableDwarf(T, EffectiveDWARFVersion))
5130 CmdArgs.push_back("-grelocatable-dwarf");
5131 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5132
5133 // This controls whether or not we perform JustMyCode instrumentation.
5134 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5135 if (TC.getTriple().isOSBinFormatELF() ||
5136 TC.getTriple().isWindowsMSVCEnvironment()) {
5137 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5138 CmdArgs.push_back("-fjmc");
5139 else if (D.IsCLMode())
5140 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5141 << "'/Zi', '/Z7'";
5142 else
5143 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5144 << "-g";
5145 } else {
5146 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5147 }
5148 }
5149
5150 // Add in -fdebug-compilation-dir if necessary.
5151 const char *DebugCompilationDir =
5152 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5153
5154 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5155
5156 // Add the output path to the object file for CodeView debug infos.
5157 if (EmitCodeView && Output.isFilename())
5158 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5159 Output.getFilename());
5160}
5161
5162static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5163 ArgStringList &CmdArgs) {
5164 unsigned RTOptionID = options::OPT__SLASH_MT;
5165
5166 if (Args.hasArg(options::OPT__SLASH_LDd))
5167 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5168 // but defining _DEBUG is sticky.
5169 RTOptionID = options::OPT__SLASH_MTd;
5170
5171 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5172 RTOptionID = A->getOption().getID();
5173
5174 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5175 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5176 .Case("static", options::OPT__SLASH_MT)
5177 .Case("static_dbg", options::OPT__SLASH_MTd)
5178 .Case("dll", options::OPT__SLASH_MD)
5179 .Case("dll_dbg", options::OPT__SLASH_MDd)
5180 .Default(options::OPT__SLASH_MT);
5181 }
5182
5183 StringRef FlagForCRT;
5184 switch (RTOptionID) {
5185 case options::OPT__SLASH_MD:
5186 if (Args.hasArg(options::OPT__SLASH_LDd))
5187 CmdArgs.push_back("-D_DEBUG");
5188 CmdArgs.push_back("-D_MT");
5189 CmdArgs.push_back("-D_DLL");
5190 FlagForCRT = "--dependent-lib=msvcrt";
5191 break;
5192 case options::OPT__SLASH_MDd:
5193 CmdArgs.push_back("-D_DEBUG");
5194 CmdArgs.push_back("-D_MT");
5195 CmdArgs.push_back("-D_DLL");
5196 FlagForCRT = "--dependent-lib=msvcrtd";
5197 break;
5198 case options::OPT__SLASH_MT:
5199 if (Args.hasArg(options::OPT__SLASH_LDd))
5200 CmdArgs.push_back("-D_DEBUG");
5201 CmdArgs.push_back("-D_MT");
5202 CmdArgs.push_back("-flto-visibility-public-std");
5203 FlagForCRT = "--dependent-lib=libcmt";
5204 break;
5205 case options::OPT__SLASH_MTd:
5206 CmdArgs.push_back("-D_DEBUG");
5207 CmdArgs.push_back("-D_MT");
5208 CmdArgs.push_back("-flto-visibility-public-std");
5209 FlagForCRT = "--dependent-lib=libcmtd";
5210 break;
5211 default:
5212 llvm_unreachable("Unexpected option ID.");
5213 }
5214
5215 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5216 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5217 } else {
5218 CmdArgs.push_back(FlagForCRT.data());
5219
5220 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5221 // users want. The /Za flag to cl.exe turns this off, but it's not
5222 // implemented in clang.
5223 CmdArgs.push_back("--dependent-lib=oldnames");
5224 }
5225
5226 // SYCL: Add SYCL runtime library dependency
5227 // SYCL runtime is a required dependency similar to CRT, so we use
5228 // --dependent-lib to embed it in the object file metadata
5229 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5230 !Args.hasArg(options::OPT_nolibsycl) &&
5231 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5232
5233 // Determine debug vs release based on CRT flags
5234 bool IsDebugBuild = false;
5235
5236 // Check -fms-runtime-lib=dll_dbg
5237 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5238 StringRef RuntimeVal = A->getValue();
5239 if (RuntimeVal == "dll_dbg")
5240 IsDebugBuild = true;
5241 }
5242
5243 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5244 // overriding options (e.g., /MDd /MD -> /MD wins)
5245 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5246 if (A->getOption().matches(options::OPT__SLASH_MDd))
5247 IsDebugBuild = true;
5248 }
5249
5250 // Add appropriate SYCL runtime library dependency
5251 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5252 : "--dependent-lib=LLVMSYCL");
5253 }
5254
5255 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5256 // even if the file doesn't actually refer to any of the routines because
5257 // the CRT itself has incomplete dependency markings.
5258 if (TC.getTriple().isWindowsArm64EC())
5259 CmdArgs.push_back("--dependent-lib=softintrin");
5260}
5261
5263 const InputInfo &Output, const InputInfoList &Inputs,
5264 const ArgList &Args, const char *LinkingOutput) const {
5265 const auto &TC = getToolChain();
5266 const llvm::Triple &RawTriple = TC.getTriple();
5267 const llvm::Triple &Triple = TC.getEffectiveTriple();
5268 const std::string &TripleStr = Triple.getTriple();
5269
5270 bool KernelOrKext =
5271 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5272 const Driver &D = TC.getDriver();
5273 ArgStringList CmdArgs;
5274
5275 assert(Inputs.size() >= 1 && "Must have at least one input.");
5276 // CUDA/HIP compilation may have multiple inputs (source file + results of
5277 // device-side compilations). OpenMP device jobs also take the host IR as a
5278 // second input. Module precompilation accepts a list of header files to
5279 // include as part of the module. API extraction accepts a list of header
5280 // files whose API information is emitted in the output. All other jobs are
5281 // expected to have exactly one input. SYCL compilation only expects a
5282 // single input.
5283 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5284 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5285 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5286 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5287 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5288 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5289 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5290 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5291 bool UsesLLVMOffloading = Args.hasFlag(
5292 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
5293 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5295 bool IsHostOffloadingAction =
5298 (JA.isHostOffloading(C.getActiveOffloadKinds()));
5299
5300 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5301 bool IsRDCMode = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5302 /*Default=*/IsSYCL);
5303
5304 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5305 bool IsUsingLTO = LTOMode != LTOK_None;
5306
5307 // Extract API doesn't have a main input file, so invent a fake one as a
5308 // placeholder.
5309 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5310 "extract-api");
5311
5312 const InputInfo &Input =
5313 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5314
5315 InputInfoList ExtractAPIInputs;
5316 InputInfoList HostOffloadingInputs;
5317 const InputInfo *OpenMPDeviceInput = nullptr;
5318 for (const InputInfo &I : Inputs) {
5319 if (&I == &Input || I.getType() == types::TY_Nothing) {
5320 // This is the primary input or contains nothing.
5321 } else if (IsExtractAPI) {
5322 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5323 if (I.getType() != ExpectedInputType) {
5324 D.Diag(diag::err_drv_extract_api_wrong_kind)
5325 << I.getFilename() << types::getTypeName(I.getType())
5326 << types::getTypeName(ExpectedInputType);
5327 }
5328 ExtractAPIInputs.push_back(I);
5329 } else if (IsHostOffloadingAction) {
5330 HostOffloadingInputs.push_back(I);
5331 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5332 OpenMPDeviceInput = &I;
5333 } else {
5334 llvm_unreachable("unexpectedly given multiple inputs");
5335 }
5336 }
5337
5338 bool IsUEFI = RawTriple.isUEFI();
5339 bool IsIAMCU = RawTriple.isOSIAMCU();
5340
5341 // C++ is not supported for IAMCU.
5342 if (IsIAMCU && types::isCXX(Input.getType()))
5343 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5344
5345 // Invoke ourselves in -cc1 mode.
5346 //
5347 // FIXME: Implement custom jobs for internal actions.
5348 CmdArgs.push_back("-cc1");
5349
5350 // Add the "effective" target triple.
5351 CmdArgs.push_back("-triple");
5352 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5353
5354 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5355
5356 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5357 if (AuxTriple) {
5358 CmdArgs.push_back("-aux-triple");
5359 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5360
5361 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5362 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5363 // Windows), we need to pass Windows-specific flags to cc1.
5364 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5366 // Figure out the device side triple for the host-side compilation.
5367 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5368 ++I) {
5370 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5371 if (OffloadToolChains.first == OffloadToolChains.second)
5372 continue;
5373
5374 const llvm::Triple &DeviceAuxTriple =
5375 OffloadToolChains.first->second->getTriple();
5376 CmdArgs.push_back("-aux-triple");
5377 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5378 break;
5379 }
5380 }
5381
5382 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5383 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5384 Args.ClaimAllArgs(options::OPT_MJ);
5385 } else if (const Arg *GenCDBFragment =
5386 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5387 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5388 TripleStr, Output, Input, Args);
5389 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5390 }
5391
5392 if ((getToolChain().getTriple().isAMDGPU() ||
5393 (getToolChain().getTriple().isSPIRV() &&
5394 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5395 // Device side compilation printf
5396 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5397 CmdArgs.push_back(Args.MakeArgString(
5398 "-mprintf-kind=" +
5399 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5400 // Force compiler error on invalid conversion specifiers
5401 CmdArgs.push_back(
5402 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5403 }
5404 }
5405
5406 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5407 // We need to figure out which CUDA version we're compiling for, as that
5408 // determines how we load and launch GPU kernels.
5409 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5410 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5411 assert(CTC && "Expected valid CUDA Toolchain.");
5412 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5413 CmdArgs.push_back(Args.MakeArgString(
5414 Twine("-target-sdk-version=") +
5415 CudaVersionToString(CTC->CudaInstallation.version())));
5416 }
5417
5418 // Optimization level for CodeGen.
5419 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5420 if (A->getOption().matches(options::OPT_O4)) {
5421 CmdArgs.push_back("-O3");
5422 D.Diag(diag::warn_O4_is_O3);
5423 } else {
5424 A->render(Args, CmdArgs);
5425 }
5426 }
5427
5428 // Unconditionally claim the printf option now to avoid unused diagnostic.
5429 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5430 PF->claim();
5431
5432 if (IsSYCL) {
5433 if (IsSYCLDevice) {
5434 // We want to compile sycl kernels.
5435 CmdArgs.push_back("-fsycl-is-device");
5436
5437 // Set O2 optimization level by default
5438 if (!Args.getLastArg(options::OPT_O_Group))
5439 CmdArgs.push_back("-O2");
5440 } else {
5441 // Add any options that are needed specific to SYCL offload while
5442 // performing the host side compilation.
5443
5444 // Let the front-end host compilation flow know about SYCL offload
5445 // compilation.
5446 CmdArgs.push_back("-fsycl-is-host");
5447 }
5448
5449 // Set options for both host and device.
5450 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5451 if (SYCLStdArg) {
5452 SYCLStdArg->render(Args, CmdArgs);
5453 } else {
5454 // Ensure the default version in SYCL mode is 2020.
5455 CmdArgs.push_back("-sycl-std=2020");
5456 }
5457 }
5458
5459 if (Args.hasFlag(options::OPT_fclangir, options::OPT_fno_clangir, false))
5460 CmdArgs.push_back("-fclangir");
5461
5462 if (IsOpenMPDevice) {
5463 // We have to pass the triple of the host if compiling for an OpenMP device.
5464 const llvm::Triple &HostTriple =
5465 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5466 CmdArgs.push_back("-aux-triple");
5467 CmdArgs.push_back(HostTriple.str().c_str());
5468 }
5469
5470 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5471 Triple.getArch() == llvm::Triple::thumb)) {
5472 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5473 unsigned Version = 0;
5474 bool Failure =
5475 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5476 if (Failure || Version < 7)
5477 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5478 << TripleStr;
5479 }
5480
5481 // Push all default warning arguments that are specific to
5482 // the given target. These come before user provided warning options
5483 // are provided.
5484 TC.addClangWarningOptions(CmdArgs);
5485
5486 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5487 if (Triple.isSPIR() || Triple.isSPIRV())
5488 CmdArgs.push_back("-Wspir-compat");
5489
5490 // Select the appropriate action.
5491 RewriteKind rewriteKind = RK_None;
5492
5493 bool UnifiedLTO = false;
5494 if (IsUsingLTO) {
5495 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5496 options::OPT_fno_unified_lto, Triple.isPS());
5497 if (UnifiedLTO)
5498 CmdArgs.push_back("-funified-lto");
5499 }
5500
5501 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5502 CmdArgs.push_back("-fdefined-pointer-subtraction");
5503
5504 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5505 // it claims when not running an assembler. Otherwise, clang would emit
5506 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5507 // flags while debugging something. That'd be somewhat inconvenient, and it's
5508 // also inconsistent with most other flags -- we don't warn on
5509 // -ffunction-sections not being used in -E mode either for example, even
5510 // though it's not really used either.
5511 if (!isa<AssembleJobAction>(JA)) {
5512 // The args claimed here should match the args used in
5513 // CollectArgsForIntegratedAssembler().
5514 if (TC.useIntegratedAs()) {
5515 Args.ClaimAllArgs(options::OPT_mrelax_all);
5516 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5517 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5518 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5519 switch (C.getDefaultToolChain().getArch()) {
5520 case llvm::Triple::arm:
5521 case llvm::Triple::armeb:
5522 case llvm::Triple::thumb:
5523 case llvm::Triple::thumbeb:
5524 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5525 break;
5526 default:
5527 break;
5528 }
5529 }
5530 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5531 Args.ClaimAllArgs(options::OPT_Xassembler);
5532 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5533 }
5534
5535 bool IsAMDSPIRVForHIPDevice =
5536 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5537 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5538
5539 if (isa<AnalyzeJobAction>(JA)) {
5540 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5541 CmdArgs.push_back("-analyze");
5542 } else if (isa<PreprocessJobAction>(JA)) {
5543 if (Output.getType() == types::TY_Dependencies)
5544 CmdArgs.push_back("-Eonly");
5545 else {
5546 CmdArgs.push_back("-E");
5547 if (Args.hasArg(options::OPT_rewrite_objc) &&
5548 !Args.hasArg(options::OPT_g_Group))
5549 CmdArgs.push_back("-P");
5550 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5551 CmdArgs.push_back("-fdirectives-only");
5552 }
5553 } else if (isa<AssembleJobAction>(JA)) {
5554 CmdArgs.push_back("-emit-obj");
5555
5556 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5557
5558 // Also ignore explicit -force_cpusubtype_ALL option.
5559 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5560 } else if (isa<PrecompileJobAction>(JA)) {
5561 if (JA.getType() == types::TY_Nothing)
5562 CmdArgs.push_back("-fsyntax-only");
5563 else if (JA.getType() == types::TY_ModuleFile) {
5564 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5565 ((Input.getType() == types::TY_CXXStdModule ||
5566 Input.getType() == types::TY_PP_CXXStdModule) &&
5567 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5568 CmdArgs.push_back("-emit-reduced-module-interface");
5569 else
5570 CmdArgs.push_back("-emit-module-interface");
5571 } else if (JA.getType() == types::TY_HeaderUnit)
5572 CmdArgs.push_back("-emit-header-unit");
5573 else if (!Args.hasArg(options::OPT_ignore_pch))
5574 CmdArgs.push_back("-emit-pch");
5575 } else if (isa<VerifyPCHJobAction>(JA)) {
5576 CmdArgs.push_back("-verify-pch");
5577 } else if (isa<ExtractAPIJobAction>(JA)) {
5578 assert(JA.getType() == types::TY_API_INFO &&
5579 "Extract API actions must generate a API information.");
5580 CmdArgs.push_back("-extract-api");
5581
5582 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5583 PrettySGFArg->render(Args, CmdArgs);
5584
5585 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5586
5587 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5588 ProductNameArg->render(Args, CmdArgs);
5589 if (Arg *ExtractAPIIgnoresFileArg =
5590 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5591 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5592 if (Arg *EmitExtensionSymbolGraphs =
5593 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5594 if (!SymbolGraphDirArg)
5595 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5596
5597 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5598 }
5599 if (SymbolGraphDirArg)
5600 SymbolGraphDirArg->render(Args, CmdArgs);
5601 } else {
5602 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5603 "Invalid action for clang tool.");
5604 if (JA.getType() == types::TY_Nothing) {
5605 CmdArgs.push_back("-fsyntax-only");
5606 } else if (JA.getType() == types::TY_LLVM_IR ||
5607 JA.getType() == types::TY_LTO_IR) {
5608 CmdArgs.push_back("-emit-llvm");
5609 } else if (JA.getType() == types::TY_LLVM_BC ||
5610 JA.getType() == types::TY_LTO_BC) {
5611 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5612 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5613 Args.hasArg(options::OPT_emit_llvm)) {
5614 CmdArgs.push_back("-emit-llvm");
5615 } else {
5616 CmdArgs.push_back("-emit-llvm-bc");
5617 }
5618 } else if (JA.getType() == types::TY_IFS ||
5619 JA.getType() == types::TY_IFS_CPP) {
5620 StringRef ArgStr =
5621 Args.hasArg(options::OPT_interface_stub_version_EQ)
5622 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5623 : "ifs-v1";
5624 CmdArgs.push_back("-emit-interface-stubs");
5625 CmdArgs.push_back(
5626 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5627 } else if (JA.getType() == types::TY_PP_Asm) {
5628 CmdArgs.push_back("-S");
5629 } else if (JA.getType() == types::TY_AST) {
5630 if (!Args.hasArg(options::OPT_ignore_pch))
5631 CmdArgs.push_back("-emit-pch");
5632 } else if (JA.getType() == types::TY_ModuleFile) {
5633 CmdArgs.push_back("-module-file-info");
5634 } else if (JA.getType() == types::TY_RewrittenObjC) {
5635 CmdArgs.push_back("-rewrite-objc");
5636 rewriteKind = RK_NonFragile;
5637 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5638 CmdArgs.push_back("-rewrite-objc");
5639 rewriteKind = RK_Fragile;
5640 } else if (JA.getType() == types::TY_CIR) {
5641 CmdArgs.push_back("-emit-cir");
5642 } else if (JA.getType() == types::TY_CIRBC) {
5643 CmdArgs.push_back("-emit-cir-bc");
5644 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5645 CmdArgs.push_back("-emit-obj");
5646 } else {
5647 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5648 }
5649
5650 // Preserve use-list order by default when emitting bitcode, so that
5651 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5652 // same result as running passes here. For LTO, we don't need to preserve
5653 // the use-list order, since serialization to bitcode is part of the flow.
5654 if (JA.getType() == types::TY_LLVM_BC)
5655 CmdArgs.push_back("-emit-llvm-uselists");
5656
5657 if (IsUsingLTO) {
5658 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5659 options::OPT_foffload_lto_EQ);
5660 if (Triple.isNVPTX() && !IsRDCMode &&
5662 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5663 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5664 << "-fno-gpu-rdc";
5665 } else {
5666 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5667 CmdArgs.push_back(Args.MakeArgString(
5668 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5669 // PS4 uses the legacy LTO API, which does not support some of the
5670 // features enabled by -flto-unit.
5671 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5672 CmdArgs.push_back("-flto-unit");
5673 }
5674 }
5675 }
5676
5677 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5678
5679 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5680 if (!types::isLLVMIR(Input.getType()))
5681 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5682 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5683 }
5684
5685 if (Triple.isPPC())
5686 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5687 options::OPT_mno_regnames);
5688
5689 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5690 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5691
5692 if (Args.getLastArg(options::OPT_save_temps_EQ))
5693 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5694
5695 if (Args.getLastArg(options::OPT_save_dynamic_debugging_temps))
5696 Args.AddLastArg(CmdArgs, options::OPT_save_dynamic_debugging_temps);
5697
5698 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5699 options::OPT_fmemory_profile_EQ,
5700 options::OPT_fno_memory_profile);
5701 if (MemProfArg &&
5702 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5703 MemProfArg->render(Args, CmdArgs);
5704
5705 if (auto *MemProfUseArg =
5706 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5707 if (MemProfArg)
5708 D.Diag(diag::err_drv_argument_not_allowed_with)
5709 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5710 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5711 options::OPT_fprofile_generate_EQ))
5712 D.Diag(diag::err_drv_argument_not_allowed_with)
5713 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5714 MemProfUseArg->render(Args, CmdArgs);
5715 }
5716
5717 auto *CopyProfArg =
5718 Args.getLastArg(options::OPT_fcopyprof, options::OPT_fno_copyprof);
5719 if (CopyProfArg &&
5720 !CopyProfArg->getOption().matches(options::OPT_fno_copyprof)) {
5721 CopyProfArg->render(Args, CmdArgs);
5722 Args.AddLastArg(CmdArgs, options::OPT_fcopyprof_static_size_threshold_EQ);
5723 }
5724
5725 // Embed-bitcode option.
5726 // Only white-listed flags below are allowed to be embedded.
5727 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5729 // Add flags implied by -fembed-bitcode.
5730 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5731 // Disable all llvm IR level optimizations.
5732 CmdArgs.push_back("-disable-llvm-passes");
5733
5734 // Render target options.
5735 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5737
5738 // reject options that shouldn't be supported in bitcode
5739 // also reject kernel/kext
5740 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5741 options::OPT_mkernel,
5742 options::OPT_fapple_kext,
5743 options::OPT_ffunction_sections,
5744 options::OPT_fno_function_sections,
5745 options::OPT_fdata_sections,
5746 options::OPT_fno_data_sections,
5747 options::OPT_fbasic_block_sections_EQ,
5748 options::OPT_funique_internal_linkage_names,
5749 options::OPT_fno_unique_internal_linkage_names,
5750 options::OPT_funique_section_names,
5751 options::OPT_fno_unique_section_names,
5752 options::OPT_funique_basic_block_section_names,
5753 options::OPT_fno_unique_basic_block_section_names,
5754 options::OPT_mrestrict_it,
5755 options::OPT_mno_restrict_it,
5756 options::OPT_mstackrealign,
5757 options::OPT_mno_stackrealign,
5758 options::OPT_mstack_alignment,
5759 options::OPT_mcmodel_EQ,
5760 options::OPT_mlong_calls,
5761 options::OPT_mno_long_calls,
5762 options::OPT_ggnu_pubnames,
5763 options::OPT_gdwarf_aranges,
5764 options::OPT_fdebug_types_section,
5765 options::OPT_fno_debug_types_section,
5766 options::OPT_fdwarf_directory_asm,
5767 options::OPT_fno_dwarf_directory_asm,
5768 options::OPT_mrelax_all,
5769 options::OPT_mno_relax_all,
5770 options::OPT_ftrap_function_EQ,
5771 options::OPT_ffixed_r9,
5772 options::OPT_mfix_cortex_a53_835769,
5773 options::OPT_mno_fix_cortex_a53_835769,
5774 options::OPT_ffixed_x18,
5775 options::OPT_mglobal_merge,
5776 options::OPT_mno_global_merge,
5777 options::OPT_mred_zone,
5778 options::OPT_mno_red_zone,
5779 options::OPT_Wa_COMMA,
5780 options::OPT_Xassembler,
5781 options::OPT_mllvm,
5782 options::OPT_mmlir,
5783 };
5784 for (const auto &A : Args)
5785 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5786 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5787
5788 // Render the CodeGen options that need to be passed.
5789 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5790 options::OPT_fno_optimize_sibling_calls);
5791
5793 CmdArgs, JA);
5794
5795 // Render ABI arguments
5796 switch (TC.getArch()) {
5797 default: break;
5798 case llvm::Triple::arm:
5799 case llvm::Triple::armeb:
5800 case llvm::Triple::thumbeb:
5801 RenderARMABI(D, Triple, Args, CmdArgs);
5802 break;
5803 case llvm::Triple::aarch64:
5804 case llvm::Triple::aarch64_32:
5805 case llvm::Triple::aarch64_be:
5806 RenderAArch64ABI(Triple, Args, CmdArgs);
5807 break;
5808 }
5809
5810 // Input/Output file.
5811 if (Output.getType() == types::TY_Dependencies) {
5812 // Handled with other dependency code.
5813 } else if (Output.isFilename()) {
5814 CmdArgs.push_back("-o");
5815 CmdArgs.push_back(Output.getFilename());
5816 } else {
5817 assert(Output.isNothing() && "Input output.");
5818 }
5819
5820 for (const auto &II : Inputs) {
5821 addDashXForInput(Args, II, CmdArgs);
5822 if (II.isFilename())
5823 CmdArgs.push_back(II.getFilename());
5824 else
5825 II.getInputArg().renderAsInput(Args, CmdArgs);
5826 }
5827
5828 C.addCommand(std::make_unique<Command>(
5830 CmdArgs, Inputs, Output, D.getPrependArg()));
5831 return;
5832 }
5833
5834 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5835 CmdArgs.push_back("-fembed-bitcode=marker");
5836
5837 // We normally speed up the clang process a bit by skipping destructors at
5838 // exit, but when we're generating diagnostics we can rely on some of the
5839 // cleanup.
5840 if (!C.isForDiagnostics())
5841 CmdArgs.push_back("-disable-free");
5842 CmdArgs.push_back("-clear-ast-before-backend");
5843
5844#ifdef NDEBUG
5845 const bool IsAssertBuild = false;
5846#else
5847 const bool IsAssertBuild = true;
5848#endif
5849
5850 // Disable the verification pass in no-asserts builds unless otherwise
5851 // specified.
5852 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5853 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5854 CmdArgs.push_back("-disable-llvm-verifier");
5855 }
5856
5857 // Discard value names in no-asserts builds unless otherwise specified.
5858 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5859 options::OPT_fno_discard_value_names, !IsAssertBuild))
5860 CmdArgs.push_back("-discard-value-names");
5861
5862 // Set the main file name, so that debug info works even with
5863 // -save-temps.
5864 CmdArgs.push_back("-main-file-name");
5865 CmdArgs.push_back(getBaseInputName(Args, Input));
5866
5867 // Some flags which affect the language (via preprocessor
5868 // defines).
5869 if (Args.hasArg(options::OPT_static))
5870 CmdArgs.push_back("-static-define");
5871
5872 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5873
5874 if (Args.hasArg(options::OPT_municode))
5875 CmdArgs.push_back("-DUNICODE");
5876
5877 if (isa<AnalyzeJobAction>(JA))
5878 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5879
5880 if (isa<AnalyzeJobAction>(JA) ||
5881 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5882 CmdArgs.push_back("-setup-static-analyzer");
5883
5884 // Enable compatilibily mode to avoid analyzer-config related errors.
5885 // Since we can't access frontend flags through hasArg, let's manually iterate
5886 // through them.
5887 bool FoundAnalyzerConfig = false;
5888 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5889 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5890 FoundAnalyzerConfig = true;
5891 break;
5892 }
5893 if (!FoundAnalyzerConfig)
5894 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5895 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5896 FoundAnalyzerConfig = true;
5897 break;
5898 }
5899 if (FoundAnalyzerConfig)
5900 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5901
5903
5904 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5905 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5906 if (FunctionAlignment) {
5907 CmdArgs.push_back("-function-alignment");
5908 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5909 }
5910
5911 if (const Arg *A =
5912 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5913 unsigned Value = 0;
5914 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5915 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5916 << A->getAsString(Args) << A->getValue();
5917 else if (!llvm::isPowerOf2_32(Value))
5918 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5919 << A->getAsString(Args) << A->getValue();
5920
5921 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5922 Twine(std::min(Value, 65536u))));
5923 }
5924
5925 // We support -falign-loops=N where N is a power of 2. GCC supports more
5926 // forms.
5927 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5928 unsigned Value = 0;
5929 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5930 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5931 << A->getAsString(Args) << A->getValue();
5932 else if (Value & (Value - 1))
5933 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5934 << A->getAsString(Args) << A->getValue();
5935 // Treat =0 as unspecified (use the target preference).
5936 if (Value)
5937 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5938 Twine(std::min(Value, 65536u))));
5939 }
5940
5941 if (Triple.isOSzOS()) {
5942 // On z/OS some of the system header feature macros need to
5943 // be defined to enable most cross platform projects to build
5944 // successfully. Ths include the libc++ library. A
5945 // complicating factor is that users can define these
5946 // macros to the same or different values. We need to add
5947 // the definition for these macros to the compilation command
5948 // if the user hasn't already defined them.
5949
5950 auto findMacroDefinition = [&](const std::string &Macro) {
5951 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5952 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5953 return M == Macro || M.find(Macro + '=') != std::string::npos;
5954 });
5955 };
5956
5957 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5958 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5959 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5960 // _OPEN_DEFAULT is required for XL compat
5961 if (!findMacroDefinition("_OPEN_DEFAULT"))
5962 CmdArgs.push_back("-D_OPEN_DEFAULT");
5963 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5964 // _XOPEN_SOURCE=600 is required for libcxx.
5965 if (!findMacroDefinition("_XOPEN_SOURCE"))
5966 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5967 }
5968 }
5969
5970 llvm::Reloc::Model RelocationModel;
5971 unsigned PICLevel;
5972 bool IsPIE;
5973 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5974 Arg *LastPICDataRelArg =
5975 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5976 options::OPT_mpic_data_is_text_relative);
5977 bool NoPICDataIsTextRelative = false;
5978 if (LastPICDataRelArg) {
5979 if (LastPICDataRelArg->getOption().matches(
5980 options::OPT_mno_pic_data_is_text_relative)) {
5981 NoPICDataIsTextRelative = true;
5982 if (!PICLevel)
5983 D.Diag(diag::err_drv_argument_only_allowed_with)
5984 << "-mno-pic-data-is-text-relative"
5985 << "-fpic/-fpie";
5986 }
5987 if (!Triple.isSystemZ())
5988 D.Diag(diag::err_drv_unsupported_opt_for_target)
5989 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5990 : "-mpic-data-is-text-relative")
5991 << RawTriple.str();
5992 }
5993
5994 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5995 RelocationModel == llvm::Reloc::ROPI_RWPI;
5996 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5997 RelocationModel == llvm::Reloc::ROPI_RWPI;
5998
5999 if (Args.hasArg(options::OPT_mcmse) &&
6000 !Args.hasArg(options::OPT_fallow_unsupported)) {
6001 if (IsROPI)
6002 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
6003 if (IsRWPI)
6004 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
6005 }
6006
6007 if (IsROPI && types::isCXX(Input.getType()) &&
6008 !Args.hasArg(options::OPT_fallow_unsupported))
6009 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
6010
6011 const char *RMName = RelocationModelName(RelocationModel);
6012 if (RMName) {
6013 CmdArgs.push_back("-mrelocation-model");
6014 CmdArgs.push_back(RMName);
6015 }
6016 if (PICLevel > 0) {
6017 CmdArgs.push_back("-pic-level");
6018 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
6019 if (IsPIE)
6020 CmdArgs.push_back("-pic-is-pie");
6021 if (NoPICDataIsTextRelative)
6022 CmdArgs.push_back("-mcmodel=medium");
6023 }
6024
6025 if (RelocationModel == llvm::Reloc::ROPI ||
6026 RelocationModel == llvm::Reloc::ROPI_RWPI)
6027 CmdArgs.push_back("-fropi");
6028 if (RelocationModel == llvm::Reloc::RWPI ||
6029 RelocationModel == llvm::Reloc::ROPI_RWPI)
6030 CmdArgs.push_back("-frwpi");
6031
6032 // -meabi=gnu/5 are encoded in the cc1 -triple environment; forward only other
6033 // values (e.g. 4, which has no triple representation, and invalid values).
6034 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
6035 StringRef Value = A->getValue();
6036 if (Value != "gnu" && Value != "5") {
6037 CmdArgs.push_back("-meabi");
6038 CmdArgs.push_back(A->getValue());
6039 }
6040 }
6041
6042 // -fsemantic-interposition is forwarded to CC1: set the
6043 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
6044 // make default visibility external linkage definitions dso_preemptable.
6045 //
6046 // -fno-semantic-interposition: if the target supports .Lfoo$local local
6047 // aliases (make default visibility external linkage definitions dso_local).
6048 // This is the CC1 default for ELF to match COFF/Mach-O.
6049 //
6050 // Otherwise use Clang's traditional behavior: like
6051 // -fno-semantic-interposition but local aliases are not used. So references
6052 // can be interposed if not optimized out.
6053 if (Triple.isOSBinFormatELF()) {
6054 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
6055 options::OPT_fno_semantic_interposition);
6056 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
6057 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
6058 bool SupportsLocalAlias =
6059 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
6060 if (!A)
6061 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6062 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
6063 A->render(Args, CmdArgs);
6064 else if (!SupportsLocalAlias)
6065 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6066 }
6067 }
6068
6069 {
6070 std::string Model;
6071 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
6072 if (!TC.isThreadModelSupported(A->getValue()))
6073 D.Diag(diag::err_drv_invalid_thread_model_for_target)
6074 << A->getValue() << A->getAsString(Args);
6075 Model = A->getValue();
6076 } else
6077 Model = TC.getThreadModel();
6078 if (Model != "posix") {
6079 CmdArgs.push_back("-mthread-model");
6080 CmdArgs.push_back(Args.MakeArgString(Model));
6081 }
6082 }
6083
6084 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6085 StringRef Name = A->getValue();
6086 if (Name == "SVML") {
6087 if (Triple.getArch() != llvm::Triple::x86 &&
6088 Triple.getArch() != llvm::Triple::x86_64)
6089 D.Diag(diag::err_drv_unsupported_opt_for_target)
6090 << Name << Triple.getArchName();
6091 } else if (Name == "AMDLIBM") {
6092 if (Triple.getArch() != llvm::Triple::x86 &&
6093 Triple.getArch() != llvm::Triple::x86_64)
6094 D.Diag(diag::err_drv_unsupported_opt_for_target)
6095 << Name << Triple.getArchName();
6096 } else if (Name == "libmvec") {
6097 if (Triple.getArch() != llvm::Triple::x86 &&
6098 Triple.getArch() != llvm::Triple::x86_64 &&
6099 Triple.getArch() != llvm::Triple::aarch64 &&
6100 Triple.getArch() != llvm::Triple::aarch64_be)
6101 D.Diag(diag::err_drv_unsupported_opt_for_target)
6102 << Name << Triple.getArchName();
6103 } else if (Name == "SLEEF" || Name == "ArmPL") {
6104 if (Triple.getArch() != llvm::Triple::aarch64 &&
6105 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6106 D.Diag(diag::err_drv_unsupported_opt_for_target)
6107 << Name << Triple.getArchName();
6108 }
6109 A->render(Args, CmdArgs);
6110 }
6111
6112 if (Args.hasFlag(options::OPT_fmerge_all_constants,
6113 options::OPT_fno_merge_all_constants, false))
6114 CmdArgs.push_back("-fmerge-all-constants");
6115
6116 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
6117 options::OPT_fno_delete_null_pointer_checks);
6118
6119 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6120 options::OPT_fno_lifetime_dse);
6121
6122 // LLVM Code Generator Options.
6123
6124 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6125 if (!Triple.isOSAIX() || Triple.isPPC32())
6126 D.Diag(diag::err_drv_unsupported_opt_for_target)
6127 << A->getSpelling() << RawTriple.str();
6128 CmdArgs.push_back("-mabi=quadword-atomics");
6129 }
6130
6131 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6132 // Emit the unsupported option error until the Clang's library integration
6133 // support for 128-bit long double is available for AIX.
6134 if (Triple.isOSAIX())
6135 D.Diag(diag::err_drv_unsupported_opt_for_target)
6136 << A->getSpelling() << RawTriple.str();
6137 }
6138
6139 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6140 StringRef V = A->getValue(), V1 = V;
6141 unsigned Size;
6142 if (V1.consumeInteger(10, Size) || !V1.empty())
6143 D.Diag(diag::err_drv_invalid_argument_to_option)
6144 << V << A->getOption().getName();
6145 else
6146 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6147 }
6148
6149 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6150 options::OPT_fno_jump_tables);
6151 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6152 options::OPT_fno_profile_sample_accurate);
6153 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6154 options::OPT_fno_preserve_as_comments);
6155
6156 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6157 CmdArgs.push_back("-mregparm");
6158 CmdArgs.push_back(A->getValue());
6159 }
6160
6161 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6162 options::OPT_msvr4_struct_return)) {
6163 if (!TC.getTriple().isPPC32()) {
6164 D.Diag(diag::err_drv_unsupported_opt_for_target)
6165 << A->getSpelling() << RawTriple.str();
6166 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6167 CmdArgs.push_back("-maix-struct-return");
6168 } else {
6169 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6170 CmdArgs.push_back("-msvr4-struct-return");
6171 }
6172 }
6173
6174 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6175 options::OPT_freg_struct_return)) {
6176 if (TC.getArch() != llvm::Triple::x86) {
6177 D.Diag(diag::err_drv_unsupported_opt_for_target)
6178 << A->getSpelling() << RawTriple.str();
6179 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6180 CmdArgs.push_back("-fpcc-struct-return");
6181 } else {
6182 assert(A->getOption().matches(options::OPT_freg_struct_return));
6183 CmdArgs.push_back("-freg-struct-return");
6184 }
6185 }
6186
6187 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6188 if (Triple.getArch() == llvm::Triple::m68k)
6189 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6190 else
6191 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6192 }
6193
6194 if (Args.hasArg(options::OPT_fenable_matrix)) {
6195 // enable-matrix is needed by both the LangOpts and by LLVM.
6196 CmdArgs.push_back("-fenable-matrix");
6197 CmdArgs.push_back("-mllvm");
6198 CmdArgs.push_back("-enable-matrix");
6199 // Only handle default layout if matrix is enabled
6200 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6201 StringRef Val = A->getValue();
6202 if (Val == "row-major" || Val == "column-major") {
6203 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6204 CmdArgs.push_back("-mllvm");
6205 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6206
6207 } else {
6208 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6209 }
6210 }
6211 }
6212
6214 getFramePointerKind(Args, RawTriple);
6215 const char *FPKeepKindStr = nullptr;
6216 switch (FPKeepKind) {
6218 FPKeepKindStr = "-mframe-pointer=none";
6219 break;
6221 FPKeepKindStr = "-mframe-pointer=reserved";
6222 break;
6224 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6225 break;
6227 FPKeepKindStr = "-mframe-pointer=non-leaf";
6228 break;
6230 FPKeepKindStr = "-mframe-pointer=all";
6231 break;
6232 }
6233 assert(FPKeepKindStr && "unknown FramePointerKind");
6234 CmdArgs.push_back(FPKeepKindStr);
6235
6236 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6237 options::OPT_fno_zero_initialized_in_bss);
6238
6239 bool OFastEnabled = isOptimizationLevelFast(Args);
6240 if (Args.hasArg(options::OPT_Ofast))
6241 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6242 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6243 // enabled. This alias option is being used to simplify the hasFlag logic.
6244 OptSpecifier StrictAliasingAliasOption =
6245 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6246 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6247 // doesn't do any TBAA.
6248 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6249 options::OPT_fno_strict_aliasing,
6250 !IsWindowsMSVC && !IsUEFI))
6251 CmdArgs.push_back("-relaxed-aliasing");
6252 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6253 false))
6254 CmdArgs.push_back("-no-pointer-tbaa");
6255 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6256 options::OPT_fno_struct_path_tbaa, true))
6257 CmdArgs.push_back("-no-struct-path-tbaa");
6258
6259 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6260 options::OPT_fno_strict_bool,
6261 options::OPT_fno_strict_bool_EQ)) {
6262 StringRef BFM = "";
6263 if (A->getOption().matches(options::OPT_fstrict_bool))
6264 BFM = "strict";
6265 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6266 BFM = "nonstrict";
6267 else if (A->getValue() == StringRef("truncate"))
6268 BFM = "truncate";
6269 else if (A->getValue() == StringRef("nonzero"))
6270 BFM = "nonzero";
6271 else
6272 D.Diag(diag::err_drv_invalid_value)
6273 << A->getAsString(Args) << A->getValue();
6274 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6275 } else if (KernelOrKext) {
6276 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6277 CmdArgs.push_back("-load-bool-from-mem=truncate");
6278 }
6279
6280 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6281 options::OPT_fno_strict_enums);
6282 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6283 options::OPT_fno_strict_return);
6284 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6285 options::OPT_fno_allow_editor_placeholders);
6286 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6287 options::OPT_fno_strict_vtable_pointers);
6288 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6289 options::OPT_fno_force_emit_vtables);
6290 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6291 options::OPT_fno_optimize_sibling_calls);
6292 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6293 options::OPT_fno_escaping_block_tail_calls);
6294
6295 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6296 options::OPT_fno_fine_grained_bitfield_accesses);
6297
6298 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6299 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6300
6301 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6302 options::OPT_fno_experimental_omit_vtable_rtti);
6303
6304 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6305 options::OPT_fno_disable_block_signature_string);
6306
6307 // Handle segmented stacks.
6308 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6309 options::OPT_fno_split_stack);
6310
6311 // -fprotect-parens=0 is default.
6312 if (Args.hasFlag(options::OPT_fprotect_parens,
6313 options::OPT_fno_protect_parens, false))
6314 CmdArgs.push_back("-fprotect-parens");
6315
6316 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6317
6318 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6319 options::OPT_fno_atomic_remote_memory);
6320 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6321 options::OPT_fno_atomic_fine_grained_memory);
6322 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6323 options::OPT_fno_atomic_ignore_denormal_mode);
6324
6325 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6326 const llvm::Triple::ArchType Arch = TC.getArch();
6327 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6328 StringRef V = A->getValue();
6329 if (V == "64")
6330 CmdArgs.push_back("-fextend-arguments=64");
6331 else if (V != "32")
6332 D.Diag(diag::err_drv_invalid_argument_to_option)
6333 << A->getValue() << A->getOption().getName();
6334 } else
6335 D.Diag(diag::err_drv_unsupported_opt_for_target)
6336 << A->getOption().getName() << TripleStr;
6337 }
6338
6339 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6340 if (TC.getArch() == llvm::Triple::avr)
6341 A->render(Args, CmdArgs);
6342 else
6343 D.Diag(diag::err_drv_unsupported_opt_for_target)
6344 << A->getAsString(Args) << TripleStr;
6345 }
6346
6347 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6348 if (TC.getTriple().isX86())
6349 A->render(Args, CmdArgs);
6350 else if (TC.getTriple().isPPC() &&
6351 (A->getOption().getID() != options::OPT_mlong_double_80))
6352 A->render(Args, CmdArgs);
6353 else
6354 D.Diag(diag::err_drv_unsupported_opt_for_target)
6355 << A->getAsString(Args) << TripleStr;
6356 }
6357
6358 // Decide whether to use verbose asm. Verbose assembly is the default on
6359 // toolchains which have the integrated assembler on by default.
6360 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6361 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6362 IsIntegratedAssemblerDefault))
6363 CmdArgs.push_back("-fno-verbose-asm");
6364
6365 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6366 // use that to indicate the MC default in the backend.
6367 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6368 StringRef V = A->getValue();
6369 unsigned Num;
6370 if (V == "none")
6371 A->render(Args, CmdArgs);
6372 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6373 (V.empty() || (V.consume_front(".") &&
6374 !V.consumeInteger(10, Num) && V.empty())))
6375 A->render(Args, CmdArgs);
6376 else
6377 D.Diag(diag::err_drv_invalid_argument_to_option)
6378 << A->getValue() << A->getOption().getName();
6379 }
6380
6381 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6382 // option to disable integrated-as explicitly.
6384 CmdArgs.push_back("-no-integrated-as");
6385
6386 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6387 CmdArgs.push_back("-mdebug-pass");
6388 CmdArgs.push_back("Structure");
6389 }
6390 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6391 CmdArgs.push_back("-mdebug-pass");
6392 CmdArgs.push_back("Arguments");
6393 }
6394
6395 // Enable -mconstructor-aliases except on darwin, where we have to work around
6396 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6397 // code, where aliases aren't supported.
6398 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6399 CmdArgs.push_back("-mconstructor-aliases");
6400
6401 // Darwin's kernel doesn't support guard variables; just die if we
6402 // try to use them.
6403 if (KernelOrKext && RawTriple.isOSDarwin())
6404 CmdArgs.push_back("-fforbid-guard-variables");
6405
6406 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6407 options::OPT_mno_ms_bitfields)) {
6408 if (A->getOption().matches(options::OPT_mms_bitfields))
6409 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6410 else
6411 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6412 }
6413
6414 if (Triple.isOSCygMing()) {
6415 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6416 options::OPT_fno_auto_import);
6417 }
6418
6419 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6420 Triple.isX86() && IsWindowsMSVC))
6421 CmdArgs.push_back("-fms-volatile");
6422
6423 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6424 // defaults to -fno-direct-access-external-data. Pass the option if different
6425 // from the default.
6426 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6427 options::OPT_fno_direct_access_external_data)) {
6428 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6429 (PICLevel == 0))
6430 A->render(Args, CmdArgs);
6431 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6432 // Some targets default to -fno-direct-access-external-data even for
6433 // -fno-pic.
6434 CmdArgs.push_back("-fno-direct-access-external-data");
6435 }
6436
6437 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6438 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6439
6440 // -fhosted is default.
6441 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6442 // use Freestanding.
6443 bool Freestanding =
6444 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6445 KernelOrKext;
6446 if (Freestanding)
6447 CmdArgs.push_back("-ffreestanding");
6448
6449 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6450
6452 auto SanitizeArgs =
6454 Args.AddLastArg(CmdArgs,
6455 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6456
6457 // This is a coarse approximation of what llvm-gcc actually does, both
6458 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6459 // complicated ways.
6460 bool IsAsyncUnwindTablesDefault =
6462 bool IsSyncUnwindTablesDefault =
6464
6465 bool AsyncUnwindTables = Args.hasFlag(
6466 options::OPT_fasynchronous_unwind_tables,
6467 options::OPT_fno_asynchronous_unwind_tables,
6468 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6469 !Freestanding);
6470 bool UnwindTables =
6471 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6472 IsSyncUnwindTablesDefault && !Freestanding);
6473 if (AsyncUnwindTables)
6474 CmdArgs.push_back("-funwind-tables=2");
6475 else if (UnwindTables)
6476 CmdArgs.push_back("-funwind-tables=1");
6477
6478 // Sframe unwind tables are independent of the other types. Although also
6479 // defined for aarch64, only x86_64 support is implemented at the moment.
6480 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6481 if (Triple.isOSBinFormatELF() && Triple.isX86())
6482 CmdArgs.push_back("--gsframe");
6483 else
6484 D.Diag(diag::err_drv_unsupported_opt_for_target)
6485 << A->getOption().getName() << TripleStr;
6486 }
6487
6488 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6489 // `--gpu-use-aux-triple-only` is specified.
6490 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6491 const ArgList &HostArgs =
6492 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6493 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6494 if (!HostCPU.empty()) {
6495 CmdArgs.push_back("-aux-target-cpu");
6496 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6497 }
6498 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6499 /*ForAS*/ false, /*IsAux*/ true);
6500 }
6501
6502 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6504
6505 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6506
6507 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6508 StringRef Value = A->getValue();
6509 unsigned TLSSize = 0;
6510 Value.getAsInteger(10, TLSSize);
6511 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6512 D.Diag(diag::err_drv_unsupported_opt_for_target)
6513 << A->getOption().getName() << TripleStr;
6514 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6515 D.Diag(diag::err_drv_invalid_int_value)
6516 << A->getOption().getName() << Value;
6517 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6518 }
6519
6520 if (isTLSDESCEnabled(TC, Args))
6521 CmdArgs.push_back("-enable-tlsdesc");
6522
6523 // Add the target cpu
6524 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6525 if (!CPU.empty()) {
6526 CmdArgs.push_back("-target-cpu");
6527 CmdArgs.push_back(Args.MakeArgString(CPU));
6528 }
6529
6530 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6531
6532 // Add clang-cl arguments.
6533 types::ID InputType = Input.getType();
6534 if (D.IsCLMode())
6535 AddClangCLArgs(Args, InputType, CmdArgs);
6536
6537 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6538 llvm::codegenoptions::NoDebugInfo;
6540 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6541 DebugInfoKind, DwarfFission, IsUsingLTO);
6542
6543 // Add the split debug info name to the command lines here so we
6544 // can propagate it to the backend.
6545 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6546 (TC.getTriple().isOSBinFormatELF() ||
6547 TC.getTriple().isOSBinFormatWasm() ||
6548 TC.getTriple().isOSBinFormatCOFF()) &&
6551 if (SplitDWARF) {
6552 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6553 CmdArgs.push_back("-split-dwarf-file");
6554 CmdArgs.push_back(SplitDWARFOut);
6555 if (DwarfFission == DwarfFissionKind::Split) {
6556 CmdArgs.push_back("-split-dwarf-output");
6557 CmdArgs.push_back(SplitDWARFOut);
6558 }
6559 }
6560
6561 // Pass the linker version in use.
6562 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6563 CmdArgs.push_back("-target-linker-version");
6564 CmdArgs.push_back(A->getValue());
6565 }
6566
6567 // Explicitly error on some things we know we don't support and can't just
6568 // ignore.
6569 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6570 Arg *Unsupported;
6571 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6572 TC.getArch() == llvm::Triple::x86) {
6573 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6574 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6575 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6576 << Unsupported->getOption().getName();
6577 }
6578 // The faltivec option has been superseded by the maltivec option.
6579 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6580 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6581 << Unsupported->getOption().getName()
6582 << "please use -maltivec and include altivec.h explicitly";
6583 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6584 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6585 << Unsupported->getOption().getName() << "please use -mno-altivec";
6586 }
6587
6588 Args.AddAllArgs(CmdArgs, options::OPT_v);
6589
6590 if (Args.getLastArg(options::OPT_H)) {
6591 CmdArgs.push_back("-H");
6592 CmdArgs.push_back("-sys-header-deps");
6593 }
6594 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6595
6597 CmdArgs.push_back("-header-include-file");
6598 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6599 ? D.CCPrintHeadersFilename.c_str()
6600 : "-");
6601 CmdArgs.push_back("-sys-header-deps");
6602 CmdArgs.push_back(Args.MakeArgString(
6603 "-header-include-format=" +
6605 CmdArgs.push_back(Args.MakeArgString(
6606 "-header-include-filtering=" +
6608 }
6609 Args.AddLastArg(CmdArgs, options::OPT_P);
6610 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6611
6612 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6613 CmdArgs.push_back("-diagnostic-log-file");
6614 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6615 ? D.CCLogDiagnosticsFilename.c_str()
6616 : "-");
6617 }
6618
6619 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6620 // crashes.
6621 if (D.CCGenDiagnostics)
6622 CmdArgs.push_back("-disable-pragma-debug-crash");
6623
6624 // Allow backend to put its diagnostic files in the same place as frontend
6625 // crash diagnostics files.
6626 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6627 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6628 CmdArgs.push_back("-mllvm");
6629 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6630 }
6631
6632 addSeparateSectionFlags(Triple, Args, CmdArgs);
6633
6634 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6635 options::OPT_fno_basic_block_address_map)) {
6636 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6637 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6638 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6639 A->render(Args, CmdArgs);
6640 } else {
6641 D.Diag(diag::err_drv_unsupported_opt_for_target)
6642 << A->getAsString(Args) << TripleStr;
6643 }
6644 }
6645
6646 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6647 StringRef Val = A->getValue();
6648 if (Val == "labels") {
6649 D.Diag(diag::warn_drv_deprecated_arg)
6650 << A->getAsString(Args) << /*hasReplacement=*/true
6651 << "-fbasic-block-address-map";
6652 CmdArgs.push_back("-fbasic-block-address-map");
6653 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6654 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6655 D.Diag(diag::err_drv_invalid_value)
6656 << A->getAsString(Args) << A->getValue();
6657 else
6658 A->render(Args, CmdArgs);
6659 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6660 // "all" is not supported on AArch64 since branch relaxation creates new
6661 // basic blocks for some cross-section branches.
6662 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6663 D.Diag(diag::err_drv_invalid_value)
6664 << A->getAsString(Args) << A->getValue();
6665 else
6666 A->render(Args, CmdArgs);
6667 } else if (Triple.isNVPTX()) {
6668 // Do not pass the option to the GPU compilation. We still want it enabled
6669 // for the host-side compilation, so seeing it here is not an error.
6670 } else if (Val != "none") {
6671 // =none is allowed everywhere. It's useful for overriding the option
6672 // and is the same as not specifying the option.
6673 D.Diag(diag::err_drv_unsupported_opt_for_target)
6674 << A->getAsString(Args) << TripleStr;
6675 }
6676 }
6677
6678 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6679 options::OPT_fno_unique_section_names);
6680 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6681 options::OPT_fno_separate_named_sections);
6682 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6683 options::OPT_fno_unique_internal_linkage_names);
6684 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6685 options::OPT_fno_unique_basic_block_section_names);
6686
6687 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6688
6689 if (Arg *A =
6690 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6691 options::OPT_fno_partition_static_data_sections)) {
6692 if (!A->getOption().matches(
6693 options::OPT_fno_partition_static_data_sections)) {
6694 // This codegen pass is only available on x86 and AArch64 ELF targets.
6695 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6696 A->render(Args, CmdArgs);
6697 CmdArgs.push_back("-mllvm");
6698 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6699 } else
6700 D.Diag(diag::err_drv_unsupported_opt_for_target)
6701 << A->getAsString(Args) << TripleStr;
6702 }
6703 }
6704
6705 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6706 options::OPT_finstrument_functions_after_inlining,
6707 options::OPT_finstrument_function_entry_bare);
6708 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6709 options::OPT_fno_convergent_functions);
6710
6711 // NVPTX doesn't support PGO or coverage
6712 if (!Triple.isNVPTX())
6713 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6714
6715 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6716
6717 if (getLastProfileSampleUseArg(Args) &&
6718 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6719 options::OPT_fno_sample_profile_use_profi, true)) {
6720 CmdArgs.push_back("-mllvm");
6721 CmdArgs.push_back("-sample-profile-use-profi");
6722 }
6723
6724 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6725 if (RawTriple.isPS() &&
6726 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6727 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6728 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6729 }
6730
6731 // Pass options for controlling the default header search paths.
6732 if (Args.hasArg(options::OPT_nostdinc)) {
6733 CmdArgs.push_back("-nostdsysteminc");
6734 CmdArgs.push_back("-nobuiltininc");
6735 } else {
6736 if (Args.hasArg(options::OPT_nostdlibinc))
6737 CmdArgs.push_back("-nostdsysteminc");
6738 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6739 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6740 }
6741
6742 // Pass the path to compiler resource files.
6743 CmdArgs.push_back("-resource-dir");
6744 CmdArgs.push_back(D.ResourceDir.c_str());
6745
6746 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6747
6748 // Add preprocessing options like -I, -D, etc. if we are using the
6749 // preprocessor.
6750 //
6751 // FIXME: Support -fpreprocessed
6753 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6754
6755 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6756 // that "The compiler can only warn and ignore the option if not recognized".
6757 // When building with ccache, it will pass -D options to clang even on
6758 // preprocessed inputs and configure concludes that -fPIC is not supported.
6759 Args.ClaimAllArgs(options::OPT_D);
6760
6761 // Warn about ignored options to clang.
6762 for (const Arg *A :
6763 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6764 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6765 A->claim();
6766 }
6767
6768 for (const Arg *A :
6769 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6770 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6771 A->claim();
6772 }
6773
6774 claimNoWarnArgs(Args);
6775
6776 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6777
6778 for (const Arg *A :
6779 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6780 A->claim();
6781 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6782 unsigned WarningNumber;
6783 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6784 D.Diag(diag::err_drv_invalid_int_value)
6785 << A->getAsString(Args) << A->getValue();
6786 continue;
6787 }
6788
6789 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6790 CmdArgs.push_back(Args.MakeArgString(
6791 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6792 }
6793 continue;
6794 }
6795 A->render(Args, CmdArgs);
6796 }
6797
6798 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6799
6800 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6801 CmdArgs.push_back("-pedantic");
6802 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6803 Args.AddLastArg(CmdArgs, options::OPT_w);
6804
6805 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6806 options::OPT_fno_fixed_point);
6807
6808 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6809 options::OPT_fno_experimental_overflow_behavior_types);
6810
6811 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6812 A->render(Args, CmdArgs);
6813
6814 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6815 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6816
6817 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6818 options::OPT_fno_experimental_omit_vtable_rtti);
6819
6820 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6821 A->render(Args, CmdArgs);
6822
6823 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6824 // (-ansi is equivalent to -std=c89 or -std=c++98).
6825 //
6826 // If a std is supplied, only add -trigraphs if it follows the
6827 // option.
6828 bool ImplyVCPPCVer = false;
6829 bool ImplyVCPPCXXVer = false;
6830 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6831 if (Std) {
6832 if (Std->getOption().matches(options::OPT_ansi))
6833 if (types::isCXX(InputType))
6834 CmdArgs.push_back("-std=c++98");
6835 else
6836 CmdArgs.push_back("-std=c89");
6837 else {
6838 if (IsSYCL) {
6839 const LangStandard *LangStd =
6840 LangStandard::getLangStandardForName(Std->getValue());
6841 if (LangStd) {
6842 // Use of -std= with 'C' is not supported for SYCL.
6843 if (LangStd->getLanguage() == Language::C)
6844 D.Diag(diag::err_drv_argument_not_allowed_with)
6845 << Std->getAsString(Args) << "-fsycl";
6846 // SYCL requires C++17 or later.
6847 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6848 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6849 }
6850 }
6851 Std->render(Args, CmdArgs);
6852 }
6853
6854 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6855 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6856 options::OPT_ftrigraphs,
6857 options::OPT_fno_trigraphs))
6858 if (A != Std)
6859 A->render(Args, CmdArgs);
6860 } else {
6861 // Honor -std-default.
6862 //
6863 // FIXME: Clang doesn't correctly handle -std= when the input language
6864 // doesn't match. For the time being just ignore this for C++ inputs;
6865 // eventually we want to do all the standard defaulting here instead of
6866 // splitting it between the driver and clang -cc1.
6867 if (!types::isCXX(InputType)) {
6868 if (!Args.hasArg(options::OPT__SLASH_std)) {
6869 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6870 /*Joined=*/true);
6871 } else
6872 ImplyVCPPCVer = true;
6873 }
6874 else if (IsWindowsMSVC)
6875 ImplyVCPPCXXVer = true;
6876
6877 if (IsSYCL && types::isCXX(InputType) &&
6878 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6879 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6880 // on the command line will override. On Windows MSVC, this is handled
6881 // by the ImplyVCPPCXXVer path below.
6882 CmdArgs.push_back("-std=c++17");
6883
6884 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6885 options::OPT_fno_trigraphs);
6886 }
6887
6888 // GCC's behavior for -Wwrite-strings is a bit strange:
6889 // * In C, this "warning flag" changes the types of string literals from
6890 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6891 // for the discarded qualifier.
6892 // * In C++, this is just a normal warning flag.
6893 //
6894 // Implementing this warning correctly in C is hard, so we follow GCC's
6895 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6896 // a non-const char* in C, rather than using this crude hack.
6897 if (!types::isCXX(InputType)) {
6898 // FIXME: This should behave just like a warning flag, and thus should also
6899 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6900 Arg *WriteStrings =
6901 Args.getLastArg(options::OPT_Wwrite_strings,
6902 options::OPT_Wno_write_strings, options::OPT_w);
6903 if (WriteStrings &&
6904 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6905 CmdArgs.push_back("-fconst-strings");
6906 }
6907
6908 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6909 // during C++ compilation, which it is by default. GCC keeps this define even
6910 // in the presence of '-w', match this behavior bug-for-bug.
6911 if (types::isCXX(InputType) &&
6912 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6913 true)) {
6914 CmdArgs.push_back("-fdeprecated-macro");
6915 }
6916
6917 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6918 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6919 if (Asm->getOption().matches(options::OPT_fasm))
6920 CmdArgs.push_back("-fgnu-keywords");
6921 else
6922 CmdArgs.push_back("-fno-gnu-keywords");
6923 }
6924
6925 if (!ShouldEnableAutolink(Args, TC, JA))
6926 CmdArgs.push_back("-fno-autolink");
6927
6928 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6929 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6930 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6931 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6932
6933 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6934
6935 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6936 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6937 Args.AddLastArg(CmdArgs,
6938 options::OPT_fno_experimental_new_constant_interpreter);
6939 } else {
6940 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6941 Args.AddLastArg(CmdArgs,
6942 options::OPT_fexperimental_new_constant_interpreter);
6943 }
6944
6945 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6946 CmdArgs.push_back("-fbracket-depth");
6947 CmdArgs.push_back(A->getValue());
6948 }
6949
6950 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6951 options::OPT_Wlarge_by_value_copy_def)) {
6952 if (A->getNumValues()) {
6953 StringRef bytes = A->getValue();
6954 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6955 } else
6956 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6957 }
6958
6959 if (Args.hasArg(options::OPT_relocatable_pch))
6960 CmdArgs.push_back("-relocatable-pch");
6961 Args.AddLastArg(CmdArgs, options::OPT_fpch_base_dir_is_cwd);
6962
6963 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6964 static const char *kCFABIs[] = {
6965 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6966 };
6967
6968 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6969 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6970 else
6971 A->render(Args, CmdArgs);
6972 }
6973
6974 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6975 CmdArgs.push_back("-fconstant-string-class");
6976 CmdArgs.push_back(A->getValue());
6977 }
6978
6979 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6980 CmdArgs.push_back("-fconstant-array-class");
6981 CmdArgs.push_back(A->getValue());
6982 }
6983 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6984 CmdArgs.push_back("-fconstant-dictionary-class");
6985 CmdArgs.push_back(A->getValue());
6986 }
6987 if (Arg *A =
6988 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6989 CmdArgs.push_back("-fconstant-integer-number-class");
6990 CmdArgs.push_back(A->getValue());
6991 }
6992 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6993 CmdArgs.push_back("-fconstant-float-number-class");
6994 CmdArgs.push_back(A->getValue());
6995 }
6996 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6997 CmdArgs.push_back("-fconstant-double-number-class");
6998 CmdArgs.push_back(A->getValue());
6999 }
7000
7001 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
7002 CmdArgs.push_back("-ftabstop");
7003 CmdArgs.push_back(A->getValue());
7004 }
7005
7006 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
7007 options::OPT_fno_experimental_call_graph_section, false))
7008 CmdArgs.push_back("-fexperimental-call-graph-section");
7009
7010 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
7011 options::OPT_fno_stack_size_section);
7012
7013 if (Args.hasArg(options::OPT_fstack_usage)) {
7014 CmdArgs.push_back("-stack-usage-file");
7015
7016 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7017 SmallString<128> OutputFilename(OutputOpt->getValue());
7018 llvm::sys::path::replace_extension(OutputFilename, "su");
7019 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7020 } else
7021 CmdArgs.push_back(
7022 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
7023 }
7024
7025 CmdArgs.push_back("-ferror-limit");
7026 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
7027 CmdArgs.push_back(A->getValue());
7028 else
7029 CmdArgs.push_back("19");
7030
7031 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
7032 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
7033 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
7034 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
7035 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
7036
7037 // Pass -fmessage-length=.
7038 unsigned MessageLength = 0;
7039 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
7040 StringRef V(A->getValue());
7041 if (V.getAsInteger(0, MessageLength))
7042 D.Diag(diag::err_drv_invalid_argument_to_option)
7043 << V << A->getOption().getName();
7044 } else {
7045 // If -fmessage-length=N was not specified, determine whether this is a
7046 // terminal and, if so, implicitly define -fmessage-length appropriately.
7047 MessageLength = llvm::sys::Process::StandardErrColumns();
7048 }
7049 if (MessageLength != 0)
7050 CmdArgs.push_back(
7051 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
7052
7053 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
7054 CmdArgs.push_back(
7055 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
7056
7057 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
7058 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
7059 Twine(A->getValue(0))));
7060
7061 // -fvisibility= and -fvisibility-ms-compat are of a piece.
7062 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
7063 options::OPT_fvisibility_ms_compat)) {
7064 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
7065 A->render(Args, CmdArgs);
7066 } else {
7067 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7068 CmdArgs.push_back("-fvisibility=hidden");
7069 CmdArgs.push_back("-ftype-visibility=default");
7070 }
7071 } else if (IsOpenMPDevice) {
7072 // When compiling for the OpenMP device we want protected visibility by
7073 // default. This prevents the device from accidentally preempting code on
7074 // the host, makes the system more robust, and improves performance.
7075 CmdArgs.push_back("-fvisibility=protected");
7076 }
7077
7078 // PS4/PS5 process these options in addClangTargetOptions.
7079 if (!RawTriple.isPS()) {
7080 if (const Arg *A =
7081 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
7082 options::OPT_fno_visibility_from_dllstorageclass)) {
7083 if (A->getOption().matches(
7084 options::OPT_fvisibility_from_dllstorageclass)) {
7085 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
7086 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
7087 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
7088 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
7089 Args.AddLastArg(CmdArgs,
7090 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7091 }
7092 }
7093 }
7094
7095 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
7096 options::OPT_fno_visibility_inlines_hidden, false))
7097 CmdArgs.push_back("-fvisibility-inlines-hidden");
7098
7099 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
7100 options::OPT_fno_visibility_inlines_hidden_static_local_var);
7101
7102 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7103 // -fvisibility-global-new-delete=force-hidden.
7104 if (const Arg *A =
7105 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
7106 D.Diag(diag::warn_drv_deprecated_arg)
7107 << A->getAsString(Args) << /*hasReplacement=*/true
7108 << "-fvisibility-global-new-delete=force-hidden";
7109 }
7110
7111 if (const Arg *A =
7112 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7113 options::OPT_fvisibility_global_new_delete_hidden)) {
7114 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7115 A->render(Args, CmdArgs);
7116 } else {
7117 assert(A->getOption().matches(
7118 options::OPT_fvisibility_global_new_delete_hidden));
7119 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7120 }
7121 }
7122
7123 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7124
7125 if (Args.hasFlag(options::OPT_fnew_infallible,
7126 options::OPT_fno_new_infallible, false))
7127 CmdArgs.push_back("-fnew-infallible");
7128
7129 if (Args.hasFlag(options::OPT_fno_operator_names,
7130 options::OPT_foperator_names, false))
7131 CmdArgs.push_back("-fno-operator-names");
7132
7133 // Forward -f (flag) options which we can pass directly.
7134 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7135 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7136 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7137 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7138 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7139 options::OPT_fno_raw_string_literals);
7140
7141 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7142 Triple.hasDefaultEmulatedTLS()))
7143 CmdArgs.push_back("-femulated-tls");
7144
7145 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7146 options::OPT_fno_check_new);
7147
7148 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7149 // FIXME: There's no reason for this to be restricted to some backend.
7150 // The backend code needs to be changed to include the appropriate function
7151 // calls automatically.
7152 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7153 D.Diag(diag::err_drv_unsupported_opt_for_target)
7154 << A->getAsString(Args) << TripleStr;
7155 }
7156
7157 // AltiVec-like language extensions aren't relevant for assembling.
7158 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7159 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7160
7161 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7162 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7163
7164 // Forward flags for OpenMP. We don't do this if the current action is an
7165 // device offloading action other than OpenMP.
7166 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7167 options::OPT_fno_openmp, false) &&
7168 !Args.hasFlag(options::OPT_foffload_via_llvm,
7169 options::OPT_fno_offload_via_llvm, false) &&
7172
7173 // Determine if target-fast optimizations should be enabled
7174 bool TargetFastUsed =
7175 Args.hasFlag(options::OPT_fopenmp_target_fast,
7176 options::OPT_fno_openmp_target_fast, OFastEnabled);
7177 switch (D.getOpenMPRuntime(Args)) {
7178 case Driver::OMPRT_OMP:
7180 // Clang can generate useful OpenMP code for these two runtime libraries.
7181 CmdArgs.push_back("-fopenmp");
7182
7183 // If no option regarding the use of TLS in OpenMP codegeneration is
7184 // given, decide a default based on the target. Otherwise rely on the
7185 // options and pass the right information to the frontend.
7186 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7187 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7188 CmdArgs.push_back("-fnoopenmp-use-tls");
7189 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7190 options::OPT_fno_openmp_simd);
7191 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7192 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7193 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7194 options::OPT_fno_openmp_extensions, /*Default=*/true))
7195 CmdArgs.push_back("-fno-openmp-extensions");
7196 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7197 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7198 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7199 // effect: the teams reduction buffer is sized at kernel launch by the
7200 // offload plugin to match the actual number of teams. Honoring a
7201 // smaller user-supplied value would silently truncate the buffer for
7202 // larger launches.
7203 if (Arg *A = Args.getLastArg(
7204 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7205 D.Diag(diag::warn_drv_deprecated_custom)
7206 << A->getAsString(Args)
7207 << "the value is ignored; the teams reduction buffer is sized "
7208 "automatically at kernel launch";
7209 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7210 options::OPT_fno_openmp_optimistic_collapse,
7211 /*Default=*/false))
7212 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7213
7214 // When in OpenMP offloading mode with NVPTX target, forward
7215 // cuda-mode flag
7216 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7217 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7218 CmdArgs.push_back("-fopenmp-cuda-mode");
7219
7220 // When in OpenMP offloading mode, enable debugging on the device.
7221 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7222 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7223 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7224 CmdArgs.push_back("-fopenmp-target-debug");
7225
7226 // When in OpenMP offloading mode, forward assumptions information about
7227 // thread and team counts in the device.
7228 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7229 options::OPT_fno_openmp_assume_teams_oversubscription,
7230 /*Default=*/TargetFastUsed))
7231 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7232 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7233 options::OPT_fno_openmp_assume_threads_oversubscription,
7234 /*Default=*/TargetFastUsed))
7235 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7236
7237 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7238 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7239 options::OPT_fno_openmp_assume_no_thread_state,
7240 /*Default=*/TargetFastUsed))
7241 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7242
7243 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7244 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7245 options::OPT_fno_openmp_assume_no_nested_parallelism,
7246 /*Default=*/TargetFastUsed))
7247 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7248
7249 // Handle -fopenmp-target-atomic-reduction.
7250 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7251 options::OPT_fno_openmp_target_atomic_reduction,
7252 /*Default=*/false))
7253 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7254
7255 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7256 CmdArgs.push_back("-fopenmp-offload-mandatory");
7257 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7258 CmdArgs.push_back("-fopenmp-force-usm");
7259 break;
7260 default:
7261 // By default, if Clang doesn't know how to generate useful OpenMP code
7262 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7263 // down to the actual compilation.
7264 // FIXME: It would be better to have a mode which *only* omits IR
7265 // generation based on the OpenMP support so that we get consistent
7266 // semantic analysis, etc.
7267 break;
7268 }
7269 } else {
7270 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7271 options::OPT_fno_openmp_simd);
7272 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7273 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7274 options::OPT_fno_openmp_extensions);
7275 }
7276 // Forward '-foffload-via-llvm' to code generation to target the LLVM/Offload
7277 // runtime.
7278 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7279 options::OPT_fno_offload_via_llvm, false))
7280 CmdArgs.push_back("-foffload-via-llvm");
7281
7282 const XRayArgs &XRay = TC.getXRayArgs(Args);
7283 XRay.addArgs(TC, Args, CmdArgs, InputType);
7284
7285 for (const auto &Filename :
7286 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7287 if (D.getVFS().exists(Filename))
7288 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7289 else
7290 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7291 }
7292
7293 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7294 StringRef S0 = A->getValue(), S = S0;
7295 unsigned Size, Offset = 0;
7296 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7297 !Triple.isX86() && !Triple.isSystemZ() &&
7298 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7299 Triple.getArch() == llvm::Triple::ppc64 ||
7300 Triple.getArch() == llvm::Triple::ppc64le)))
7301 D.Diag(diag::err_drv_unsupported_opt_for_target)
7302 << A->getAsString(Args) << TripleStr;
7303 else if (S.consumeInteger(10, Size) ||
7304 (!S.empty() &&
7305 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7306 (!S.empty() && (!S.consume_front(",") || S.empty())))
7307 D.Diag(diag::err_drv_invalid_argument_to_option)
7308 << S0 << A->getOption().getName();
7309 else if (Size < Offset)
7310 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7311 else {
7312 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7313 CmdArgs.push_back(Args.MakeArgString(
7314 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7315 if (!S.empty())
7316 CmdArgs.push_back(
7317 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7318 }
7319 }
7320
7321 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7322
7323 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7324 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7325
7326 for (const auto &A :
7327 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7328 CmdArgs.push_back(
7329 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7330
7331 if (TC.SupportsProfiling()) {
7332 Args.AddLastArg(CmdArgs, options::OPT_pg);
7333
7334 llvm::Triple::ArchType Arch = TC.getArch();
7335 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7336 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7337 A->render(Args, CmdArgs);
7338 else
7339 D.Diag(diag::err_drv_unsupported_opt_for_target)
7340 << A->getAsString(Args) << TripleStr;
7341 }
7342 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7343 if (Arch == llvm::Triple::systemz ||
7344 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7345 A->render(Args, CmdArgs);
7346 else
7347 D.Diag(diag::err_drv_unsupported_opt_for_target)
7348 << A->getAsString(Args) << TripleStr;
7349 }
7350 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7351 if (Arch == llvm::Triple::systemz ||
7352 (TC.getTriple().isX86() && TC.getTriple().isOSBinFormatELF()))
7353 A->render(Args, CmdArgs);
7354 else
7355 D.Diag(diag::err_drv_unsupported_opt_for_target)
7356 << A->getAsString(Args) << TripleStr;
7357 }
7358 }
7359
7360 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7361 if (TC.getTriple().isOSzOS()) {
7362 D.Diag(diag::err_drv_unsupported_opt_for_target)
7363 << A->getAsString(Args) << TripleStr;
7364 }
7365 }
7366 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7367 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7368 D.Diag(diag::err_drv_unsupported_opt_for_target)
7369 << A->getAsString(Args) << TripleStr;
7370 }
7371 }
7372 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7373 if (A->getOption().matches(options::OPT_p)) {
7374 A->claim();
7375 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7376 CmdArgs.push_back("-pg");
7377 }
7378 }
7379
7380 // Reject AIX-specific link options on other targets.
7381 if (!TC.getTriple().isOSAIX()) {
7382 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7383 options::OPT_mxcoff_build_id_EQ)) {
7384 D.Diag(diag::err_drv_unsupported_opt_for_target)
7385 << A->getSpelling() << TripleStr;
7386 }
7387 }
7388
7389 if (Args.getLastArg(options::OPT_fapple_kext) ||
7390 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7391 CmdArgs.push_back("-fapple-kext");
7392
7393 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7394 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7395 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7396 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7397 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7398 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7399 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7400 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7401 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7402 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7403 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7404
7405 if (const char *Name = C.getTimeTraceFile(&JA)) {
7406 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7407 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7408 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7409 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_compress_EQ);
7410 }
7411
7412 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7413 CmdArgs.push_back("-ftrapv-handler");
7414 CmdArgs.push_back(A->getValue());
7415 }
7416
7417 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7418
7419 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7420 options::OPT_fno_finite_loops);
7421
7422 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7423 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7424 options::OPT_fno_unroll_loops);
7425 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7426 options::OPT_fno_loop_interchange);
7427 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7428 options::OPT_fno_experimental_loop_fusion);
7429
7430 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7431
7432 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7433
7434 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7435 options::OPT_mno_speculative_load_hardening);
7436
7437 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7438 RenderSCPOptions(TC, Args, CmdArgs);
7439 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7440
7441 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7442
7443 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7444 options::OPT_mno_stackrealign);
7445
7446 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7447 StringRef Value = A->getValue();
7448 int64_t Alignment = 0;
7449 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7450 D.Diag(diag::err_drv_invalid_argument_to_option)
7451 << Value << A->getOption().getName();
7452 else if (Alignment & (Alignment - 1))
7453 D.Diag(diag::err_drv_alignment_not_power_of_two)
7454 << A->getAsString(Args) << Value;
7455 else
7456 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7457 }
7458
7459 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7460 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7461
7462 if (!Size.empty())
7463 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7464 else
7465 CmdArgs.push_back("-mstack-probe-size=0");
7466 }
7467
7468 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7469 options::OPT_mno_stack_arg_probe);
7470
7471 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7472 options::OPT_mno_restrict_it)) {
7473 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7474 CmdArgs.push_back("-mllvm");
7475 CmdArgs.push_back("-arm-restrict-it");
7476 } else {
7477 CmdArgs.push_back("-mllvm");
7478 CmdArgs.push_back("-arm-default-it");
7479 }
7480 }
7481
7482 // Forward -cl options to -cc1
7483 RenderOpenCLOptions(Args, CmdArgs, InputType);
7484
7485 // Forward hlsl options to -cc1
7486 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7487
7488 // Forward OpenACC options to -cc1
7489 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7490
7491 if (IsHIP) {
7492 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7493 options::OPT_fno_hip_new_launch_api, true))
7494 CmdArgs.push_back("-fhip-new-launch-api");
7495 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7496 options::OPT_fno_gpu_allow_device_init);
7497 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7498 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7499 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7500 options::OPT_fno_hip_kernel_arg_name);
7501 if (TC.getTriple().isSPIRV() &&
7502 TC.getTriple().getVendor() == llvm::Triple::VendorType::AMD)
7503 Args.addLastArg(CmdArgs, options::OPT_fenable_spirv_size_optimization);
7504 }
7505
7506 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7507 CmdArgs.push_back("-fgpu-rdc");
7508
7509 if (IsCuda || IsHIP) {
7510 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7511 options::OPT_fno_gpu_defer_diag);
7512 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7513 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7514 false)) {
7515 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7516 CmdArgs.push_back("-fgpu-defer-diag");
7517 }
7518 }
7519
7520 // Forward --no-offloadlib to -cc1.
7521 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7522 CmdArgs.push_back("--no-offloadlib");
7523
7524 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7525 CmdArgs.push_back(
7526 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7527
7528 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7529 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7530 SA->getValue()));
7531 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7532 // Emit IBT endbr64 instructions by default
7533 CmdArgs.push_back("-fcf-protection=branch");
7534 // jump-table can generate indirect jumps, which are not permitted
7535 CmdArgs.push_back("-fno-jump-tables");
7536 }
7537
7538 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7539 CmdArgs.push_back(
7540 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7541
7542 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7543
7544 // Forward -f options with positive and negative forms; we translate these by
7545 // hand. Do not propagate PGO options to the GPU-side compilations as the
7546 // profile info is for the host-side compilation only.
7547 if (!(IsCudaDevice || IsHIPDevice)) {
7548 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7549 auto *PGOArg = Args.getLastArg(
7550 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7551 options::OPT_fcs_profile_generate,
7552 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7553 options::OPT_fprofile_use_EQ);
7554 if (PGOArg)
7555 D.Diag(diag::err_drv_argument_not_allowed_with)
7556 << "SampleUse with PGO options";
7557
7558 StringRef fname = A->getValue();
7559 if (!llvm::sys::fs::exists(fname))
7560 D.Diag(diag::err_drv_no_such_file) << fname;
7561 else
7562 A->render(Args, CmdArgs);
7563 }
7564 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7565
7566 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7567 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7568 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7569 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7570 // off.
7571 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7572 options::OPT_fno_unique_internal_linkage_names, true))
7573 CmdArgs.push_back("-funique-internal-linkage-names");
7574 }
7575 }
7576 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7577
7578 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7579 options::OPT_fno_assume_sane_operator_new);
7580
7581 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7582 CmdArgs.push_back("-fapinotes");
7583 if (Args.hasFlag(options::OPT_fapinotes_modules,
7584 options::OPT_fno_apinotes_modules, false))
7585 CmdArgs.push_back("-fapinotes-modules");
7586 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7587
7588 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7589 options::OPT_fno_swift_version_independent_apinotes, false))
7590 CmdArgs.push_back("-fswift-version-independent-apinotes");
7591
7592 // -fblocks=0 is default.
7593 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7594 TC.IsBlocksDefault()) ||
7595 (Args.hasArg(options::OPT_fgnu_runtime) &&
7596 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7597 !Args.hasArg(options::OPT_fno_blocks))) {
7598 CmdArgs.push_back("-fblocks");
7599
7600 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7601 CmdArgs.push_back("-fblocks-runtime-optional");
7602 }
7603
7604 // -fencode-extended-block-signature=1 is default.
7606 CmdArgs.push_back("-fencode-extended-block-signature");
7607
7608 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7609 options::OPT_fno_coro_aligned_allocation, false) &&
7610 types::isCXX(InputType))
7611 CmdArgs.push_back("-fcoro-aligned-allocation");
7612
7613 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7614 /*Default=*/false))
7615 CmdArgs.push_back("-fdefer-ts");
7616
7617 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7618 options::OPT_fno_double_square_bracket_attributes);
7619
7620 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7621 options::OPT_fno_access_control);
7622 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7623 options::OPT_fno_elide_constructors);
7624
7625 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7626
7627 if (KernelOrKext || (types::isCXX(InputType) &&
7628 (RTTIMode == ToolChain::RM_Disabled)))
7629 CmdArgs.push_back("-fno-rtti");
7630
7631 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7632 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7633 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7634 CmdArgs.push_back("-fshort-enums");
7635
7636 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7637
7638 // -fuse-cxa-atexit is default.
7639 if (!Args.hasFlag(
7640 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7641 !RawTriple.isOSAIX() &&
7642 (!RawTriple.isOSWindows() ||
7643 RawTriple.isWindowsCygwinEnvironment()) &&
7644 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7645 RawTriple.hasEnvironment())) ||
7646 KernelOrKext)
7647 CmdArgs.push_back("-fno-use-cxa-atexit");
7648
7649 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7650 options::OPT_fno_register_global_dtors_with_atexit,
7651 RawTriple.isOSDarwin() && !KernelOrKext))
7652 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7653
7654 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7655 options::OPT_fno_use_line_directives);
7656
7657 // -fno-minimize-whitespace is default.
7658 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7659 options::OPT_fno_minimize_whitespace, false)) {
7660 types::ID InputType = Inputs[0].getType();
7661 if (!isDerivedFromC(InputType))
7662 D.Diag(diag::err_drv_opt_unsupported_input_type)
7663 << "-fminimize-whitespace" << types::getTypeName(InputType);
7664 CmdArgs.push_back("-fminimize-whitespace");
7665 }
7666
7667 // -fno-keep-system-includes is default.
7668 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7669 options::OPT_fno_keep_system_includes, false)) {
7670 types::ID InputType = Inputs[0].getType();
7671 if (!isDerivedFromC(InputType))
7672 D.Diag(diag::err_drv_opt_unsupported_input_type)
7673 << "-fkeep-system-includes" << types::getTypeName(InputType);
7674 CmdArgs.push_back("-fkeep-system-includes");
7675 }
7676
7677 // -fms-extensions=0 is default.
7678 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7679 IsWindowsMSVC || IsUEFI))
7680 CmdArgs.push_back("-fms-extensions");
7681
7682 // -fms-compatibility=0 is default.
7683 bool IsMSVCCompat = Args.hasFlag(
7684 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7685 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7686 options::OPT_fno_ms_extensions, true)));
7687 if (IsMSVCCompat) {
7688 CmdArgs.push_back("-fms-compatibility");
7689 if (!types::isCXX(Input.getType()) &&
7690 Args.hasArg(options::OPT_fms_define_stdc))
7691 CmdArgs.push_back("-fms-define-stdc");
7692 }
7693
7694 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7695 // clang and flang.
7696 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7697
7698 // -fms-anonymous-structs is disabled by default.
7699 // Determine whether to enable Microsoft named anonymous struct/union support.
7700 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7701 // where the feature can be:
7702 // - Explicitly enabled via -fms-anonymous-structs.
7703 // - Explicitly disabled via fno-ms-anonymous-structs
7704 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7705 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7706 //
7707 // When multiple relevent options are present, the last option on the command
7708 // line takes precedence. This allows users to selectively override implicit
7709 // enablement. Examples:
7710 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7711 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7712 auto MSAnonymousStructsOptionToUseOrNull =
7713 [](const ArgList &Args) -> const char * {
7714 const char *Option = nullptr;
7715 constexpr const char *Enable = "-fms-anonymous-structs";
7716 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7717
7718 // Iterate through all arguments in order to implement "last flag wins".
7719 for (const Arg *A : Args) {
7720 switch (A->getOption().getID()) {
7721 case options::OPT_fms_anonymous_structs:
7722 A->claim();
7723 Option = Enable;
7724 break;
7725 case options::OPT_fno_ms_anonymous_structs:
7726 A->claim();
7727 Option = Disable;
7728 break;
7729 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7730 // feature.
7731 case options::OPT_fms_extensions:
7732 case options::OPT_fms_compatibility:
7733 Option = Enable;
7734 break;
7735 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7736 // disables the feature.
7737 case options::OPT_fno_ms_extensions:
7738 case options::OPT_fno_ms_compatibility:
7739 Option = Disable;
7740 break;
7741 default:
7742 break;
7743 }
7744 }
7745 return Option;
7746 };
7747
7748 // Only pass a flag to CC1 if a relevant option was seen
7749 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7750 CmdArgs.push_back(MSAnonOpt);
7751
7752 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7753 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7754 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7755
7756 // Handle -fgcc-version, if present.
7757 VersionTuple GNUCVer;
7758 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7759 // Check that the version has 1 to 3 components and the minor and patch
7760 // versions fit in two decimal digits.
7761 StringRef Val = A->getValue();
7762 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7763 bool Invalid = GNUCVer.tryParse(Val);
7764 unsigned Minor = GNUCVer.getMinor().value_or(0);
7765 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7766 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7767 D.Diag(diag::err_drv_invalid_value)
7768 << A->getAsString(Args) << A->getValue();
7769 }
7770 } else if (!IsMSVCCompat) {
7771 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7772 GNUCVer = VersionTuple(4, 2, 1);
7773 }
7774 if (!GNUCVer.empty()) {
7775 CmdArgs.push_back(
7776 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7777 }
7778
7779 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7780 if (!MSVT.empty())
7781 CmdArgs.push_back(
7782 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7783
7784 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7785 if (ImplyVCPPCVer) {
7786 StringRef LanguageStandard;
7787 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7788 Std = StdArg;
7789 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7790 .Case("c11", "-std=c11")
7791 .Case("c17", "-std=c17")
7792 // If you add cases below for spellings that are
7793 // not in LangStandards.def, update
7794 // TransferableCommand::tryParseStdArg() in
7795 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7796 // to match.
7797 // TODO: add c23 when MSVC supports it.
7798 .Case("clatest", "-std=c23")
7799 .Default("");
7800 if (LanguageStandard.empty())
7801 D.Diag(clang::diag::warn_drv_unused_argument)
7802 << StdArg->getAsString(Args);
7803 }
7804 CmdArgs.push_back(LanguageStandard.data());
7805 }
7806 if (ImplyVCPPCXXVer) {
7807 StringRef LanguageStandard;
7808 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7809 Std = StdArg;
7810 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7811 .Case("c++14", "-std=c++14")
7812 .Case("c++17", "-std=c++17")
7813 .Case("c++20", "-std=c++20")
7814 .Case("c++23", "-std=c++23")
7815 // If you add cases below for spellings that are
7816 // not in LangStandards.def, update
7817 // TransferableCommand::tryParseStdArg() in
7818 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7819 // to match.
7820 // TODO add c++26, c++29 when MSVC supports
7821 // it.
7822 .Case("c++23preview", "-std=c++23")
7823 .Case("c++26preview", "-std=c++26")
7824 .Case("c++latest", "-std=c++2d")
7825 .Default("");
7826 if (IsSYCL) {
7827 const LangStandard *LangStd =
7828 LangStandard::getLangStandardForName(StdArg->getValue());
7829 if (LangStd) {
7830 // Use of /std: with 'C' is not supported for SYCL.
7831 if (LangStd->getLanguage() == Language::C)
7832 D.Diag(diag::err_drv_argument_not_allowed_with)
7833 << StdArg->getAsString(Args) << "-fsycl";
7834 // SYCL requires C++17 or later.
7835 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7836 D.Diag(diag::err_drv_sycl_requires_cxx17)
7837 << StdArg->getAsString(Args);
7838 }
7839 }
7840 if (LanguageStandard.empty())
7841 D.Diag(clang::diag::warn_drv_unused_argument)
7842 << StdArg->getAsString(Args);
7843 }
7844
7845 if (LanguageStandard.empty()) {
7846 if (IsSYCL)
7847 // For SYCL, C++17 is the default.
7848 LanguageStandard = "-std=c++17";
7849 else if (IsMSVC2015Compatible)
7850 LanguageStandard = "-std=c++14";
7851 else
7852 LanguageStandard = "-std=c++11";
7853 }
7854
7855 CmdArgs.push_back(LanguageStandard.data());
7856 }
7857
7858 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7859 options::OPT_fno_borland_extensions);
7860
7861 // -fno-declspec is default, except for PS4/PS5.
7862 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7863 RawTriple.isPS()))
7864 CmdArgs.push_back("-fdeclspec");
7865 else if (Args.hasArg(options::OPT_fno_declspec))
7866 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7867
7868 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7869 // than 19.
7870 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7871 options::OPT_fno_threadsafe_statics,
7872 !types::isOpenCL(InputType) &&
7873 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7874 CmdArgs.push_back("-fno-threadsafe-statics");
7875
7876 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7877 true))
7878 CmdArgs.push_back("-fno-ms-tls-guards");
7879
7880 // Add -fno-assumptions, if it was specified.
7881 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7882 true))
7883 CmdArgs.push_back("-fno-assumptions");
7884
7885 // -fgnu-keywords default varies depending on language; only pass if
7886 // specified.
7887 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7888 options::OPT_fno_gnu_keywords);
7889
7890 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7891 options::OPT_fno_gnu89_inline);
7892
7893 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7894 options::OPT_finline_hint_functions,
7895 options::OPT_fno_inline_functions);
7896 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7897 if (A->getOption().matches(options::OPT_fno_inline))
7898 A->render(Args, CmdArgs);
7899 } else if (InlineArg) {
7900 InlineArg->render(Args, CmdArgs);
7901 }
7902
7903 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7904
7905 // FIXME: Find a better way to determine whether we are in C++20.
7906 bool HaveCxx20 =
7907 Std &&
7908 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7909 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7910 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7911 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7912 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7913 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7914 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7915 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7916 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7917 bool HaveModules =
7918 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7919
7920 // -fdelayed-template-parsing is default when targeting MSVC.
7921 // Many old Windows SDK versions require this to parse.
7922 //
7923 // According to
7924 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7925 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7926 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7927 // not enable -fdelayed-template-parsing by default after C++20.
7928 //
7929 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7930 // able to disable this by default at some point.
7931 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7932 options::OPT_fno_delayed_template_parsing,
7933 IsWindowsMSVC && !HaveCxx20)) {
7934 if (HaveCxx20)
7935 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7936
7937 CmdArgs.push_back("-fdelayed-template-parsing");
7938 }
7939
7940 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7941 options::OPT_fno_pch_validate_input_files_content, false))
7942 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7943 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7944 options::OPT_fno_pch_instantiate_templates, false))
7945 CmdArgs.push_back("-fpch-instantiate-templates");
7946 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7947 false))
7948 CmdArgs.push_back("-fmodules-codegen");
7949 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7950 false))
7951 CmdArgs.push_back("-fmodules-debuginfo");
7952
7953 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7954 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7955 Input, CmdArgs);
7956
7957 if (types::isObjC(Input.getType()) &&
7958 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7959 options::OPT_fno_objc_encode_cxx_class_template_spec,
7960 !Runtime.isNeXTFamily()))
7961 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7962
7963 if (Args.hasFlag(options::OPT_fapplication_extension,
7964 options::OPT_fno_application_extension, false))
7965 CmdArgs.push_back("-fapplication-extension");
7966
7967 // Handle GCC-style exception args.
7968 bool EH = false;
7969 if (!C.getDriver().IsCLMode())
7970 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7971 IsDeviceOffloadAction, Runtime, CmdArgs);
7972
7973 // Handle exception personalities
7974 Arg *A = Args.getLastArg(
7975 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7976 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions,
7977 options::OPT_femscripten_exceptions);
7978 if (A) {
7979 const Option &Opt = A->getOption();
7980 if (Opt.matches(options::OPT_fsjlj_exceptions))
7981 CmdArgs.push_back("-exception-model=sjlj");
7982 if (Opt.matches(options::OPT_fseh_exceptions))
7983 CmdArgs.push_back("-exception-model=seh");
7984 if (Opt.matches(options::OPT_fdwarf_exceptions))
7985 CmdArgs.push_back("-exception-model=dwarf");
7986 if (Opt.matches(options::OPT_fwasm_exceptions))
7987 CmdArgs.push_back("-exception-model=wasm");
7988 if (Opt.matches(options::OPT_femscripten_exceptions))
7989 CmdArgs.push_back("-exception-model=emscripten");
7990 } else {
7991 switch (TC.GetExceptionModel(Args)) {
7992 default:
7993 break;
7994 case llvm::ExceptionHandling::DwarfCFI:
7995 CmdArgs.push_back("-exception-model=dwarf");
7996 break;
7997 case llvm::ExceptionHandling::SjLj:
7998 CmdArgs.push_back("-exception-model=sjlj");
7999 break;
8000 case llvm::ExceptionHandling::WinEH:
8001 CmdArgs.push_back("-exception-model=seh");
8002 break;
8003 }
8004 }
8005
8006 // Unwind information version for x64 Windows.
8007 // Forward the new unified flag if present, otherwise translate legacy flags.
8008 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
8009 A->claim();
8010 CmdArgs.push_back(
8011 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
8012 } else if (const Arg *A =
8013 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
8014 A->claim();
8015 StringRef Val = A->getValue();
8016 if (Val == "best-effort")
8017 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
8018 else if (Val == "required")
8019 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
8020 // "disabled" maps to v1 default, nothing to forward.
8021 else if (Val != "disabled")
8022 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
8023 }
8024
8025 // Control Flow Guard mechanism for Windows.
8026 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
8027
8028 // C++ "sane" operator new.
8029 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
8030 options::OPT_fno_assume_sane_operator_new);
8031
8032 // -fassume-unique-vtables is on by default.
8033 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
8034 options::OPT_fno_assume_unique_vtables);
8035
8036 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
8037 // by default.
8038 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
8039 options::OPT_fno_sized_deallocation);
8040
8041 // -faligned-allocation is on by default in C++17 onwards and otherwise off
8042 // by default.
8043 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
8044 options::OPT_fno_aligned_allocation,
8045 options::OPT_faligned_new_EQ)) {
8046 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
8047 CmdArgs.push_back("-fno-aligned-allocation");
8048 else
8049 CmdArgs.push_back("-faligned-allocation");
8050 }
8051
8052 // The default new alignment can be specified using a dedicated option or via
8053 // a GCC-compatible option that also turns on aligned allocation.
8054 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
8055 options::OPT_faligned_new_EQ))
8056 CmdArgs.push_back(
8057 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
8058
8059 // -fconstant-cfstrings is default, and may be subject to argument translation
8060 // on Darwin.
8061 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
8062 options::OPT_fno_constant_cfstrings, true) ||
8063 !Args.hasFlag(options::OPT_mconstant_cfstrings,
8064 options::OPT_mno_constant_cfstrings, true))
8065 CmdArgs.push_back("-fno-constant-cfstrings");
8066
8067 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
8068 options::OPT_fno_pascal_strings);
8069
8070 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8071 // -fno-pack-struct doesn't apply to -fpack-struct=.
8072 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
8073 CmdArgs.push_back(
8074 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
8075 } else if (Args.hasFlag(options::OPT_fpack_struct,
8076 options::OPT_fno_pack_struct, false)) {
8077 CmdArgs.push_back("-fpack-struct=1");
8078 }
8079
8080 // Handle -fmax-type-align=N and -fno-type-align
8081 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
8082 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
8083 if (!SkipMaxTypeAlign) {
8084 std::string MaxTypeAlignStr = "-fmax-type-align=";
8085 MaxTypeAlignStr += A->getValue();
8086 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8087 }
8088 } else if (RawTriple.isOSDarwin()) {
8089 if (!SkipMaxTypeAlign) {
8090 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8091 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8092 }
8093 }
8094
8095 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
8096 CmdArgs.push_back("-Qn");
8097
8098 // -fno-common is the default, set -fcommon only when that flag is set.
8099 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
8100
8101 // -fsigned-bitfields is default, and clang doesn't yet support
8102 // -funsigned-bitfields.
8103 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
8104 options::OPT_funsigned_bitfields, true))
8105 D.Diag(diag::warn_drv_clang_unsupported)
8106 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
8107
8108 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8109 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
8110 D.Diag(diag::err_drv_clang_unsupported)
8111 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
8112
8113 // -finput_charset=UTF-8 is default. Reject others
8114 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
8115 StringRef value = inputCharset->getValue();
8116 if (!value.equals_insensitive("utf-8"))
8117 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8118 << value;
8119 }
8120
8121 // -fexec_charset=UTF-8 is default. Reject others
8122 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8123 StringRef value = execCharset->getValue();
8124 if (!value.equals_insensitive("utf-8"))
8125 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8126 << value;
8127 }
8128
8129 RenderDiagnosticsOptions(D, Args, CmdArgs);
8130
8131 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8132 options::OPT_fno_asm_blocks);
8133
8134 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8135 options::OPT_fno_gnu_inline_asm);
8136
8137 handleVectorizeLoopsArgs(Args, CmdArgs);
8138 handleVectorizeSLPArgs(Args, CmdArgs);
8139
8140 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8141 if (!VecWidth.empty())
8142 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8143
8144 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8145 Args.AddLastArg(CmdArgs,
8146 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8147
8148 // -fdollars-in-identifiers default varies depending on platform and
8149 // language; only pass if specified.
8150 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8151 options::OPT_fno_dollars_in_identifiers)) {
8152 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8153 CmdArgs.push_back("-fdollars-in-identifiers");
8154 else
8155 CmdArgs.push_back("-fno-dollars-in-identifiers");
8156 }
8157
8158 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8159 options::OPT_fno_apple_pragma_pack);
8160
8161 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8162 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8163 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8164
8165 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8166 options::OPT_fno_rewrite_imports, false);
8167 if (RewriteImports)
8168 CmdArgs.push_back("-frewrite-imports");
8169
8170 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8171 options::OPT_fno_directives_only);
8172
8173 // Enable rewrite includes if the user's asked for it or if we're generating
8174 // diagnostics.
8175 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8176 // nice to enable this when doing a crashdump for modules as well.
8177 if (Args.hasFlag(options::OPT_frewrite_includes,
8178 options::OPT_fno_rewrite_includes, false) ||
8179 (C.isForDiagnostics() && !HaveModules))
8180 CmdArgs.push_back("-frewrite-includes");
8181
8182 if (Args.hasFlag(options::OPT_fzos_extensions,
8183 options::OPT_fno_zos_extensions, false))
8184 CmdArgs.push_back("-fzos-extensions");
8185 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8186 CmdArgs.push_back("-fno-zos-extensions");
8187
8188 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8189 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8190 options::OPT_traditional_cpp)) {
8192 CmdArgs.push_back("-traditional-cpp");
8193 else
8194 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8195 }
8196
8197 Args.AddLastArg(CmdArgs, options::OPT_dM);
8198 Args.AddLastArg(CmdArgs, options::OPT_dD);
8199 Args.AddLastArg(CmdArgs, options::OPT_dI);
8200
8201 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8202
8203 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8204 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8205 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8206 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8207 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8208 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8209 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8210 Args.AddLastArg(CmdArgs, options::OPT__ssaf_link_unit_id);
8211 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8212 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8213
8214 // Handle serialized diagnostics.
8215 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8216 CmdArgs.push_back("-serialize-diagnostic-file");
8217 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8218 }
8219
8220 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8221 CmdArgs.push_back("-fretain-comments-from-system-headers");
8222
8223 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8224 A->render(Args, CmdArgs);
8225 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8226 A && A->containsValue("g")) {
8227 // Set -fextend-variable-liveness=all by default at -Og.
8228 CmdArgs.push_back("-fextend-variable-liveness=all");
8229 }
8230
8231 // Forward -fcomment-block-commands to -cc1.
8232 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8233 // Forward -fparse-all-comments to -cc1.
8234 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8235 // Forward -fretain-comments to -cc1.
8236 Args.AddAllArgs(CmdArgs, options::OPT_fretain_comments);
8237
8238 // Turn -fplugin=name.so into -load name.so
8239 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8240 CmdArgs.push_back("-load");
8241 CmdArgs.push_back(A->getValue());
8242 A->claim();
8243 }
8244
8245 // Turn -fplugin-arg-pluginname-key=value into
8246 // -plugin-arg-pluginname key=value
8247 // GCC has an actual plugin_argument struct with key/value pairs that it
8248 // passes to its plugins, but we don't, so just pass it on as-is.
8249 //
8250 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8251 // argument key are allowed to contain dashes. GCC therefore only
8252 // allows dashes in the key. We do the same.
8253 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8254 auto ArgValue = StringRef(A->getValue());
8255 auto FirstDashIndex = ArgValue.find('-');
8256 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8257 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8258
8259 A->claim();
8260 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8261 if (PluginName.empty()) {
8262 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8263 } else {
8264 D.Diag(diag::warn_drv_missing_plugin_arg)
8265 << PluginName << A->getAsString(Args);
8266 }
8267 continue;
8268 }
8269
8270 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8271 CmdArgs.push_back(Args.MakeArgString(Arg));
8272 }
8273
8274 // Forward -fpass-plugin=name.so to -cc1.
8275 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8276 CmdArgs.push_back(
8277 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8278 A->claim();
8279 }
8280
8281 // Forward --vfsoverlay to -cc1.
8282 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8283 CmdArgs.push_back("--vfsoverlay");
8284 CmdArgs.push_back(A->getValue());
8285 A->claim();
8286 }
8287
8288 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8289 options::OPT_fno_safe_buffer_usage_suggestions);
8290
8291 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8292 options::OPT_fno_experimental_late_parse_attributes);
8293
8294 if (Args.hasFlag(options::OPT_funique_source_file_names,
8295 options::OPT_fno_unique_source_file_names, false)) {
8296 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8297 A->render(Args, CmdArgs);
8298 else
8299 CmdArgs.push_back(Args.MakeArgString(
8300 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8301 }
8302
8303 if (Args.hasFlag(
8304 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8305 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8306 false) ||
8307 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8308 options::OPT_fno_experimental_pointer_field_protection_abi,
8309 false))
8310 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8311
8312 if (!IsCudaDevice) {
8313 Args.addOptInFlag(
8314 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8315 options::OPT_fno_experimental_pointer_field_protection_abi);
8316 Args.addOptInFlag(
8317 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8318 options::OPT_fno_experimental_pointer_field_protection_tagged);
8319 }
8320
8321 // Setup statistics file output.
8322 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8323 if (!StatsFile.empty()) {
8324 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8326 CmdArgs.push_back("-stats-file-append");
8327 }
8328
8329 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8330 // parser.
8331 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8332 Arg->claim();
8333 // -finclude-default-header flag is for preprocessor,
8334 // do not pass it to other cc1 commands when save-temps is enabled
8335 if (C.getDriver().isSaveTempsEnabled() &&
8337 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8338 continue;
8339 }
8340 CmdArgs.push_back(Arg->getValue());
8341 }
8342 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8343 A->claim();
8344
8345 // We translate this by hand to the -cc1 argument, since nightly test uses
8346 // it and developers have been trained to spell it with -mllvm. Both
8347 // spellings are now deprecated and should be removed.
8348 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8349 CmdArgs.push_back("-disable-llvm-optzns");
8350 } else {
8351 A->render(Args, CmdArgs);
8352 }
8353 }
8354
8355 // This needs to run after -Xclang argument forwarding to pick up the target
8356 // features enabled through -Xclang -target-feature flags.
8357 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8358
8359 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8360
8361#if CLANG_ENABLE_CIR
8362 // Forward -mmlir arguments to to the MLIR option parser.
8363 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8364 A->claim();
8365 A->render(Args, CmdArgs);
8366 }
8367#endif // CLANG_ENABLE_CIR
8368
8369 // With -save-temps, we want to save the unoptimized bitcode output from the
8370 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8371 // by the frontend.
8372 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8373 // has slightly different breakdown between stages.
8374 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8375 // pristine IR generated by the frontend. Ideally, a new compile action should
8376 // be added so both IR can be captured.
8377 if ((C.getDriver().isSaveTempsEnabled() ||
8379 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8381 CmdArgs.push_back("-disable-llvm-passes");
8382
8383 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8384
8385 const char *Exec = D.getDriverProgramPath();
8386
8387 // Optionally embed the -cc1 level arguments into the debug info or a
8388 // section, for build analysis.
8389 // Also record command line arguments into the debug info if
8390 // -grecord-gcc-switches options is set on.
8391 // By default, -gno-record-gcc-switches is set on and no recording.
8392 auto GRecordSwitches = false;
8393 auto FRecordSwitches = false;
8394 bool DXRecordSwitches = false;
8395 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8396 DXRecordSwitches)) {
8397 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8398 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8399 CmdArgs.push_back("-dwarf-debug-flags");
8400 CmdArgs.push_back(FlagsArgString);
8401 }
8402 if (FRecordSwitches) {
8403 CmdArgs.push_back("-record-command-line");
8404 CmdArgs.push_back(FlagsArgString);
8405 }
8406 if (DXRecordSwitches) {
8407 CmdArgs.push_back("-fdx-record-command-line");
8408 CmdArgs.push_back(FlagsArgString);
8409 }
8410 }
8411
8412 // Host-side offloading compilation receives all device-side outputs. Include
8413 // them in the host compilation depending on the target.
8414 if (!HostOffloadingInputs.empty()) {
8415 bool UseOffloadIncludeBinary =
8416 (IsCuda || IsHIP) &&
8417 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi)) &&
8418 !UsesLLVMOffloading;
8419 UseOffloadIncludeBinary |= IsSYCL && !IsRDCMode;
8420 if (UseOffloadIncludeBinary) {
8421 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8422 CmdArgs.push_back("-foffload-include-binary");
8423 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8424 } else {
8425 for (const InputInfo Input : HostOffloadingInputs)
8426 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8427 TC.getInputFilename(Input)));
8428 }
8429 }
8430
8431 if (IsCuda) {
8432 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8433 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8434 }
8435
8436 if (IsCuda || IsHIP) {
8437 // Determine the original source input.
8438 const Action *SourceAction = &JA;
8439 while (SourceAction->getKind() != Action::InputClass) {
8440 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8441 SourceAction = SourceAction->getInputs()[0];
8442 }
8443 auto CUID = cast<InputAction>(SourceAction)->getId();
8444 if (!CUID.empty())
8445 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8446
8447 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8448 // be overriden by -fno-gpu-approx-transcendentals.
8449 bool UseApproxTranscendentals = Args.hasFlag(
8450 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8451 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8452 options::OPT_fno_gpu_approx_transcendentals,
8453 UseApproxTranscendentals))
8454 CmdArgs.push_back("-fgpu-approx-transcendentals");
8455 } else {
8456 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8457 options::OPT_fno_gpu_approx_transcendentals);
8458 }
8459
8460 if (IsHIP) {
8461 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8462 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8463 }
8464
8465 Args.AddAllArgs(CmdArgs,
8466 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8467
8468 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8469 options::OPT_fno_offload_uniform_block);
8470
8471 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8472 options::OPT_fno_offload_implicit_host_device_templates);
8473
8474 if (IsCudaDevice || IsHIPDevice) {
8475 StringRef InlineThresh =
8476 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8477 if (!InlineThresh.empty()) {
8478 std::string ArgStr =
8479 std::string("-inline-threshold=") + InlineThresh.str();
8480 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8481 }
8482 }
8483
8484 if (IsHIPDevice)
8485 Args.addOptOutFlag(CmdArgs,
8486 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8487 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8488
8489 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8490 // to specify the result of the compile phase on the host, so the meaningful
8491 // device declarations can be identified. Also, -fopenmp-is-target-device is
8492 // passed along to tell the frontend that it is generating code for a device,
8493 // so that only the relevant declarations are emitted.
8494 if (IsOpenMPDevice) {
8495 CmdArgs.push_back("-fopenmp-is-target-device");
8496 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8497 if (Args.hasArg(options::OPT_foffload_via_llvm))
8498 CmdArgs.push_back("-fcuda-is-device");
8499
8500 if (OpenMPDeviceInput) {
8501 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8502 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8503 }
8504 }
8505
8506 if (Triple.isAMDGPU() ||
8507 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8508 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8509
8510 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8511 options::OPT_mno_unsafe_fp_atomics);
8512 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8513 options::OPT_mno_amdgpu_ieee);
8514 }
8515
8516 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8517
8518 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8519 options::OPT_fno_devirtualize_speculatively,
8520 /*Default value*/ false))
8521 CmdArgs.push_back("-fdevirtualize-speculatively");
8522
8523 bool VirtualFunctionElimination =
8524 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8525 options::OPT_fno_virtual_function_elimination, false);
8526 if (VirtualFunctionElimination) {
8527 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8528 // in the future).
8529 if (LTOMode != LTOK_Full)
8530 D.Diag(diag::err_drv_argument_only_allowed_with)
8531 << "-fvirtual-function-elimination"
8532 << "-flto=full";
8533
8534 CmdArgs.push_back("-fvirtual-function-elimination");
8535 }
8536
8537 // VFE requires whole-program-vtables, and enables it by default.
8538 bool WholeProgramVTables = Args.hasFlag(
8539 options::OPT_fwhole_program_vtables,
8540 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8541 if (VirtualFunctionElimination && !WholeProgramVTables) {
8542 D.Diag(diag::err_drv_argument_not_allowed_with)
8543 << "-fno-whole-program-vtables"
8544 << "-fvirtual-function-elimination";
8545 }
8546
8547 if (WholeProgramVTables) {
8548 // PS4 uses the legacy LTO API, which does not support this feature in
8549 // ThinLTO mode.
8550 bool IsPS4 = getToolChain().getTriple().isPS4();
8551
8552 // Check if we passed LTO options but they were suppressed because this is a
8553 // device offloading action, or we passed device offload LTO options which
8554 // were suppressed because this is not the device offload action.
8555 // Check if we are using PS4 in regular LTO mode.
8556 // Otherwise, issue an error.
8557
8558 auto OtherLTOMode = TC.getLTOMode(
8559 Args, IsDeviceOffloadAction ? Action::OFK_None
8560 : static_cast<Action::OffloadKind>(
8561 C.getActiveOffloadKinds()));
8562 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8563
8564 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8565 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8566 D.Diag(diag::err_drv_argument_only_allowed_with)
8567 << "-fwhole-program-vtables"
8568 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8569
8570 // Propagate -fwhole-program-vtables if this is an LTO compile.
8571 if (IsUsingLTO)
8572 CmdArgs.push_back("-fwhole-program-vtables");
8573 }
8574
8575 bool DefaultsSplitLTOUnit =
8576 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8577 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8578 (!Triple.isPS4() && UnifiedLTO);
8579 bool SplitLTOUnit =
8580 Args.hasFlag(options::OPT_fsplit_lto_unit,
8581 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8582 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8583 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8584 << "-fsanitize=cfi";
8585 if (SplitLTOUnit)
8586 CmdArgs.push_back("-fsplit-lto-unit");
8587
8588 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8589 options::OPT_fno_fat_lto_objects)) {
8590 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8591 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8592 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8593 D.Diag(diag::err_drv_unsupported_opt_for_target)
8594 << A->getAsString(Args) << TC.getTripleString();
8595 }
8596 CmdArgs.push_back(Args.MakeArgString(
8597 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8598 CmdArgs.push_back("-flto-unit");
8599 CmdArgs.push_back("-ffat-lto-objects");
8600 A->render(Args, CmdArgs);
8601 }
8602 }
8603
8604 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8605
8606 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8607 options::OPT_fno_force_enable_int128)) {
8608 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8609 CmdArgs.push_back("-fforce-enable-int128");
8610 }
8611
8612 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8613 options::OPT_fno_keep_static_consts);
8614 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8615 options::OPT_fno_keep_persistent_storage_variables);
8616 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_inline_functions,
8617 options::OPT_fno_keep_inline_functions);
8618 Args.addOptInFlag(CmdArgs, options::OPT_fmodule_local_hints,
8619 options::OPT_fno_module_local_hints);
8620 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8621 options::OPT_fno_complete_member_pointers);
8622 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8623 A->render(Args, CmdArgs);
8624
8625 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8626
8627 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8628
8629 if (Triple.isAArch64() &&
8630 (Args.hasArg(options::OPT_mno_fmv) ||
8631 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8632 // Disable Function Multiversioning on AArch64 target.
8633 CmdArgs.push_back("-target-feature");
8634 CmdArgs.push_back("-fmv");
8635 }
8636
8637 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8638 (TC.getTriple().isOSBinFormatELF() ||
8639 TC.getTriple().isOSBinFormatCOFF()) &&
8640 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8641 !TC.getTriple().isOSNetBSD() &&
8642 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8643 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8644 CmdArgs.push_back("-faddrsig");
8645
8646 const bool HasDefaultDwarf2CFIASM =
8647 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8648 (EH || UnwindTables || AsyncUnwindTables ||
8649 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8650 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8651 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8652 CmdArgs.push_back("-fdwarf2-cfi-asm");
8653
8654 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8655 std::string Str = A->getAsString(Args);
8656 if (!TC.getTriple().isOSBinFormatELF())
8657 D.Diag(diag::err_drv_unsupported_opt_for_target)
8658 << Str << TC.getTripleString();
8659 CmdArgs.push_back(Args.MakeArgString(Str));
8660 }
8661
8662 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8663 // the -cc1 command easier to edit when reproducing compiler crashes.
8664 if (Output.getType() == types::TY_Dependencies) {
8665 // Handled with other dependency code.
8666 } else if (Output.isFilename()) {
8667 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8668 Output.getType() == clang::driver::types::TY_IFS) {
8669 SmallString<128> OutputFilename(Output.getFilename());
8670 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8671 CmdArgs.push_back("-o");
8672 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8673 } else {
8674 CmdArgs.push_back("-o");
8675 CmdArgs.push_back(Output.getFilename());
8676 }
8677 } else {
8678 assert(Output.isNothing() && "Invalid output.");
8679 }
8680
8681 addDashXForInput(Args, Input, CmdArgs);
8682
8683 ArrayRef<InputInfo> FrontendInputs = Input;
8684 if (IsExtractAPI)
8685 FrontendInputs = ExtractAPIInputs;
8686 else if (Input.isNothing())
8687 FrontendInputs = {};
8688
8689 for (const InputInfo &Input : FrontendInputs) {
8690 if (Input.isFilename())
8691 CmdArgs.push_back(Input.getFilename());
8692 else
8693 Input.getInputArg().renderAsInput(Args, CmdArgs);
8694 }
8695
8696 if (D.CC1Main && !D.CCGenDiagnostics) {
8697 // Invoke the CC1 directly in this process
8698 C.addCommand(std::make_unique<CC1Command>(
8699 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8700 Output, D.getPrependArg()));
8701 } else {
8702 C.addCommand(std::make_unique<Command>(
8703 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8704 Output, D.getPrependArg()));
8705 }
8706
8707 // Make the compile command echo its inputs for /showFilenames.
8708 if (Output.getType() == types::TY_Object &&
8709 Args.hasFlag(options::OPT__SLASH_showFilenames,
8710 options::OPT__SLASH_showFilenames_, false)) {
8711 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8712 }
8713
8714 if (Arg *A = Args.getLastArg(options::OPT_pg))
8715 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8716 !Args.hasArg(options::OPT_mfentry))
8717 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8718 << A->getAsString(Args);
8719
8720 // Claim some arguments which clang supports automatically.
8721
8722 // -fpch-preprocess is used with gcc to add a special marker in the output to
8723 // include the PCH file.
8724 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8725
8726 // Claim some arguments which clang doesn't support, but we don't
8727 // care to warn the user about.
8728 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8729 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8730
8731 // Disable warnings for clang -E -emit-llvm foo.c
8732 Args.ClaimAllArgs(options::OPT_emit_llvm);
8733}
8734
8735Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8736 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8737 // as it is for other tools. Some operations on a Tool actually test
8738 // whether that tool is Clang based on the Tool's Name as a string.
8739 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8740
8742
8743/// Add options related to the Objective-C runtime/ABI.
8744///
8745/// Returns true if the runtime is non-fragile.
8746ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8747 const InputInfoList &inputs,
8748 ArgStringList &cmdArgs,
8749 RewriteKind rewriteKind) const {
8750 // Look for the controlling runtime option.
8751 Arg *runtimeArg =
8752 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8753 options::OPT_fobjc_runtime_EQ);
8754
8755 // Just forward -fobjc-runtime= to the frontend. This supercedes
8756 // options about fragility.
8757 if (runtimeArg &&
8758 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8759 ObjCRuntime runtime;
8760 StringRef value = runtimeArg->getValue();
8761 if (runtime.tryParse(value)) {
8762 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8763 << value;
8764 }
8765 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8766 (runtime.getVersion() >= VersionTuple(2, 0)))
8767 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8768 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8769 !getToolChain().getTriple().isOSBinFormatWasm()) {
8771 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8772 << runtime.getVersion().getMajor();
8773 }
8774
8775 runtimeArg->render(args, cmdArgs);
8776 return runtime;
8777 }
8778
8779 // Otherwise, we'll need the ABI "version". Version numbers are
8780 // slightly confusing for historical reasons:
8781 // 1 - Traditional "fragile" ABI
8782 // 2 - Non-fragile ABI, version 1
8783 // 3 - Non-fragile ABI, version 2
8784 unsigned objcABIVersion = 1;
8785 // If -fobjc-abi-version= is present, use that to set the version.
8786 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8787 StringRef value = abiArg->getValue();
8788 if (value == "1")
8789 objcABIVersion = 1;
8790 else if (value == "2")
8791 objcABIVersion = 2;
8792 else if (value == "3")
8793 objcABIVersion = 3;
8794 else
8795 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8796 } else {
8797 // Otherwise, determine if we are using the non-fragile ABI.
8798 bool nonFragileABIIsDefault =
8799 (rewriteKind == RK_NonFragile ||
8800 (rewriteKind == RK_None &&
8802 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8803 options::OPT_fno_objc_nonfragile_abi,
8804 nonFragileABIIsDefault)) {
8805// Determine the non-fragile ABI version to use.
8806#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8807 unsigned nonFragileABIVersion = 1;
8808#else
8809 unsigned nonFragileABIVersion = 2;
8810#endif
8811
8812 if (Arg *abiArg =
8813 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8814 StringRef value = abiArg->getValue();
8815 if (value == "1")
8816 nonFragileABIVersion = 1;
8817 else if (value == "2")
8818 nonFragileABIVersion = 2;
8819 else
8820 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8821 << value;
8822 }
8823
8824 objcABIVersion = 1 + nonFragileABIVersion;
8825 } else {
8826 objcABIVersion = 1;
8827 }
8828 }
8829
8830 // We don't actually care about the ABI version other than whether
8831 // it's non-fragile.
8832 bool isNonFragile = objcABIVersion != 1;
8833
8834 // If we have no runtime argument, ask the toolchain for its default runtime.
8835 // However, the rewriter only really supports the Mac runtime, so assume that.
8836 ObjCRuntime runtime;
8837 if (!runtimeArg) {
8838 switch (rewriteKind) {
8839 case RK_None:
8840 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8841 break;
8842 case RK_Fragile:
8843 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8844 break;
8845 case RK_NonFragile:
8846 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8847 break;
8848 }
8849
8850 // -fnext-runtime
8851 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8852 // On Darwin, make this use the default behavior for the toolchain.
8853 if (getToolChain().getTriple().isOSDarwin()) {
8854 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8855
8856 // Otherwise, build for a generic macosx port.
8857 } else {
8858 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8859 }
8860
8861 // -fgnu-runtime
8862 } else {
8863 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8864 // Legacy behaviour is to target the gnustep runtime if we are in
8865 // non-fragile mode or the GCC runtime in fragile mode.
8866 if (isNonFragile)
8867 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8868 else
8869 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8870 }
8871
8872 if (llvm::any_of(inputs, [](const InputInfo &input) {
8873 return types::isObjC(input.getType());
8874 }))
8875 cmdArgs.push_back(
8876 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8877 return runtime;
8878}
8879
8880static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8881 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8882 I += HaveDash;
8883 return !HaveDash;
8884}
8885
8886namespace {
8887struct EHFlags {
8888 bool Synch = false;
8889 bool Asynch = false;
8890 bool NoUnwindC = false;
8891};
8892} // end anonymous namespace
8893
8894/// /EH controls whether to run destructor cleanups when exceptions are
8895/// thrown. There are three modifiers:
8896/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8897/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8898/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8899/// - c: Assume that extern "C" functions are implicitly nounwind.
8900/// The default is /EHs-c-, meaning cleanups are disabled.
8901static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8902 bool isWindowsMSVC) {
8903 EHFlags EH;
8904
8905 std::vector<std::string> EHArgs =
8906 Args.getAllArgValues(options::OPT__SLASH_EH);
8907 for (const auto &EHVal : EHArgs) {
8908 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8909 switch (EHVal[I]) {
8910 case 'a':
8911 EH.Asynch = maybeConsumeDash(EHVal, I);
8912 if (EH.Asynch) {
8913 // Async exceptions are Windows MSVC only.
8914 if (!isWindowsMSVC) {
8915 EH.Asynch = false;
8916 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8917 continue;
8918 }
8919 EH.Synch = false;
8920 }
8921 continue;
8922 case 'c':
8923 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8924 continue;
8925 case 's':
8926 EH.Synch = maybeConsumeDash(EHVal, I);
8927 if (EH.Synch)
8928 EH.Asynch = false;
8929 continue;
8930 default:
8931 break;
8932 }
8933 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8934 break;
8935 }
8936 }
8937 // The /GX, /GX- flags are only processed if there are not /EH flags.
8938 // The default is that /GX is not specified.
8939 if (EHArgs.empty() &&
8940 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8941 /*Default=*/false)) {
8942 EH.Synch = true;
8943 EH.NoUnwindC = true;
8944 }
8945
8946 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8947 EH.Synch = false;
8948 EH.NoUnwindC = false;
8949 EH.Asynch = false;
8950 }
8951
8952 return EH;
8953}
8954
8955void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8956 ArgStringList &CmdArgs) const {
8957 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8958
8959 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8960
8961 if (Arg *ShowIncludes =
8962 Args.getLastArg(options::OPT__SLASH_showIncludes,
8963 options::OPT__SLASH_showIncludes_user)) {
8964 CmdArgs.push_back("--show-includes");
8965 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8966 CmdArgs.push_back("-sys-header-deps");
8967 }
8968
8969 // This controls whether or not we emit RTTI data for polymorphic types.
8970 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8971 /*Default=*/false))
8972 CmdArgs.push_back("-fno-rtti-data");
8973
8974 // This controls whether or not we emit stack-protector instrumentation.
8975 // In MSVC, Buffer Security Check (/GS) is on by default.
8976 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8977 /*Default=*/true)) {
8978 CmdArgs.push_back("-stack-protector");
8979 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8980 }
8981
8982 const Driver &D = getToolChain().getDriver();
8983
8984 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8985 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8986 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8987 if (types::isCXX(InputType))
8988 CmdArgs.push_back("-fcxx-exceptions");
8989 CmdArgs.push_back("-fexceptions");
8990 if (EH.Asynch)
8991 CmdArgs.push_back("-fasync-exceptions");
8992 }
8993 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8994 CmdArgs.push_back("-fexternc-nounwind");
8995
8996 // /EP should expand to -E -P.
8997 if (Args.hasArg(options::OPT__SLASH_EP)) {
8998 CmdArgs.push_back("-E");
8999 CmdArgs.push_back("-P");
9000 }
9001
9002 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
9003 options::OPT__SLASH_Zc_dllexportInlines,
9004 false)) {
9005 CmdArgs.push_back("-fno-dllexport-inlines");
9006 }
9007
9008 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
9009 options::OPT__SLASH_Zc_wchar_t, false)) {
9010 CmdArgs.push_back("-fno-wchar");
9011 }
9012
9013 if (Args.hasArg(options::OPT__SLASH_kernel)) {
9014 llvm::Triple::ArchType Arch = getToolChain().getArch();
9015 std::vector<std::string> Values =
9016 Args.getAllArgValues(options::OPT__SLASH_arch);
9017 if (!Values.empty()) {
9018 llvm::SmallSet<std::string, 4> SupportedArches;
9019 if (Arch == llvm::Triple::x86)
9020 SupportedArches.insert("IA32");
9021
9022 for (auto &V : Values)
9023 if (!SupportedArches.contains(V))
9024 D.Diag(diag::err_drv_argument_not_allowed_with)
9025 << std::string("/arch:").append(V) << "/kernel";
9026 }
9027
9028 CmdArgs.push_back("-fno-rtti");
9029 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
9030 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
9031 << "/kernel";
9032 }
9033
9034 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
9035 options::OPT__SLASH_vlen_EQ_256,
9036 options::OPT__SLASH_vlen_EQ_512)) {
9037 llvm::Triple::ArchType AT = getToolChain().getArch();
9038 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
9039 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
9040 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
9041 "AVX10.2"};
9042
9043 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
9044 if (Arch512.contains(Arch))
9045 CmdArgs.push_back("-mprefer-vector-width=512");
9046 else
9047 D.Diag(diag::warn_drv_argument_not_allowed_with)
9048 << "/vlen=512" << std::string("/arch:").append(Arch);
9049 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
9050 if (Arch512.contains(Arch))
9051 CmdArgs.push_back("-mprefer-vector-width=256");
9052 else if (Arch != "AVX" && Arch != "AVX2")
9053 D.Diag(diag::warn_drv_argument_not_allowed_with)
9054 << "/vlen=256" << std::string("/arch:").append(Arch);
9055 } else {
9056 if (Arch == "AVX10.1" || Arch == "AVX10.2")
9057 CmdArgs.push_back("-mprefer-vector-width=256");
9058 }
9059 } else {
9060 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
9061 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
9062 CmdArgs.push_back("-mprefer-vector-width=256");
9063 CmdArgs.push_back("-target-feature");
9064 CmdArgs.push_back("-amx-tile");
9065 }
9066 if (Arch == "AVX10.2") {
9067 CmdArgs.push_back("-target-feature");
9068 CmdArgs.push_back("+avx10.2");
9069 }
9070 }
9071
9072 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
9073 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
9074 if (MostGeneralArg && BestCaseArg)
9075 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9076 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9077
9078 if (MostGeneralArg) {
9079 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
9080 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
9081 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
9082
9083 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9084 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9085 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9086 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9087 << FirstConflict->getAsString(Args)
9088 << SecondConflict->getAsString(Args);
9089
9090 if (SingleArg)
9091 CmdArgs.push_back("-fms-memptr-rep=single");
9092 else if (MultipleArg)
9093 CmdArgs.push_back("-fms-memptr-rep=multiple");
9094 else
9095 CmdArgs.push_back("-fms-memptr-rep=virtual");
9096 }
9097
9098 if (Args.hasArg(options::OPT_regcall4))
9099 CmdArgs.push_back("-regcall4");
9100
9101 // Parse the default calling convention options.
9102 if (Arg *CCArg =
9103 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
9104 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
9105 options::OPT__SLASH_Gregcall)) {
9106 unsigned DCCOptId = CCArg->getOption().getID();
9107 const char *DCCFlag = nullptr;
9108 bool ArchSupported = !isNVPTX;
9109 llvm::Triple::ArchType Arch = getToolChain().getArch();
9110 switch (DCCOptId) {
9111 case options::OPT__SLASH_Gd:
9112 DCCFlag = "-fdefault-calling-conv=cdecl";
9113 break;
9114 case options::OPT__SLASH_Gr:
9115 ArchSupported = Arch == llvm::Triple::x86;
9116 DCCFlag = "-fdefault-calling-conv=fastcall";
9117 break;
9118 case options::OPT__SLASH_Gz:
9119 ArchSupported = Arch == llvm::Triple::x86;
9120 DCCFlag = "-fdefault-calling-conv=stdcall";
9121 break;
9122 case options::OPT__SLASH_Gv:
9123 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9124 DCCFlag = "-fdefault-calling-conv=vectorcall";
9125 break;
9126 case options::OPT__SLASH_Gregcall:
9127 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9128 DCCFlag = "-fdefault-calling-conv=regcall";
9129 break;
9130 }
9131
9132 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9133 if (ArchSupported && DCCFlag)
9134 CmdArgs.push_back(DCCFlag);
9135 }
9136
9137 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9138 CmdArgs.push_back("-regcall4");
9139
9140 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9141
9142 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9143 CmdArgs.push_back("-fdiagnostics-format");
9144 CmdArgs.push_back("msvc");
9145 }
9146
9147 if (Args.hasArg(options::OPT__SLASH_kernel))
9148 CmdArgs.push_back("-fms-kernel");
9149
9150 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9151 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9152 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9153 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9154 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9155 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9156
9157 // Handle the various /guard options. We don't immediately push back clang
9158 // args since there are /d2 args that can modify the behavior of /guard:cf.
9159 bool HasCFGuard = false;
9160 bool HasCFGuardNoChecks = false;
9161 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9162 StringRef GuardArgs = A->getValue();
9163 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9164 // "ehcont-".
9165 if (GuardArgs.equals_insensitive("cf")) {
9166 // Emit CFG instrumentation and the table of address-taken functions.
9167 HasCFGuard = true;
9168 HasCFGuardNoChecks = false;
9169 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9170 // Emit only the table of address-taken functions.
9171 HasCFGuard = false;
9172 HasCFGuardNoChecks = true;
9173 } else if (GuardArgs.equals_insensitive("ehcont")) {
9174 // Emit EH continuation table.
9175 CmdArgs.push_back("-ehcontguard");
9176 } else if (GuardArgs.equals_insensitive("cf-") ||
9177 GuardArgs.equals_insensitive("ehcont-")) {
9178 // Do nothing, but we might want to emit a security warning in future.
9179 } else {
9180 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9181 }
9182 A->claim();
9183 }
9184
9185 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9186 // If CFG is not enabled, it is a no-op.
9187 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9188 if (HasCFGuard) {
9189 HasCFGuard = false;
9190 HasCFGuardNoChecks = true;
9191 }
9192 }
9193
9194 if (HasCFGuard)
9195 CmdArgs.push_back("-cfguard");
9196 else if (HasCFGuardNoChecks)
9197 CmdArgs.push_back("-cfguard-no-checks");
9198
9199 // Control Flow Guard mechanism for Windows.
9200 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9201 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9202 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9203 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9204
9205 for (const auto &FuncOverride :
9206 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9207 CmdArgs.push_back(Args.MakeArgString(
9208 Twine("-loader-replaceable-function=") + FuncOverride));
9209 }
9210
9211 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9212 CmdArgs.push_back("-Wdate-time");
9213
9214 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9215 D.Diag(diag::err_drv_argument_not_allowed_with)
9216 << "/experimental:deterministic"
9217 << "/Brepro-";
9218 }
9219 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9220 // deterministic result, but we force this timestamp to 0, which also
9221 // produces deterministic result.
9222 CmdArgs.push_back("-mno-incremental-linker-compatible");
9223 }
9224
9225 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9226 options::OPT__SLASH_d1nodatetime_, false);
9227
9228 if (HasNoDateTime)
9229 CmdArgs.push_back("-init-datetime-macros=undefined");
9230
9231 // /Brepro is an alias for -mincremental-linker-compatible option.
9232 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9233 options::OPT_mno_incremental_linker_compatible,
9234 getToolChain()
9235 .getTriple()
9236 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9237 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9238 // This option does not allow the user redefinitions for these macros.
9239 if (!HasNoDateTime)
9240 CmdArgs.push_back("-init-datetime-macros=literalone");
9241 // Omit tool, current workdir and command line in COFF CV debug section.
9242 CmdArgs.push_back("-gno-codeview-command-line");
9243 CmdArgs.push_back("-gno-codeview-cwd");
9244 }
9245}
9246
9247const char *Clang::getBaseInputName(const ArgList &Args,
9248 const InputInfo &Input) {
9249 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9250}
9251
9252const char *Clang::getBaseInputStem(const ArgList &Args,
9253 const InputInfoList &Inputs) {
9254 const char *Str = getBaseInputName(Args, Inputs[0]);
9255
9256 if (const char *End = strrchr(Str, '.'))
9257 return Args.MakeArgString(std::string(Str, End));
9258
9259 return Str;
9260}
9261
9262const char *Clang::getDependencyFileName(const ArgList &Args,
9263 const InputInfoList &Inputs) {
9264 // FIXME: Think about this more.
9265
9266 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9267 SmallString<128> OutputFilename(OutputOpt->getValue());
9268 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9269 return Args.MakeArgString(OutputFilename);
9270 }
9271
9272 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9273}
9274
9275// Begin ClangAs
9276
9277void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9278 ArgStringList &CmdArgs) const {
9279 StringRef CPUName;
9280 StringRef ABIName;
9281 const llvm::Triple &Triple = getToolChain().getTriple();
9282 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9283
9284 CmdArgs.push_back("-target-abi");
9285 CmdArgs.push_back(ABIName.data());
9286}
9287
9288void ClangAs::AddX86TargetArgs(const ArgList &Args,
9289 ArgStringList &CmdArgs) const {
9290 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9291 /*IsLTO=*/false);
9292
9293 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9294 StringRef Value = A->getValue();
9295 if (Value == "intel" || Value == "att") {
9296 CmdArgs.push_back("-mllvm");
9297 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9298 } else {
9299 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9300 << A->getSpelling() << Value;
9301 }
9302 }
9303}
9304
9305void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9306 ArgStringList &CmdArgs) const {
9307 CmdArgs.push_back("-target-abi");
9308 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9310 .data());
9311}
9312
9313void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9314 ArgStringList &CmdArgs) const {
9315 const llvm::Triple &Triple = getToolChain().getTriple();
9316 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9317
9318 CmdArgs.push_back("-target-abi");
9319 CmdArgs.push_back(ABIName.data());
9320
9321 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9322 options::OPT_mno_default_build_attributes, true)) {
9323 CmdArgs.push_back("-mllvm");
9324 CmdArgs.push_back("-riscv-add-build-attributes");
9325 }
9326}
9327
9329 const InputInfo &Output, const InputInfoList &Inputs,
9330 const ArgList &Args,
9331 const char *LinkingOutput) const {
9332 ArgStringList CmdArgs;
9333
9334 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9335 const InputInfo &Input = Inputs[0];
9336
9337 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9338 const std::string &TripleStr = Triple.getTriple();
9339 const auto &D = getToolChain().getDriver();
9340
9341 // Don't warn about "clang -w -c foo.s"
9342 Args.ClaimAllArgs(options::OPT_w);
9343 // and "clang -emit-llvm -c foo.s"
9344 Args.ClaimAllArgs(options::OPT_emit_llvm);
9345
9346 claimNoWarnArgs(Args);
9347
9348 // Invoke ourselves in -cc1as mode.
9349 //
9350 // FIXME: Implement custom jobs for internal actions.
9351 CmdArgs.push_back("-cc1as");
9352
9353 // Add the "effective" target triple.
9354 CmdArgs.push_back("-triple");
9355 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9356
9358
9359 // Set the output mode, we currently only expect to be used as a real
9360 // assembler.
9361 CmdArgs.push_back("-filetype");
9362 CmdArgs.push_back("obj");
9363
9364 // Set the main file name, so that debug info works even with
9365 // -save-temps or preprocessed assembly.
9366 CmdArgs.push_back("-main-file-name");
9367 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9368
9369 // Add the target cpu
9370 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9371 if (!CPU.empty()) {
9372 CmdArgs.push_back("-target-cpu");
9373 CmdArgs.push_back(Args.MakeArgString(CPU));
9374 }
9375
9376 // Add the target features
9377 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9378
9379 // Ignore explicit -force_cpusubtype_ALL option.
9380 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9381
9382 // Pass along any -I options so we get proper .include search paths.
9383 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9384
9385 // Pass along any --embed-dir or similar options so we get proper embed paths.
9386 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9387
9388 // Determine the original source input.
9389 auto FindSource = [](const Action *S) -> const Action * {
9390 while (S->getKind() != Action::InputClass) {
9391 assert(!S->getInputs().empty() && "unexpected root action!");
9392 S = S->getInputs()[0];
9393 }
9394 return S;
9395 };
9396 const Action *SourceAction = FindSource(&JA);
9397
9398 // Forward -g and handle debug info related flags, assuming we are dealing
9399 // with an actual assembly file.
9400 bool WantDebug = false;
9401 Args.ClaimAllArgs(options::OPT_g_Group);
9402 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9403 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9404 !A->getOption().matches(options::OPT_ggdb0);
9405
9406 // If a -gdwarf argument appeared, remember it.
9407 bool EmitDwarf = false;
9408 if (const Arg *A = getDwarfNArg(Args))
9409 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9410
9411 bool EmitCodeView = false;
9412 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9413 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9414
9415 // If the user asked for debug info but did not explicitly specify -gcodeview
9416 // or -gdwarf, ask the toolchain for the default format.
9417 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9418 switch (getToolChain().getDefaultDebugFormat()) {
9419 case llvm::codegenoptions::DIF_CodeView:
9420 EmitCodeView = true;
9421 break;
9422 case llvm::codegenoptions::DIF_DWARF:
9423 EmitDwarf = true;
9424 break;
9425 }
9426 }
9427
9428 // If the arguments don't imply DWARF, don't emit any debug info here.
9429 if (!EmitDwarf)
9430 WantDebug = false;
9431
9432 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9433 llvm::codegenoptions::NoDebugInfo;
9434
9435 // Add the -fdebug-compilation-dir flag if needed.
9436 const char *DebugCompilationDir =
9437 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9438
9439 if (SourceAction->getType() == types::TY_Asm ||
9440 SourceAction->getType() == types::TY_PP_Asm) {
9441 // You might think that it would be ok to set DebugInfoKind outside of
9442 // the guard for source type, however there is a test which asserts
9443 // that some assembler invocation receives no -debug-info-kind,
9444 // and it's not clear whether that test is just overly restrictive.
9445 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9446 : llvm::codegenoptions::NoDebugInfo);
9447
9448 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9449 CmdArgs);
9450
9451 // Set the AT_producer to the clang version when using the integrated
9452 // assembler on assembly source files.
9453 CmdArgs.push_back("-dwarf-debug-producer");
9454 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9455
9456 // And pass along -I options
9457 Args.AddAllArgs(CmdArgs, options::OPT_I);
9458 }
9459 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9460 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9461 llvm::DebuggerKind::Default);
9462 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9463 if (useMachORelocatableDwarf(Triple, DwarfVersion))
9464 CmdArgs.push_back("-grelocatable-dwarf");
9465 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9466
9467 // Handle -fPIC et al -- the relocation-model affects the assembler
9468 // for some targets.
9469 llvm::Reloc::Model RelocationModel;
9470 unsigned PICLevel;
9471 bool IsPIE;
9472 std::tie(RelocationModel, PICLevel, IsPIE) =
9473 ParsePICArgs(getToolChain(), Args);
9474
9475 const char *RMName = RelocationModelName(RelocationModel);
9476 if (RMName) {
9477 CmdArgs.push_back("-mrelocation-model");
9478 CmdArgs.push_back(RMName);
9479 }
9480
9481 // Optionally embed the -cc1as level arguments into the debug info, for build
9482 // analysis.
9483 if (getToolChain().UseDwarfDebugFlags()) {
9484 ArgStringList OriginalArgs;
9485 for (const auto &Arg : Args)
9486 Arg->render(Args, OriginalArgs);
9487
9488 SmallString<256> Flags;
9489 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9490 escapeSpacesAndBackslashes(Exec, Flags);
9491 for (const char *OriginalArg : OriginalArgs) {
9492 SmallString<128> EscapedArg;
9493 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9494 Flags += " ";
9495 Flags += EscapedArg;
9496 }
9497 CmdArgs.push_back("-dwarf-debug-flags");
9498 CmdArgs.push_back(Args.MakeArgString(Flags));
9499 }
9500
9501 // FIXME: Add -static support, once we have it.
9502
9503 // Add target specific flags.
9504 switch (getToolChain().getArch()) {
9505 default:
9506 break;
9507
9508 case llvm::Triple::mips:
9509 case llvm::Triple::mipsel:
9510 case llvm::Triple::mips64:
9511 case llvm::Triple::mips64el:
9512 AddMIPSTargetArgs(Args, CmdArgs);
9513 break;
9514
9515 case llvm::Triple::x86:
9516 case llvm::Triple::x86_64:
9517 AddX86TargetArgs(Args, CmdArgs);
9518 break;
9519
9520 case llvm::Triple::arm:
9521 case llvm::Triple::armeb:
9522 case llvm::Triple::thumb:
9523 case llvm::Triple::thumbeb:
9524 // This isn't in AddARMTargetArgs because we want to do this for assembly
9525 // only, not C/C++.
9526 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9527 options::OPT_mno_default_build_attributes, true)) {
9528 CmdArgs.push_back("-mllvm");
9529 CmdArgs.push_back("-arm-add-build-attributes");
9530 }
9531 break;
9532
9533 case llvm::Triple::aarch64:
9534 case llvm::Triple::aarch64_32:
9535 case llvm::Triple::aarch64_be:
9536 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9537 CmdArgs.push_back("-mllvm");
9538 CmdArgs.push_back("-aarch64-mark-bti-property");
9539 }
9540 break;
9541
9542 case llvm::Triple::loongarch32:
9543 case llvm::Triple::loongarch64:
9544 AddLoongArchTargetArgs(Args, CmdArgs);
9545 break;
9546
9547 case llvm::Triple::riscv32:
9548 case llvm::Triple::riscv64:
9549 case llvm::Triple::riscv32be:
9550 case llvm::Triple::riscv64be:
9551 AddRISCVTargetArgs(Args, CmdArgs);
9552 break;
9553
9554 case llvm::Triple::hexagon:
9555 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9556 options::OPT_mno_default_build_attributes, true)) {
9557 CmdArgs.push_back("-mllvm");
9558 CmdArgs.push_back("-hexagon-add-build-attributes");
9559 }
9560 break;
9561 }
9562
9563 // Consume all the warning flags. Usually this would be handled more
9564 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9565 // doesn't handle that so rather than warning about unused flags that are
9566 // actually used, we'll lie by omission instead.
9567 // FIXME: Stop lying and consume only the appropriate driver flags
9568 Args.ClaimAllArgs(options::OPT_W_Group);
9569
9570 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9571 getToolChain().getDriver());
9572
9573 // Forward -Xclangas arguments to -cc1as
9574 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9575 Arg->claim();
9576 CmdArgs.push_back(Arg->getValue());
9577 }
9578
9579 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9580
9581 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9582 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9583 Output.getFilename());
9584
9585 // Fixup any previous commands that use -object-file-name because when we
9586 // generated them, the final .obj name wasn't yet known.
9587 for (Command &J : C.getJobs()) {
9588 if (SourceAction != FindSource(&J.getSource()))
9589 continue;
9590 auto &JArgs = J.getArguments();
9591 for (unsigned I = 0; I < JArgs.size(); ++I) {
9592 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9593 Output.isFilename()) {
9594 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9595 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9596 Output.getFilename());
9597 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9598 J.replaceArguments(NewArgs);
9599 break;
9600 }
9601 }
9602 }
9603
9604 assert(Output.isFilename() && "Unexpected lipo output.");
9605 CmdArgs.push_back("-o");
9606 CmdArgs.push_back(Output.getFilename());
9607
9608 const llvm::Triple &T = getToolChain().getTriple();
9609 Arg *A;
9610 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9611 T.isOSBinFormatELF()) {
9612 CmdArgs.push_back("-split-dwarf-output");
9613 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9614 }
9615
9616 if (Triple.isAMDGPU())
9617 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9618
9619 assert(Input.isFilename() && "Invalid input.");
9620 CmdArgs.push_back(Input.getFilename());
9621
9622 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9623 if (D.CC1Main && !D.CCGenDiagnostics) {
9624 // Invoke cc1as directly in this process.
9625 C.addCommand(std::make_unique<CC1Command>(
9626 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9627 Output, D.getPrependArg()));
9628 } else {
9629 C.addCommand(std::make_unique<Command>(
9630 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9631 Output, D.getPrependArg()));
9632 }
9633}
9634
9635// Begin OffloadBundler
9637 const InputInfo &Output,
9638 const InputInfoList &Inputs,
9639 const llvm::opt::ArgList &TCArgs,
9640 const char *LinkingOutput) const {
9641 // The version with only one output is expected to refer to a bundling job.
9642 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9643
9644 // The bundling command looks like this:
9645 // clang-offload-bundler -type=bc
9646 // -targets=host-triple,openmp-triple1,openmp-triple2
9647 // -output=output_file
9648 // -input=unbundle_file_host
9649 // -input=unbundle_file_tgt1
9650 // -input=unbundle_file_tgt2
9651
9652 ArgStringList CmdArgs;
9653
9654 // Get the type.
9655 CmdArgs.push_back(TCArgs.MakeArgString(
9656 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9657
9658 assert(JA.getInputs().size() == Inputs.size() &&
9659 "Not have inputs for all dependence actions??");
9660
9661 // Get the targets.
9662 SmallString<128> Triples;
9663 Triples += "-targets=";
9664 for (unsigned I = 0; I < Inputs.size(); ++I) {
9665 if (I)
9666 Triples += ',';
9667
9668 // Find ToolChain for this input.
9670 const ToolChain *CurTC = &getToolChain();
9671 const Action *CurDep = JA.getInputs()[I];
9672
9673 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9674 CurTC = nullptr;
9675 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9676 assert(CurTC == nullptr && "Expected one dependence!");
9677 CurKind = A->getOffloadingDeviceKind();
9678 CurTC = TC;
9679 });
9680 }
9681 Triples += Action::GetOffloadKindName(CurKind);
9682 Triples += '-';
9683 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9684 TCArgs, CurDep->getOffloadingArch()))
9685 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9686
9687 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9688 Triples += '-';
9689 Triples += CurDep->getOffloadingArch().ArchName;
9690 }
9691 }
9692 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9693
9694 // Get bundled file command.
9695 CmdArgs.push_back(
9696 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9697
9698 // Get unbundled files command.
9699 for (unsigned I = 0; I < Inputs.size(); ++I) {
9701 UB += "-input=";
9702
9703 // Find ToolChain for this input.
9704 const ToolChain *CurTC = &getToolChain();
9705 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9706 CurTC = nullptr;
9707 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9708 assert(CurTC == nullptr && "Expected one dependence!");
9709 CurTC = TC;
9710 });
9711 UB += C.addTempFile(
9712 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9713 } else {
9714 UB += CurTC->getInputFilename(Inputs[I]);
9715 }
9716 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9717 }
9718 addOffloadCompressArgs(TCArgs, CmdArgs);
9719 if (TCArgs.hasArg(options::OPT_v))
9720 CmdArgs.push_back("--verbose");
9721 // All the inputs are encoded as commands.
9722 C.addCommand(std::make_unique<Command>(
9723 JA, *this, ResponseFileSupport::None(),
9724 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9725 CmdArgs, ArrayRef<InputInfo>(), Output));
9726}
9727
9729 const InputInfo &Output,
9730 const InputInfoList &Inputs,
9731 const llvm::opt::ArgList &Args,
9732 const char *LinkingOutput) const {
9733 ArgStringList CmdArgs;
9734
9735 // Add the output file name.
9736 assert(Output.isFilename() && "Invalid output.");
9737 CmdArgs.push_back("-o");
9738 CmdArgs.push_back(Output.getFilename());
9739
9740 // Create the inputs to bundle the needed metadata.
9741 for (const InputInfo &Input : Inputs) {
9742 const Action *OffloadAction = Input.getAction();
9744 const ArgList &TCArgs =
9745 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9747 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9749 if (Arch.empty())
9750 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9751
9752 StringRef Kind =
9754
9755 ArgStringList Features;
9756 SmallVector<StringRef> FeatureArgs;
9757 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9758 false);
9759 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9760 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9761
9762 // TODO: We need to pass in the full target-id and handle it properly in the
9763 // linker wrapper.
9765 "file=" + File.str(),
9766 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9767 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9768 "kind=" + Kind.str(),
9769 };
9770
9772 for (StringRef Feature : FeatureArgs)
9773 Parts.emplace_back("feature=" + Feature.str());
9774
9775 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9776 }
9777
9778 // FIXME: --offload-compress is HIP only until the OpenMP runtime accepts it.
9780 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
9781 addOffloadCompressArgs(Args, CmdArgs, /*EmitCompressionFormat=*/true);
9782
9783 C.addCommand(std::make_unique<Command>(
9785 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9786 CmdArgs, Inputs, Output));
9787}
9788
9789// Options that need the profile compiler-rt library on the target toolchain.
9790// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9791// too.
9792static bool requiresProfileRT(unsigned ID) {
9793 switch (ID) {
9794 case options::OPT_fprofile_generate:
9795 case options::OPT_fprofile_generate_EQ:
9796 case options::OPT_fprofile_instr_generate:
9797 case options::OPT_fprofile_instr_generate_EQ:
9798 case options::OPT_fcoverage_mapping:
9799 case options::OPT_fno_coverage_mapping:
9800 case options::OPT_fcoverage_compilation_dir_EQ:
9801 case options::OPT_ffile_compilation_dir_EQ:
9802 case options::OPT_fcoverage_prefix_map_EQ:
9803 return true;
9804 default:
9805 return false;
9806 }
9807}
9808
9809// Options that need the ubsan compiler-rt library on the target toolchain.
9810static bool requiresUBSanRT(unsigned ID) {
9811 switch (ID) {
9812 case options::OPT_fsanitize_EQ:
9813 case options::OPT_fno_sanitize_EQ:
9814 case options::OPT_fsanitize_minimal_runtime:
9815 case options::OPT_fno_sanitize_minimal_runtime:
9816 return true;
9817 default:
9818 return false;
9819 }
9820}
9821
9823 const InputInfo &Output,
9824 const InputInfoList &Inputs,
9825 const ArgList &Args,
9826 const char *LinkingOutput) const {
9827 using namespace options;
9828
9829 // A list of permitted options that will be forwarded to the embedded device
9830 // compilation job.
9831 const llvm::DenseSet<unsigned> CompilerOptions{
9832 OPT_v,
9833 OPT_hip_path_EQ,
9834 OPT_O_Group,
9835 OPT_g_Group,
9836 OPT_g_flags_Group,
9837 OPT_R_value_Group,
9838 OPT_R_Group,
9839 OPT_Xcuda_ptxas,
9840 OPT_ptxas_path_EQ,
9841 OPT_ftime_report,
9842 OPT_ftime_trace,
9843 OPT_ftime_trace_EQ,
9844 OPT_ftime_trace_granularity_EQ,
9845 OPT_ftime_trace_verbose,
9846 OPT_ftime_trace_compress_EQ,
9847 OPT_opt_record_file,
9848 OPT_opt_record_format,
9849 OPT_opt_record_passes,
9850 OPT_fsave_optimization_record,
9851 OPT_fsave_optimization_record_EQ,
9852 OPT_fno_save_optimization_record,
9853 OPT_foptimization_record_file_EQ,
9854 OPT_foptimization_record_passes_EQ,
9855 OPT_save_temps,
9856 OPT_save_temps_EQ,
9857 OPT_mcode_object_version_EQ,
9858 OPT_load,
9859 OPT_no_canonical_prefixes,
9860 OPT_fno_lto,
9861 OPT_flto,
9862 OPT_flto_partitions_EQ,
9863 OPT_flto_EQ,
9864 OPT_hipspv_pass_plugin_EQ,
9865 OPT_use_spirv_backend,
9866 OPT_no_use_spirv_backend,
9867 OPT_fmultilib_flag,
9868 OPT_fprofile_generate,
9869 OPT_fprofile_generate_EQ,
9870 OPT_fprofile_instr_generate,
9871 OPT_fprofile_instr_generate_EQ,
9872 OPT_fcoverage_mapping,
9873 OPT_fno_coverage_mapping,
9874 OPT_fcoverage_compilation_dir_EQ,
9875 OPT_ffile_compilation_dir_EQ,
9876 OPT_fcoverage_prefix_map_EQ,
9877 OPT_fsanitize_EQ,
9878 OPT_fno_sanitize_EQ,
9879 OPT_fsanitize_minimal_runtime,
9880 OPT_fno_sanitize_minimal_runtime,
9881 OPT_fsanitize_trap_EQ,
9882 OPT_fno_sanitize_trap_EQ,
9883 OPT_fvectorize,
9884 OPT_fno_vectorize,
9885 OPT_fslp_vectorize,
9886 OPT_fno_slp_vectorize,
9887 OPT_hipstdpar,
9888 OPT_fenable_spirv_size_optimization};
9889 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9890 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9891 // CMake implicit linker argument parsing.
9892 bool SuppressHIPNoRDCVerbose =
9893 JA.getType() == types::TY_HIP_FATBIN &&
9894 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9895 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9896 return TC.getVFS().exists(
9897 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9898 };
9899 auto ToolChainHasSanitizerRT = [&](const ToolChain &TC, const ArgList &TCArgs,
9900 Action::OffloadKind Kind) {
9901 if (TC.getSanitizerArgs(TCArgs, /*BA=*/{}, Kind).needsCsanRt())
9902 return ToolChainHasRT(TC, "csan");
9903 return ToolChainHasRT(TC, "ubsan_minimal") ||
9904 ToolChainHasRT(TC, "ubsan_standalone");
9905 };
9906 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC,
9907 bool HasSanitizerRT) {
9908 unsigned ID = A->getOption().getID();
9909 // Don't forward profiling arguments if the toolchain doesn't support it.
9910 // Without this check using it on the host would result in linker errors.
9911 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9912 // together to avoid a device cc1 diagnostic.
9913 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9914 return false;
9915 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9916 // Without this check using it on the host would result in linker errors.
9917 if (requiresUBSanRT(ID) && !HasSanitizerRT)
9918 return false;
9919 // Don't forward -mllvm to toolchains that don't support LLVM.
9920 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9921 };
9922 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9923 const ToolChain &TC, bool HasSanitizerRT) {
9924 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9925 return false;
9926 return (Set.contains(A->getOption().getID()) ||
9927 (A->getOption().getGroup().isValid() &&
9928 Set.contains(A->getOption().getGroup().getID()))) &&
9929 ShouldForwardForToolChain(A, TC, HasSanitizerRT);
9930 };
9931
9932 ArgStringList CmdArgs;
9935 auto TCRange = C.getOffloadToolChains(Kind);
9936 for (auto &I : llvm::make_range(TCRange)) {
9937 const ToolChain *TC = I.second;
9938
9939 // We do not use a bound architecture here so options passed only to a
9940 // specific architecture via -Xarch_<cpu> will not be forwarded.
9941 ArgStringList CompilerArgs;
9942 ArgStringList LinkerArgs;
9943 const DerivedArgList &ToolChainArgs =
9944 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9945 const bool HasSanitizerRT =
9946 ToolChainHasSanitizerRT(*TC, ToolChainArgs, Kind);
9947 for (Arg *A : ToolChainArgs) {
9948 if (A->getOption().matches(OPT_Zlinker_input))
9949 LinkerArgs.emplace_back(A->getValue());
9950 else if (ShouldForward(CompilerOptions, A, *TC, HasSanitizerRT)) {
9951 A->claim();
9952 A->render(Args, CompilerArgs);
9953 } else if (ShouldForward(LinkerOptions, A, *TC, HasSanitizerRT)) {
9954 A->claim();
9955 A->render(Args, LinkerArgs);
9956 }
9957 }
9958
9959 // If the user explicitly requested it via `--offload-arch` we should
9960 // extract it from any static libraries if present. Device images are
9961 // labeled with the canonical target ID, so request that.
9962 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ)) {
9963 std::optional<std::string> TargetID =
9964 getCanonicalTargetID(TC->getTriple(), Arg);
9965 CmdArgs.emplace_back(Args.MakeArgString(
9966 "--should-extract=" + (TargetID ? StringRef(*TargetID) : Arg)));
9967 }
9968
9969 // If this is OpenMP the device linker will need `-lompdevice`.
9970 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9971 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9972 LinkerArgs.emplace_back("-lompdevice");
9973
9974 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9975 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9976 // flags to normal compilation.
9977 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9978 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9979 if (TC->getTriple().isSPIRV() &&
9980 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9981 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9982 // For SPIR-V some functions will be defined by the runtime so allow
9983 // unresolved symbols in `spirv-link`.
9984 LinkerArgs.emplace_back("--allow-partial-linkage");
9985 // Don't optimize out exported symbols.
9986 LinkerArgs.emplace_back("--create-library");
9987 }
9988
9989 // Forward the SYCL device image split option to clang-sycl-linker.
9990 // The driver and clang-sycl-linker share the same value vocabulary, so
9991 // the value is passed through verbatim after validation.
9992 if (Kind == Action::OFK_SYCL) {
9993 if (Arg *A =
9994 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9995 StringRef Mode = A->getValue();
9996 if (Mode != "kernel" && Mode != "translation_unit" &&
9997 Mode != "link_unit")
9998 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9999 << A->getSpelling() << Mode;
10000 else
10001 LinkerArgs.emplace_back(
10002 Args.MakeArgString("--module-split-mode=" + Mode));
10003 }
10004 }
10005
10006 // Forward all of these to the appropriate toolchain.
10007 for (StringRef Arg : CompilerArgs)
10008 CmdArgs.push_back(Args.MakeArgString(
10009 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
10010 for (StringRef Arg : LinkerArgs)
10011 CmdArgs.push_back(Args.MakeArgString(
10012 "--device-linker=" + TC->getTripleString() + "=" + Arg));
10013
10014 // Forward the LTO mode for this toolchain.
10015 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
10016 if (DeviceLTOMode == LTOK_Full)
10017 CmdArgs.push_back(Args.MakeArgString(
10018 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
10019 else if (DeviceLTOMode == LTOK_Thin) {
10020 CmdArgs.push_back(Args.MakeArgString(
10021 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
10022 if (TC->getTriple().isAMDGPU()) {
10023 CmdArgs.push_back(
10024 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10025 "=-plugin-opt=-force-import-all"));
10026 CmdArgs.push_back(
10027 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10028 "=-plugin-opt=-avail-extern-to-local"));
10029 CmdArgs.push_back(Args.MakeArgString(
10030 "--device-linker=" + TC->getTripleString() +
10031 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
10032 if (Kind == Action::OFK_OpenMP) {
10033 CmdArgs.push_back(
10034 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10035 "=-plugin-opt=-amdgpu-internalize-symbols"));
10036 }
10037 }
10038 }
10039 }
10040 }
10041
10042 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
10043 CmdArgs.push_back(
10044 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
10045 else
10046 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
10047 getToolChain().getTripleString()));
10048
10049 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
10050 CmdArgs.push_back("--wrapper-verbose");
10051 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
10052 CmdArgs.push_back(
10053 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
10054 CmdArgs.push_back(Args.MakeArgString(
10055 Twine("--device-compiler=--cuda-path=") + A->getValue()));
10056 }
10057 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
10058 CmdArgs.push_back(Args.MakeArgString(
10059 Twine("--device-compiler=--rocm-path=") + A->getValue()));
10060 }
10061
10062 // Construct the link job so we can wrap around it.
10063 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
10064 const auto &LinkCommand = C.getJobs().getJobs().back();
10065
10066 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10067 // wrapper.
10068 for (Arg *A :
10069 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
10070 StringRef Val = A->getValue(0);
10071 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10072 auto WrapperOption =
10073 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10074 if (Val.empty())
10075 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
10076 else
10077 CmdArgs.push_back(Args.MakeArgString(
10078 WrapperOption +
10079 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
10080 A->getValue(1)));
10081 }
10082 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
10083 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
10084
10085 // Embed bitcode instead of an object in JIT mode.
10086 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10087 options::OPT_fno_openmp_target_jit, false))
10088 CmdArgs.push_back("--embed-bitcode");
10089
10090 // Save temporary files created by the linker wrapper.
10091 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10092 Args.hasArg(options::OPT_save_temps))
10093 CmdArgs.push_back("--save-temps");
10094
10095 // Pass in the C library for GPUs if present and not disabled.
10096 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10097 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10098 options::OPT_nodefaultlibs, options::OPT_nolibc,
10099 options::OPT_nogpulibc)) {
10100 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10101 // The device C library is only available for NVPTX and AMDGPU targets
10102 // and we only link it by default for OpenMP currently.
10103 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10105 return;
10106 bool HasLibC = TC.getStdlibIncludePath().has_value();
10107 if (HasLibC) {
10108 CmdArgs.push_back(Args.MakeArgString(
10109 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10110 CmdArgs.push_back(Args.MakeArgString(
10111 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10112 }
10113 auto HasCompilerRT = getToolChain().getVFS().exists(
10114 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10115 /*IsFortran=*/false));
10116 if (HasCompilerRT)
10117 CmdArgs.push_back(
10118 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10119 "-lclang_rt.builtins"));
10120
10121 bool HasFlangRT = getToolChain().getVFS().exists(
10122 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10123 /*IsFortran=*/true));
10124 if (HasFlangRT && C.getDriver().IsFlangMode())
10125 CmdArgs.push_back(
10126 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10127 "-lflang_rt.runtime"));
10128 });
10129 }
10130
10131 // Add the linker arguments to be forwarded by the wrapper.
10132 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10133 LinkCommand->getExecutable()));
10134
10135 // We use action type to differentiate two use cases of the linker wrapper.
10136 // TY_Image for normal linker wrapper work.
10137 // TY_HIP_FATBIN and TY_SYCL_FATBIN for device-only links emitting a fat
10138 // binary directly.
10139 assert(JA.getType() == types::TY_HIP_FATBIN ||
10140 JA.getType() == types::TY_SYCL_FATBIN ||
10141 JA.getType() == types::TY_Image);
10142 if (JA.getType() != types::TY_Image) {
10143 CmdArgs.push_back("--emit-fatbin-only");
10144 CmdArgs.append({"-o", Output.getFilename()});
10145 for (auto Input : Inputs)
10146 CmdArgs.push_back(Input.getFilename());
10147 } else {
10148 for (const char *LinkArg : LinkCommand->getArguments())
10149 CmdArgs.push_back(LinkArg);
10150 }
10151
10152 addOffloadCompressArgs(Args, CmdArgs);
10153
10154 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10155 if (OffloadJobs.A) {
10156 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10157 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10158 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10159 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10160 Twine(OffloadJobs.NumThreads)));
10161 } else if (!OffloadJobs.A->isClaimed()) {
10162 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10163 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10164 }
10165 }
10166
10167 // Propagate -no-canonical-prefixes.
10168 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10169 CmdArgs.push_back("--no-canonical-prefixes");
10170
10171 const char *Exec =
10172 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10173
10174 // Replace the executable and arguments of the link job with the
10175 // wrapper.
10176 LinkCommand->replaceExecutable(Exec);
10177 LinkCommand->replaceArguments(CmdArgs);
10178}
#define V(N, I)
static StringRef bytes(const std::vector< T, Allocator > &v)
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3967
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:118
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2342
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4395
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:717
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5162
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9792
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4576
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:766
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:71
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1361
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1213
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:8901
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2321
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:783
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4068
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4710
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2592
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1251
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:743
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:338
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4687
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:4431
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:323
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2597
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1262
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2373
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2603
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2314
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4134
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:98
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3639
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:308
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, bool IsDeviceOffloadAction, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition Clang.cpp:138
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1278
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:253
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1396
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3649
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4076
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3877
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3896
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8880
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:233
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:86
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:216
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, bool IsUsingLTO)
Definition Clang.cpp:4727
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9810
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:287
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3570
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2348
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2970
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:372
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4011
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.
static StringRef getTriple(const Command &Job)
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:946
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?
bool hasConstantLiteralClasses() const
Are Foundation backed constant literal classes supported?
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
A processor an offloading action can target.
Definition OffloadArch.h:36
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:263
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
types::ID getType() const
Definition Action.h:153
const ToolChain * getOffloadingToolChain() const
Definition Action.h:217
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:143
BoundArch getOffloadingArch() const
Definition Action.h:216
ActionClass getKind() const
Definition Action.h:152
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:159
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:215
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:223
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:226
ActionList & getInputs()
Definition Action.h:155
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:211
bool isOffloading(OffloadKind OKind) const
Definition Action.h:229
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
std::pair< const_offload_toolchains_iterator, const_offload_toolchains_iterator > const_offload_toolchains_range
Distro - Helper class for detecting and classifying Linux distributions.
Definition Distro.h:23
bool IsGentoo() const
Definition Distro.h:134
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
llvm::SmallVector< BoundArch > getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, Action::OffloadKind Kind, const ToolChain &TC) const
Returns the set of bound architectures active for this offload kind.
Definition Driver.cpp:4039
std::string SysRoot
sysroot, if present
Definition Driver.h:193
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
const char * getPrependArg() const
Definition Driver.h:419
CC1ToolFunc CC1Main
Definition Driver.h:289
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:918
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:267
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4100
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:271
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:281
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:6148
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2544
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:430
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:217
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:214
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:177
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:168
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:250
std::string getTargetTriple() const
Definition Driver.h:427
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:256
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:171
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:223
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
bool getProbePrecompiled() const
Definition Driver.h:416
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:273
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:907
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:656
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual unsigned getMaxDwarfVersion() const
Definition ToolChain.h:665
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:689
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
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:899
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:647
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:519
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
RTTIMode getRTTIMode() const
Definition ToolChain.h:365
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:678
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 ...
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:540
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:511
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:700
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:671
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
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.
virtual bool getDefaultDebugSimpleTemplateNames() const
Returns true if this toolchain adds '-gsimple-template-names=simple' by default when generating debug...
Definition ToolChain.h:675
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.
StringRef getTripleString() const
Definition ToolChain.h:307
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:534
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:740
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:653
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:641
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:894
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:523
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
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:486
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:644
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
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:515
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:482
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:291
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:508
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:51
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:13
const char * getShortName() const
Definition Tool.h:49
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< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1053
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:677
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9305
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9288
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9313
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:9328
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9277
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9247
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8735
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9262
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9252
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:5262
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:9822
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:9636
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:9728
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)
std::optional< std::string > getAArch64TargetTuneCPU(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition AArch64.cpp:117
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:479
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:305
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::optional< StringRef > getRISCVTuneCPU(const Driver &D, const llvm::opt::ArgList &Args, SmallVectorImpl< std::string > *TuneFeatures=nullptr)
Return the tune CPU and optionally, the tune features.
Definition RISCV.cpp:433
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 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.
OffloadJobsOpt parseOffloadJobs(const llvm::opt::ArgList &Args)
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)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs, bool EmitCompressionFormat=false)
void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
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 useMachORelocatableDwarf(const llvm::Triple &T, unsigned DwarfVersion)
Whether Mach-O objects for T with DWARF DwarfVersion relocate offsets between DWARF sections.
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 addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
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)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
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.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
void addSplitMachineFunctionsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
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)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
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 addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
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:329
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:240
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:292
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:253
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:331
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:81
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition Types.cpp:265
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:49
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
Top level wrappers for InstallAPI frontend operations.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
unsigned CudaArchToID(OffloadArch Arch)
Get the numeric ID (e.g. 700) of a CUDA architecture.
Definition Cuda.cpp:133
StringRef parseMPreferVectorWidthOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
@ C
Languages that the frontend can parse and compile.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
const char * CudaVersionToString(CudaVersion V)
Definition Cuda.cpp:60
std::string getCanonicalTargetID(llvm::StringRef Processor, const llvm::StringMap< bool > &Features)
Returns canonical target ID, assuming Processor is canonical and all entries in Features are valid.
Definition TargetID.cpp:146
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:39
__builtin_riscv_nclipru_u32 int64_t
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
bool empty() const
LangStandard - Information about the properties of a particular language standard.
bool isCPlusPlus() const
isCPlusPlus - Language is a C++ variant.
static const LangStandard * getLangStandardForName(StringRef Name)
bool isCPlusPlus17() const
isCPlusPlus17 - Language is a C++17 variant (or later).
clang::Language getLanguage() const
Get the language that this standard describes.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:79
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:86