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"
27#include "clang/Basic/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
31#include "clang/Driver/Distro.h"
34#include "clang/Driver/Types.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/BinaryFormat/Magic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Frontend/Debug/Options.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Option/ArgList.h"
46#include "llvm/ProfileData/InstrProfReader.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/Process.h"
54#include "llvm/Support/YAMLParser.h"
55#include "llvm/TargetParser/AArch64TargetParser.h"
56#include "llvm/TargetParser/ARMTargetParserCommon.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/LoongArchTargetParser.h"
59#include "llvm/TargetParser/PPCTargetParser.h"
60#include "llvm/TargetParser/RISCVISAInfo.h"
61#include "llvm/TargetParser/RISCVTargetParser.h"
62#include <cctype>
63#include <iterator>
64
65using namespace clang::driver;
66using namespace clang::driver::tools;
67using namespace clang;
68using namespace llvm::opt;
69
70static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC,
72 options::OPT_fminimize_whitespace,
73 options::OPT_fno_minimize_whitespace,
74 options::OPT_fkeep_system_includes,
75 options::OPT_fno_keep_system_includes)) {
76 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
77 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
79 << A->getBaseArg().getAsString(Args)
80 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81 }
82 }
83}
84
85static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
86 // In gcc, only ARM checks this, but it seems reasonable to check universally.
87 if (Args.hasArg(options::OPT_static))
88 if (const Arg *A =
89 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
90 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
91 << "-static";
92}
93
94/// Apply \a Work on the current tool chain \a RegularToolChain and any other
95/// offloading tool chain that is associated with the current action \a JA.
96static void
98 const ToolChain &RegularToolChain,
99 llvm::function_ref<void(const ToolChain &)> Work) {
100 // Apply Work on the current/regular tool chain.
101 Work(RegularToolChain);
102
103 // Apply Work on all the offloading tool chains associated with the current
104 // action.
107 if (JA.isHostOffloading(Kind)) {
108 auto TCs = C.getOffloadToolChains(Kind);
109 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
110 Work(*II->second);
111 } else if (JA.isDeviceOffloading(Kind))
112 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
113 }
114}
115
116static bool
118 const llvm::Triple &Triple) {
119 // We use the zero-cost exception tables for Objective-C if the non-fragile
120 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
121 // later.
122 if (runtime.isNonFragile())
123 return true;
124
125 if (!Triple.isMacOSX())
126 return false;
127
128 return (!Triple.isMacOSXVersionLT(10, 5) &&
129 (Triple.getArch() == llvm::Triple::x86_64 ||
130 Triple.getArch() == llvm::Triple::arm));
131}
132
133/// Adds exception related arguments to the driver command arguments. There's a
134/// main flag, -fexceptions and also language specific flags to enable/disable
135/// C++ and Objective-C exceptions. This makes it possible to for example
136/// disable C++ exceptions but enable Objective-C exceptions.
137static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
138 const ToolChain &TC, bool KernelOrKext,
139 bool IsDeviceOffloadAction,
140 const ObjCRuntime &objcRuntime,
141 ArgStringList &CmdArgs) {
142 const llvm::Triple &Triple = TC.getTriple();
143
144 if (KernelOrKext) {
145 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
146 // arguments now to avoid warnings about unused arguments.
147 Args.ClaimAllArgs(options::OPT_fexceptions);
148 Args.ClaimAllArgs(options::OPT_fno_exceptions);
149 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
150 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
151 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
152 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
153 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
154 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
155 return false;
156 }
157
158 // See if the user explicitly enabled exceptions.
159 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
160 false);
161
162 // Async exceptions are Windows MSVC only.
163 if (Triple.isWindowsMSVCEnvironment()) {
164 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
165 options::OPT_fno_async_exceptions, false);
166 if (EHa) {
167 CmdArgs.push_back("-fasync-exceptions");
168 EH = true;
169 }
170 }
171
172 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
173 // is not necessarily sensible, but follows GCC.
174 if (types::isObjC(InputType) &&
175 Args.hasFlag(options::OPT_fobjc_exceptions,
176 options::OPT_fno_objc_exceptions, true)) {
177 CmdArgs.push_back("-fobjc-exceptions");
178
179 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
180 }
181
182 if (types::isCXX(InputType)) {
183 // Disable C++ EH by default on XCore, PS4/PS5 and GPU targets.
184 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
185 !Triple.isPS() && !Triple.isDriverKit() &&
186 !(Triple.isGPU() && !IsDeviceOffloadAction);
187 Arg *ExceptionArg = Args.getLastArg(
188 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
189 options::OPT_fexceptions, options::OPT_fno_exceptions);
190 if (ExceptionArg)
191 CXXExceptionsEnabled =
192 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
193 ExceptionArg->getOption().matches(options::OPT_fexceptions);
194
195 if (CXXExceptionsEnabled) {
196 CmdArgs.push_back("-fcxx-exceptions");
197
198 EH = true;
199 }
200 }
201
202 // OPT_fignore_exceptions means exception could still be thrown,
203 // but no clean up or catch would happen in current module.
204 // So we do not set EH to false.
205 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
206
207 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
208 options::OPT_fno_assume_nothrow_exception_dtor);
209
210 if (EH)
211 CmdArgs.push_back("-fexceptions");
212 return EH;
213}
214
215static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
216 const JobAction &JA) {
217 bool Default = true;
218 if (TC.getTriple().isOSDarwin()) {
219 // The native darwin assembler doesn't support the linker_option directives,
220 // so we disable them if we think the .s file will be passed to it.
222 }
223 // The linker_option directives are intended for host compilation.
226 Default = false;
227 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
228 Default);
229}
230
231/// Add a CC1 option to specify the debug compilation directory.
232static const char *addDebugCompDirArg(const ArgList &Args,
233 ArgStringList &CmdArgs,
234 const llvm::vfs::FileSystem &VFS) {
235 std::string DebugCompDir;
236 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
237 options::OPT_fdebug_compilation_dir_EQ))
238 DebugCompDir = A->getValue();
239
240 if (DebugCompDir.empty()) {
241 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
242 DebugCompDir = std::move(*CWD);
243 else
244 return nullptr;
245 }
246 CmdArgs.push_back(
247 Args.MakeArgString("-fdebug-compilation-dir=" + DebugCompDir));
248 StringRef Path(CmdArgs.back());
249 return Path.substr(Path.find('=') + 1).data();
250}
251
252static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
253 const char *DebugCompilationDir,
254 const char *OutputFileName) {
255 // No need to generate a value for -object-file-name if it was provided.
256 for (auto *Arg : Args.filtered(options::OPT_Xclang))
257 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
258 return;
259
260 if (Args.hasArg(options::OPT_object_file_name_EQ))
261 return;
262
263 SmallString<128> ObjFileNameForDebug(OutputFileName);
264 if (ObjFileNameForDebug != "-" &&
265 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
266 (!DebugCompilationDir ||
267 llvm::sys::path::is_absolute(DebugCompilationDir))) {
268 // Make the path absolute in the debug infos like MSVC does.
269 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
270 }
271 // If the object file name is a relative path, then always use Windows
272 // backslash style as -object-file-name is used for embedding object file path
273 // in codeview and it can only be generated when targeting on Windows.
274 // Otherwise, just use native absolute path.
275 llvm::sys::path::Style Style =
276 llvm::sys::path::is_absolute(ObjFileNameForDebug)
277 ? llvm::sys::path::Style::native
278 : llvm::sys::path::Style::windows_backslash;
279 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
280 Style);
281 CmdArgs.push_back(
282 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
283}
284
285/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
286static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
287 const ArgList &Args, ArgStringList &CmdArgs) {
288 auto AddOneArg = [&](StringRef Map, StringRef Name) {
289 if (!Map.contains('='))
290 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
291 else
292 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
293 };
294
295 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
296 options::OPT_fdebug_prefix_map_EQ)) {
297 AddOneArg(A->getValue(), A->getOption().getName());
298 A->claim();
299 }
300 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
301 if (GlobalRemapEntry.empty())
302 return;
303 AddOneArg(GlobalRemapEntry, "environment");
304}
305
306/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
307static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
308 ArgStringList &CmdArgs) {
309 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
310 options::OPT_fmacro_prefix_map_EQ)) {
311 StringRef Map = A->getValue();
312 if (!Map.contains('='))
313 D.Diag(diag::err_drv_invalid_argument_to_option)
314 << Map << A->getOption().getName();
315 else
316 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
317 A->claim();
318 }
319}
320
321/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
322static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
323 ArgStringList &CmdArgs) {
324 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
325 options::OPT_fcoverage_prefix_map_EQ)) {
326 StringRef Map = A->getValue();
327 if (!Map.contains('='))
328 D.Diag(diag::err_drv_invalid_argument_to_option)
329 << Map << A->getOption().getName();
330 else
331 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
332 A->claim();
333 }
334}
335
336/// Add -x lang to \p CmdArgs for \p Input.
337static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
338 ArgStringList &CmdArgs) {
339 // When using -verify-pch, we don't want to provide the type
340 // 'precompiled-header' if it was inferred from the file extension
341 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
342 return;
343
344 CmdArgs.push_back("-x");
345 if (Args.hasArg(options::OPT_rewrite_objc))
346 CmdArgs.push_back(types::getTypeName(types::TY_ObjCXX));
347 else {
348 // Map the driver type to the frontend type. This is mostly an identity
349 // mapping, except that the distinction between module interface units
350 // and other source files does not exist at the frontend layer.
351 const char *ClangType;
352 switch (Input.getType()) {
353 case types::TY_CXXModule:
354 case types::TY_CXXStdModule:
355 ClangType = "c++";
356 break;
357 case types::TY_PP_CXXModule:
358 ClangType = "c++-cpp-output";
359 break;
360 default:
361 ClangType = types::getTypeName(Input.getType());
362 break;
363 }
364 CmdArgs.push_back(ClangType);
365 }
366}
367
369 const JobAction &JA, const InputInfo &Output,
370 const ArgList &Args, SanitizerArgs &SanArgs,
371 ArgStringList &CmdArgs) {
372 const Driver &D = TC.getDriver();
373 const llvm::Triple &T = TC.getTriple();
374 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
375 options::OPT_fprofile_generate_EQ,
376 options::OPT_fno_profile_generate);
377 if (PGOGenerateArg &&
378 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
379 PGOGenerateArg = nullptr;
380
381 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
382
383 auto *ProfileGenerateArg = Args.getLastArg(
384 options::OPT_fprofile_instr_generate,
385 options::OPT_fprofile_instr_generate_EQ,
386 options::OPT_fno_profile_instr_generate);
387 if (ProfileGenerateArg &&
388 ProfileGenerateArg->getOption().matches(
389 options::OPT_fno_profile_instr_generate))
390 ProfileGenerateArg = nullptr;
391
392 if (PGOGenerateArg && ProfileGenerateArg)
393 D.Diag(diag::err_drv_argument_not_allowed_with)
394 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
395
396 auto *ProfileUseArg = getLastProfileUseArg(Args);
397
398 if (PGOGenerateArg && ProfileUseArg)
399 D.Diag(diag::err_drv_argument_not_allowed_with)
400 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
401
402 if (ProfileGenerateArg && ProfileUseArg)
403 D.Diag(diag::err_drv_argument_not_allowed_with)
404 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
405
406 if (CSPGOGenerateArg && PGOGenerateArg) {
407 D.Diag(diag::err_drv_argument_not_allowed_with)
408 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
409 PGOGenerateArg = nullptr;
410 }
411
412 if (TC.getTriple().isOSAIX()) {
413 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
414 D.Diag(diag::err_drv_unsupported_opt_for_target)
415 << ProfileSampleUseArg->getSpelling() << TC.getTripleString();
416 }
417
418 if (ProfileGenerateArg) {
419 if (ProfileGenerateArg->getOption().matches(
420 options::OPT_fprofile_instr_generate_EQ))
421 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
422 ProfileGenerateArg->getValue()));
423 // The default is to use Clang Instrumentation.
424 CmdArgs.push_back("-fprofile-instrument=clang");
425 if (TC.getTriple().isWindowsMSVCEnvironment() &&
426 Args.hasFlag(options::OPT_frtlib_defaultlib,
427 options::OPT_fno_rtlib_defaultlib, true)) {
428 // Add dependent lib for clang_rt.profile
429 CmdArgs.push_back(Args.MakeArgString(
430 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
431 }
432 }
433
434 if (auto *ColdFuncCoverageArg = Args.getLastArg(
435 options::OPT_fprofile_generate_cold_function_coverage,
436 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
437 SmallString<128> Path(
438 ColdFuncCoverageArg->getOption().matches(
439 options::OPT_fprofile_generate_cold_function_coverage_EQ)
440 ? ColdFuncCoverageArg->getValue()
441 : "");
442 llvm::sys::path::append(Path, "default_%m.profraw");
443 // FIXME: Idealy the file path should be passed through
444 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
445 // shared with other profile use path(see PGOOptions), we need to refactor
446 // PGOOptions to make it work.
447 CmdArgs.push_back("-mllvm");
448 CmdArgs.push_back(Args.MakeArgString(
449 Twine("--instrument-cold-function-only-path=") + Path));
450 CmdArgs.push_back("-mllvm");
451 CmdArgs.push_back("--pgo-instrument-cold-function-only");
452 CmdArgs.push_back("-mllvm");
453 CmdArgs.push_back("--pgo-function-entry-coverage");
454 CmdArgs.push_back("-fprofile-instrument=sample-coldcov");
455 }
456
457 if (auto *A = Args.getLastArg(options::OPT_ftemporal_profile)) {
458 if (!PGOGenerateArg && !CSPGOGenerateArg)
459 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
460 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
461 CmdArgs.push_back("-mllvm");
462 CmdArgs.push_back("--pgo-temporal-instrumentation");
463 }
464
465 Arg *PGOGenArg = nullptr;
466 if (PGOGenerateArg) {
467 assert(!CSPGOGenerateArg);
468 PGOGenArg = PGOGenerateArg;
469 CmdArgs.push_back("-fprofile-instrument=llvm");
470 }
471 if (CSPGOGenerateArg) {
472 assert(!PGOGenerateArg);
473 PGOGenArg = CSPGOGenerateArg;
474 CmdArgs.push_back("-fprofile-instrument=csllvm");
475 }
476 if (PGOGenArg) {
477 if (TC.getTriple().isWindowsMSVCEnvironment() &&
478 Args.hasFlag(options::OPT_frtlib_defaultlib,
479 options::OPT_fno_rtlib_defaultlib, true)) {
480 // Add dependent lib for clang_rt.profile
481 CmdArgs.push_back(Args.MakeArgString(
482 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
483 }
484 if (PGOGenArg->getOption().matches(
485 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
486 : options::OPT_fcs_profile_generate_EQ)) {
487 SmallString<128> Path(PGOGenArg->getValue());
488 llvm::sys::path::append(Path, "default_%m.profraw");
489 CmdArgs.push_back(
490 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
491 }
492 }
493
494 if (ProfileUseArg) {
495 SmallString<128> UsePathBuf;
496 StringRef UsePath;
497 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
498 UsePath = ProfileUseArg->getValue();
499 else if ((ProfileUseArg->getOption().matches(
500 options::OPT_fprofile_use_EQ) ||
501 ProfileUseArg->getOption().matches(
502 options::OPT_fprofile_instr_use))) {
503 UsePathBuf =
504 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
505 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(UsePathBuf))
506 llvm::sys::path::append(UsePathBuf, "default.profdata");
507 UsePath = UsePathBuf;
508 }
509 auto ReaderOrErr =
510 llvm::IndexedInstrProfReader::create(UsePath, D.getVFS());
511 if (auto E = ReaderOrErr.takeError()) {
512 auto DiagID = D.getDiags().getCustomDiagID(
513 DiagnosticsEngine::Error, "Error in reading profile %0: %1");
514 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
515 D.Diag(DiagID) << UsePath.str() << EI.message();
516 });
517 } else {
518 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
519 std::move(ReaderOrErr.get());
520 StringRef UseKind;
521 // Currently memprof profiles are only added at the IR level. Mark the
522 // profile type as IR in that case as well and the subsequent matching
523 // needs to detect which is available (might be one or both).
524 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
525 if (PGOReader->hasCSIRLevelProfile())
526 UseKind = "csllvm";
527 else
528 UseKind = "llvm";
529 } else
530 UseKind = "clang";
531
532 CmdArgs.push_back(
533 Args.MakeArgString("-fprofile-instrument-use=" + UseKind));
534 CmdArgs.push_back(
535 Args.MakeArgString("-fprofile-instrument-use-path=" + UsePath));
536 }
537 }
538
539 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
540 options::OPT_fno_test_coverage, false) ||
541 Args.hasArg(options::OPT_coverage);
542 bool EmitCovData = TC.needsGCovInstrumentation(Args);
543
544 if (Args.hasFlag(options::OPT_fcoverage_mapping,
545 options::OPT_fno_coverage_mapping, false)) {
546 if (!ProfileGenerateArg)
547 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
548 << "-fcoverage-mapping"
549 << "-fprofile-instr-generate";
550
551 CmdArgs.push_back("-fcoverage-mapping");
552 }
553
554 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
555 false)) {
556 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
557 options::OPT_fno_coverage_mapping, false))
558 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
559 << "-fcoverage-mcdc"
560 << "-fcoverage-mapping";
561
562 CmdArgs.push_back("-fcoverage-mcdc");
563 }
564
565 StringRef CoverageCompDir;
566 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
567 options::OPT_fcoverage_compilation_dir_EQ))
568 CoverageCompDir = A->getValue();
569 if (CoverageCompDir.empty()) {
570 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
571 CmdArgs.push_back(
572 Args.MakeArgString(Twine("-fcoverage-compilation-dir=") + *CWD));
573 } else
574 CmdArgs.push_back(Args.MakeArgString(Twine("-fcoverage-compilation-dir=") +
575 CoverageCompDir));
576
577 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
578 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
579 if (!Args.hasArg(options::OPT_coverage))
580 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
581 << "-fprofile-exclude-files="
582 << "--coverage";
583
584 StringRef v = Arg->getValue();
585 CmdArgs.push_back(
586 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
587 }
588
589 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
590 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
591 if (!Args.hasArg(options::OPT_coverage))
592 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
593 << "-fprofile-filter-files="
594 << "--coverage";
595
596 StringRef v = Arg->getValue();
597 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
598 }
599
600 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
601 StringRef Val = A->getValue();
602 if (Val == "atomic" || Val == "prefer-atomic")
603 CmdArgs.push_back("-fprofile-update=atomic");
604 else if (Val != "single")
605 D.Diag(diag::err_drv_unsupported_option_argument)
606 << A->getSpelling() << Val;
607 }
608 if (const auto *A = Args.getLastArg(options::OPT_fprofile_continuous)) {
609 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
610 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
611 << A->getSpelling()
612 << "-fprofile-generate, -fprofile-instr-generate, or "
613 "-fcs-profile-generate";
614 else {
615 CmdArgs.push_back("-fprofile-continuous");
616 // Platforms that require a bias variable:
617 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
618 CmdArgs.push_back("-mllvm");
619 CmdArgs.push_back("-runtime-counter-relocation");
620 }
621 // -fprofile-instr-generate does not decide the profile file name in the
622 // FE, and so it does not define the filename symbol
623 // (__llvm_profile_filename). Instead, the runtime uses the name
624 // "default.profraw" for the profile file. When continuous mode is ON, we
625 // will create the filename symbol so that we can insert the "%c"
626 // modifier.
627 if (ProfileGenerateArg &&
628 (ProfileGenerateArg->getOption().matches(
629 options::OPT_fprofile_instr_generate) ||
630 (ProfileGenerateArg->getOption().matches(
631 options::OPT_fprofile_instr_generate_EQ) &&
632 strlen(ProfileGenerateArg->getValue()) == 0)))
633 CmdArgs.push_back("-fprofile-instrument-path=default.profraw");
634 }
635 }
636
637 int FunctionGroups = 1;
638 int SelectedFunctionGroup = 0;
639 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
640 StringRef Val = A->getValue();
641 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
642 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
643 }
644 if (const auto *A =
645 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
646 StringRef Val = A->getValue();
647 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
648 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
649 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
650 }
651 if (FunctionGroups != 1)
652 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
653 Twine(FunctionGroups)));
654 if (SelectedFunctionGroup != 0)
655 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
656 Twine(SelectedFunctionGroup)));
657
658 // Leave -fprofile-dir= an unused argument unless .gcda emission is
659 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
660 // the flag used. There is no -fno-profile-dir, so the user has no
661 // targeted way to suppress the warning.
662 Arg *FProfileDir = nullptr;
663 if (Args.hasArg(options::OPT_fprofile_arcs) ||
664 Args.hasArg(options::OPT_coverage))
665 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
666
667 // Put the .gcno and .gcda files (if needed) next to the primary output file,
668 // or fall back to a file in the current directory for `clang -c --coverage
669 // d/a.c` in the absence of -o.
670 if (EmitCovNotes || EmitCovData) {
671 SmallString<128> CoverageFilename;
672 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
673 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
674 // path separator.
675 CoverageFilename = DumpDir->getValue();
676 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
677 } else if (Arg *FinalOutput =
678 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
679 CoverageFilename = FinalOutput->getValue();
680 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
681 CoverageFilename = FinalOutput->getValue();
682 } else {
683 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
684 }
685 if (llvm::sys::path::is_relative(CoverageFilename))
686 (void)D.getVFS().makeAbsolute(CoverageFilename);
687 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
688 if (EmitCovNotes) {
689 CmdArgs.push_back(
690 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
691 }
692
693 if (EmitCovData) {
694 if (FProfileDir) {
695 SmallString<128> Gcno = std::move(CoverageFilename);
696 CoverageFilename = FProfileDir->getValue();
697 llvm::sys::path::append(CoverageFilename, Gcno);
698 }
699 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
700 CmdArgs.push_back(
701 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
702 }
703 }
704}
705
706static void
707RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
708 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
709 unsigned DwarfVersion,
710 llvm::DebuggerKind DebuggerTuning) {
711 addDebugInfoKind(CmdArgs, DebugInfoKind);
712 if (DwarfVersion > 0)
713 CmdArgs.push_back(
714 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
715 switch (DebuggerTuning) {
716 case llvm::DebuggerKind::GDB:
717 CmdArgs.push_back("-debugger-tuning=gdb");
718 break;
719 case llvm::DebuggerKind::LLDB:
720 CmdArgs.push_back("-debugger-tuning=lldb");
721 break;
722 case llvm::DebuggerKind::SCE:
723 CmdArgs.push_back("-debugger-tuning=sce");
724 break;
725 case llvm::DebuggerKind::DBX:
726 CmdArgs.push_back("-debugger-tuning=dbx");
727 break;
728 default:
729 break;
730 }
731}
732
734 const ArgList &Args,
735 ArgStringList &CmdArgs,
736 bool IsCC1As = false) {
737 // If no version was requested by the user, use the default value from the
738 // back end. This is consistent with the value returned from
739 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
740 // requiring the corresponding llvm to have the AMDGPU target enabled,
741 // provided the user (e.g. front end tests) can use the default.
743 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
744 CmdArgs.insert(CmdArgs.begin() + 1,
745 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
746 Twine(CodeObjVer)));
747 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
748 // -cc1as does not accept -mcode-object-version option.
749 if (!IsCC1As)
750 CmdArgs.insert(CmdArgs.begin() + 1,
751 Args.MakeArgString(Twine("-mcode-object-version=") +
752 Twine(CodeObjVer)));
753 }
754}
755
756static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
757 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
758 D.getVFS().getBufferForFile(Path);
759 if (!MemBuf)
760 return false;
761 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
762 if (Magic == llvm::file_magic::unknown)
763 return false;
764 // Return true for both raw Clang AST files and object files which may
765 // contain a __clangast section.
766 if (Magic == llvm::file_magic::clang_ast)
767 return true;
769 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
770 return !Obj.takeError();
771}
772
773static bool gchProbe(const Driver &D, StringRef Path) {
774 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
775 if (!Status)
776 return false;
777
778 if (Status->isDirectory()) {
779 std::error_code EC;
780 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
781 !EC && DI != DE; DI = DI.increment(EC)) {
782 if (maybeHasClangPchSignature(D, DI->path()))
783 return true;
784 }
785 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
786 return false;
787 }
788
789 if (maybeHasClangPchSignature(D, Path))
790 return true;
791 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
792 return false;
793}
794
795void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
796 const Driver &D, const ArgList &Args,
797 ArgStringList &CmdArgs,
798 const InputInfo &Output,
799 const InputInfoList &Inputs) const {
800 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
801
803
804 Args.AddLastArg(CmdArgs, options::OPT_C);
805 Args.AddLastArg(CmdArgs, options::OPT_CC);
806
807 // Handle dependency file generation.
808 Arg *ArgM = Args.getLastArg(options::OPT_MM);
809 if (!ArgM)
810 ArgM = Args.getLastArg(options::OPT_M);
811 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
812 if (!ArgMD)
813 ArgMD = Args.getLastArg(options::OPT_MD);
814
815 // -M and -MM imply -w.
816 if (ArgM)
817 CmdArgs.push_back("-w");
818 else
819 ArgM = ArgMD;
820
821 if (ArgM) {
823 // Determine the output location.
824 const char *DepFile;
825 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
826 DepFile = MF->getValue();
827 C.addFailureResultFile(DepFile, &JA);
828 } else if (Output.getType() == types::TY_Dependencies) {
829 DepFile = Output.getFilename();
830 } else if (!ArgMD) {
831 DepFile = "-";
832 } else {
833 DepFile = getDependencyFileName(Args, Inputs);
834 C.addFailureResultFile(DepFile, &JA);
835 }
836 CmdArgs.push_back("-dependency-file");
837 CmdArgs.push_back(DepFile);
838 }
839 // Cmake generates dependency files using all compilation options specified
840 // by users. Claim those not used for dependency files.
842 Args.ClaimAllArgs(options::OPT_offload_compress);
843 Args.ClaimAllArgs(options::OPT_no_offload_compress);
844 Args.ClaimAllArgs(options::OPT_offload_jobs_EQ);
845 }
846
847 bool HasTarget = false;
848 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
849 HasTarget = true;
850 A->claim();
851 if (A->getOption().matches(options::OPT_MT)) {
852 A->render(Args, CmdArgs);
853 } else {
854 CmdArgs.push_back("-MT");
855 SmallString<128> Quoted;
856 quoteMakeTarget(A->getValue(), Quoted);
857 CmdArgs.push_back(Args.MakeArgString(Quoted));
858 }
859 }
860
861 // Add a default target if one wasn't specified.
862 if (!HasTarget) {
863 const char *DepTarget;
864
865 // If user provided -o, that is the dependency target, except
866 // when we are only generating a dependency file.
867 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
868 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
869 DepTarget = OutputOpt->getValue();
870 } else {
871 // Otherwise derive from the base input.
872 //
873 // FIXME: This should use the computed output file location.
874 SmallString<128> P(Inputs[0].getBaseInput());
875 llvm::sys::path::replace_extension(P, "o");
876 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
877 }
878
879 CmdArgs.push_back("-MT");
880 SmallString<128> Quoted;
881 quoteMakeTarget(DepTarget, Quoted);
882 CmdArgs.push_back(Args.MakeArgString(Quoted));
883 }
884
885 if (ArgM->getOption().matches(options::OPT_M) ||
886 ArgM->getOption().matches(options::OPT_MD))
887 CmdArgs.push_back("-sys-header-deps");
888
889 // Determine module file deps mode.
890 StringRef ModuleFileDepsVal;
891 if (Arg *A = Args.getLastArg(options::OPT_fmodule_file_deps_EQ,
892 options::OPT_fmodule_file_deps,
893 options::OPT_fno_module_file_deps)) {
894 if (A->getOption().matches(options::OPT_fmodule_file_deps_EQ))
895 ModuleFileDepsVal = A->getValue();
896 else if (A->getOption().matches(options::OPT_fmodule_file_deps))
897 ModuleFileDepsVal = "all";
898 else
899 ModuleFileDepsVal = "none";
900 } else if (isa<PrecompileJobAction>(JA)) {
901 ModuleFileDepsVal = "all";
902 }
903 if (!ModuleFileDepsVal.empty() && ModuleFileDepsVal != "none")
904 CmdArgs.push_back(
905 Args.MakeArgString("-module-file-deps=" + ModuleFileDepsVal));
906 }
907
908 if (Args.hasArg(options::OPT_MG)) {
909 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
910 ArgM->getOption().matches(options::OPT_MMD))
911 D.Diag(diag::err_drv_mg_requires_m_or_mm);
912 CmdArgs.push_back("-MG");
913 }
914
915 Args.AddLastArg(CmdArgs, options::OPT_MP);
916 Args.AddLastArg(CmdArgs, options::OPT_MV);
917
918 bool UsesLLVMOffloading = Args.hasFlag(
919 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
920 bool UsesOffloadInclude =
921 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc, true);
922 bool NoBuiltinInc = Args.hasArg(options::OPT_nobuiltininc);
923
924 // Add offload include arguments for CUDA/HIP when using LLVM offloading. We
925 // want to pull in our wrappers instead of the vendor headers.
926 if (UsesLLVMOffloading) {
927 if (UsesOffloadInclude && !NoBuiltinInc) {
928 auto AddOffloadHeadersInclude = [&](StringRef IncludeSubdir,
929 StringRef RuntimeHeader) {
930 SmallString<128> OffloadInclude(D.Dir);
931 llvm::sys::path::append(OffloadInclude, "..", "include", "offload");
932 if (!IncludeSubdir.empty())
933 llvm::sys::path::append(OffloadInclude, IncludeSubdir);
934 CmdArgs.append({"-internal-isystem", Args.MakeArgString(OffloadInclude),
935 "-include", Args.MakeArgString(RuntimeHeader)});
936 };
937 auto AddForcedInclude = [&](StringRef Header) {
938 CmdArgs.push_back("-include");
939 CmdArgs.push_back(Args.MakeArgString(Header));
940 };
941 AddForcedInclude("__clang_gpu_runtime_wrapper.h");
942 AddForcedInclude("__clang_gpu_builtin_vars.h");
943 AddForcedInclude("__clang_gpu_device_functions.h");
944 AddForcedInclude("__clang_gpu_intrinsics.h");
946 AddOffloadHeadersInclude("cuda", "cuda_runtime.h");
948 !Args.hasArg(options::OPT_nohipwrapperinc)) {
949 // HIP code commonly includes this as "hip/hip_runtime.h".
950 AddOffloadHeadersInclude("", "hip/hip_runtime.h");
951 }
952 }
953 } else {
954 // Add offload include arguments specific for CUDA/HIP/SYCL. This must
955 // happen before we -I or -include anything else, because we must pick up
956 // the CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL
957 // installation, rather than from e.g. /usr/local/include.
959 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
961 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
963 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
964
965 // If we are offloading to a target via OpenMP we need to include the
966 // openmp_wrappers folder which contains alternative system headers.
968 !Args.hasArg(options::OPT_nostdinc) && UsesOffloadInclude &&
969 getToolChain().getTriple().isGPU()) {
970 if (!NoBuiltinInc) {
971 // Add openmp_wrappers/* to our system include path. This lets us
972 // wrap standard library headers.
973 SmallString<128> P(D.ResourceDir);
974 llvm::sys::path::append(P, "include");
975 llvm::sys::path::append(P, "openmp_wrappers");
976 CmdArgs.push_back("-internal-isystem");
977 CmdArgs.push_back(Args.MakeArgString(P));
978 }
979
980 CmdArgs.push_back("-include");
981 CmdArgs.push_back("__clang_openmp_device_functions.h");
982 }
983 }
984
985 // Add -i* options, and automatically translate to
986 // -include-pch/-include-pth for transparent PCH support. It's
987 // wonky, but we include looking for .gch so we can support seamless
988 // replacement into a build system already set up to be generating
989 // .gch files.
990
991 if (getToolChain().getDriver().IsCLMode()) {
992 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
993 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
994 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
996 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
997 // -fpch-instantiate-templates is the default when creating
998 // precomp using /Yc
999 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1000 options::OPT_fno_pch_instantiate_templates, true))
1001 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1002 }
1003 if (YcArg || YuArg) {
1004 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1005 if (!isa<PrecompileJobAction>(JA)) {
1006 CmdArgs.push_back("-include-pch");
1007 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1008 C, !ThroughHeader.empty()
1009 ? ThroughHeader
1010 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1011 }
1012
1013 if (ThroughHeader.empty()) {
1014 CmdArgs.push_back(Args.MakeArgString(
1015 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1016 } else {
1017 CmdArgs.push_back(
1018 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1019 }
1020 }
1021 }
1022
1023 bool RenderedImplicitInclude = false;
1024 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1025 if (A->getOption().matches(options::OPT_include) &&
1026 D.getProbePrecompiled()) {
1027 // Handling of gcc-style gch precompiled headers.
1028 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1029 RenderedImplicitInclude = true;
1030
1031 bool FoundPCH = false;
1032 SmallString<128> P(A->getValue());
1033 // We want the files to have a name like foo.h.pch. Add a dummy extension
1034 // so that replace_extension does the right thing.
1035 P += ".dummy";
1036 llvm::sys::path::replace_extension(P, "pch");
1037 if (D.getVFS().exists(P))
1038 FoundPCH = true;
1039
1040 if (!FoundPCH) {
1041 // For GCC compat, probe for a file or directory ending in .gch instead.
1042 llvm::sys::path::replace_extension(P, "gch");
1043 FoundPCH = gchProbe(D, P.str());
1044 }
1045
1046 if (FoundPCH) {
1047 if (IsFirstImplicitInclude) {
1048 A->claim();
1049 CmdArgs.push_back("-include-pch");
1050 CmdArgs.push_back(Args.MakeArgString(P));
1051 continue;
1052 } else {
1053 // Ignore the PCH if not first on command line and emit warning.
1054 D.Diag(diag::warn_drv_pch_not_first_include) << P
1055 << A->getAsString(Args);
1056 }
1057 }
1058 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1059 // Handling of paths which must come late. These entries are handled by
1060 // the toolchain itself after the resource dir is inserted in the right
1061 // search order.
1062 // Do not claim the argument so that the use of the argument does not
1063 // silently go unnoticed on toolchains which do not honour the option.
1064 continue;
1065 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1066 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1067 continue;
1068 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1069 // This is used only by the driver. No need to pass to cc1.
1070 continue;
1071 }
1072
1073 // Not translated, render as usual.
1074 A->claim();
1075 A->render(Args, CmdArgs);
1076 }
1077
1078 if (C.isOffloadingHostKind(Action::OFK_Cuda) ||
1080 // Collect all enabled NVPTX architectures.
1081 std::set<unsigned> ArchIDs;
1082 for (auto &I : llvm::make_range(C.getOffloadToolChains(Action::OFK_Cuda))) {
1083 const ToolChain *TC = I.second;
1084 for (BoundArch Arch :
1085 D.getOffloadArchs(C, C.getArgs(), Action::OFK_Cuda, *TC)) {
1086 if (Arch.Arch.isNVPTX())
1087 ArchIDs.insert(CudaArchToID(Arch.Arch));
1088 }
1089 }
1090
1091 if (!ArchIDs.empty()) {
1092 SmallString<128> List;
1093 llvm::raw_svector_ostream OS(List);
1094 llvm::interleave(ArchIDs, OS, ",");
1095 CmdArgs.push_back(Args.MakeArgString("-D__CUDA_ARCH_LIST__=" + List));
1096 }
1097 }
1098
1099 Args.addAllArgs(CmdArgs,
1100 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1101 options::OPT_F, options::OPT_embed_dir_EQ});
1102
1103 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1104
1105 // FIXME: There is a very unfortunate problem here, some troubled
1106 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1107 // really support that we would have to parse and then translate
1108 // those options. :(
1109 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1110 options::OPT_Xpreprocessor);
1111
1112 // -I- is a deprecated GCC feature, reject it.
1113 if (Arg *A = Args.getLastArg(options::OPT_I_))
1114 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1115
1116 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1117 // -isysroot to the CC1 invocation.
1118 StringRef sysroot = C.getSysRoot();
1119 if (sysroot != "") {
1120 if (!Args.hasArg(options::OPT_isysroot)) {
1121 CmdArgs.push_back("-isysroot");
1122 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1123 }
1124 }
1125
1126 // Parse additional include paths from environment variables.
1127 // FIXME: We should probably sink the logic for handling these from the
1128 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1129 // CPATH - included following the user specified includes (but prior to
1130 // builtin and standard includes).
1131 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1132 // C_INCLUDE_PATH - system includes enabled when compiling C.
1133 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1134 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1135 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1136 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1137 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1138 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1139 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1140
1141 // While adding the include arguments, we also attempt to retrieve the
1142 // arguments of related offloading toolchains or arguments that are specific
1143 // of an offloading programming model.
1144
1145 // Add C++ include arguments, if needed.
1146 if (types::isCXX(Inputs[0].getType())) {
1147 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1149 C, JA, getToolChain(),
1150 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1151 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1152 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1153 });
1154 }
1155
1156 // If we are compiling for a GPU target with the LLVM environment we want to
1157 // override the system headers with ones created by the 'libc' project if
1158 // present.
1159 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1160 // OffloadKind as an argument.
1161 bool OffloadUsesLLVMLibc =
1162 C.getActiveOffloadKinds() == Action::OFK_OpenMP ||
1163 (C.getActiveOffloadKinds() != Action::OFK_None &&
1164 getToolChain().getTriple().getEnvironment() == llvm::Triple::LLVM);
1165 if (!Args.hasArg(options::OPT_nostdinc) &&
1166 Args.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
1167 true) &&
1168 !Args.hasArg(options::OPT_nobuiltininc) && OffloadUsesLLVMLibc) {
1169 SmallString<128> P(D.ResourceDir);
1170 llvm::sys::path::append(P, "include");
1171 llvm::sys::path::append(P, "llvm_libc_wrappers");
1172 CmdArgs.push_back("-internal-isystem");
1173 CmdArgs.push_back(Args.MakeArgString(P));
1174 }
1175
1176 // Add system include arguments for all targets but IAMCU.
1177 if (!IsIAMCU)
1179 [&Args, &CmdArgs](const ToolChain &TC) {
1180 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1181 });
1182 else {
1183 // For IAMCU add special include arguments.
1184 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1185 }
1186
1187 addMacroPrefixMapArg(D, Args, CmdArgs);
1188 addCoveragePrefixMapArg(D, Args, CmdArgs);
1189
1190 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1191 options::OPT_fno_file_reproducible);
1192
1193 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1194 CmdArgs.push_back("-source-date-epoch");
1195 CmdArgs.push_back(Args.MakeArgString(Epoch));
1196 }
1197
1198 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1199 options::OPT_fno_define_target_os_macros);
1200}
1201
1202// FIXME: Move to target hook.
1203static bool isSignedCharDefault(const llvm::Triple &Triple) {
1204 switch (Triple.getArch()) {
1205 default:
1206 return true;
1207
1208 case llvm::Triple::aarch64:
1209 case llvm::Triple::aarch64_32:
1210 case llvm::Triple::aarch64_be:
1211 case llvm::Triple::arm:
1212 case llvm::Triple::armeb:
1213 case llvm::Triple::thumb:
1214 case llvm::Triple::thumbeb:
1215 if (Triple.isOSDarwin() || Triple.isOSWindows())
1216 return true;
1217 return false;
1218
1219 case llvm::Triple::ppc:
1220 case llvm::Triple::ppc64:
1221 if (Triple.isOSDarwin())
1222 return true;
1223 return false;
1224
1225 case llvm::Triple::csky:
1226 case llvm::Triple::hexagon:
1227 case llvm::Triple::msp430:
1228 case llvm::Triple::ppcle:
1229 case llvm::Triple::ppc64le:
1230 case llvm::Triple::riscv32:
1231 case llvm::Triple::riscv64:
1232 case llvm::Triple::riscv32be:
1233 case llvm::Triple::riscv64be:
1234 case llvm::Triple::systemz:
1235 case llvm::Triple::xcore:
1236 case llvm::Triple::xtensa:
1237 return false;
1238 }
1239}
1240
1241static bool hasMultipleInvocations(const llvm::Triple &Triple,
1242 const ArgList &Args) {
1243 // Supported only on Darwin where we invoke the compiler multiple times
1244 // followed by an invocation to lipo.
1245 if (!Triple.isOSDarwin())
1246 return false;
1247 // If more than one "-arch <arch>" is specified, we're targeting multiple
1248 // architectures resulting in a fat binary.
1249 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1250}
1251
1252static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1253 const llvm::Triple &Triple) {
1254 // When enabling remarks, we need to error if:
1255 // * The remark file is specified but we're targeting multiple architectures,
1256 // which means more than one remark file is being generated.
1258 bool hasExplicitOutputFile =
1259 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1260 if (hasMultipleInvocations && hasExplicitOutputFile) {
1261 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1262 << "-foptimization-record-file";
1263 return false;
1264 }
1265 return true;
1266}
1267
1268static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1269 const llvm::Triple &Triple,
1270 const InputInfo &Input,
1271 const InputInfo &Output, const JobAction &JA) {
1272 StringRef Format = "yaml";
1273 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1274 Format = A->getValue();
1275
1276 CmdArgs.push_back("-opt-record-file");
1277
1278 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1279 if (A) {
1280 CmdArgs.push_back(A->getValue());
1281 } else {
1282 bool hasMultipleArchs =
1283 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1284 Args.getAllArgValues(options::OPT_arch).size() > 1;
1285
1287
1288 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1289 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1290 F = FinalOutput->getValue();
1291 } else {
1292 if (Format != "yaml" && // For YAML, keep the original behavior.
1293 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1294 Output.isFilename())
1295 F = Output.getFilename();
1296 }
1297
1298 if (F.empty()) {
1299 // Use the input filename.
1300 F = llvm::sys::path::stem(Input.getBaseInput());
1301
1302 // If we're compiling for an offload architecture (i.e. a CUDA device),
1303 // we need to make the file name for the device compilation different
1304 // from the host compilation.
1307 llvm::sys::path::replace_extension(F, "");
1309 Triple.str());
1310 F += "-";
1311 F += JA.getOffloadingArch().ArchName;
1312 }
1313 }
1314
1315 // If we're having more than one "-arch", we should name the files
1316 // differently so that every cc1 invocation writes to a different file.
1317 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1318 // name from the triple.
1319 if (hasMultipleArchs) {
1320 // First, remember the extension.
1321 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1322 // then, remove it.
1323 llvm::sys::path::replace_extension(F, "");
1324 // attach -<arch> to it.
1325 F += "-";
1326 F += Triple.getArchName();
1327 // put back the extension.
1328 llvm::sys::path::replace_extension(F, OldExtension);
1329 }
1330
1331 SmallString<32> Extension;
1332 Extension += "opt.";
1333 Extension += Format;
1334
1335 llvm::sys::path::replace_extension(F, Extension);
1336 CmdArgs.push_back(Args.MakeArgString(F));
1337 }
1338
1339 if (const Arg *A =
1340 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1341 CmdArgs.push_back("-opt-record-passes");
1342 CmdArgs.push_back(A->getValue());
1343 }
1344
1345 if (!Format.empty()) {
1346 CmdArgs.push_back("-opt-record-format");
1347 CmdArgs.push_back(Format.data());
1348 }
1349}
1350
1351void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1352 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1353 options::OPT_fno_aapcs_bitfield_width, true))
1354 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1355
1356 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1357 CmdArgs.push_back("-faapcs-bitfield-load");
1358}
1359
1360namespace {
1361void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1362 const ArgList &Args, ArgStringList &CmdArgs) {
1363 // Select the ABI to use.
1364 // FIXME: Support -meabi.
1365 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1366 const char *ABIName = nullptr;
1367 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1368 ABIName = A->getValue();
1369 else
1370 ABIName = llvm::ARM::computeDefaultTargetABI(Triple).data();
1371
1372 CmdArgs.push_back("-target-abi");
1373 CmdArgs.push_back(ABIName);
1374}
1375
1376void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1377 auto StrictAlignIter =
1378 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1379 return Arg == "+strict-align" || Arg == "-strict-align";
1380 });
1381 if (StrictAlignIter != CmdArgs.rend() &&
1382 StringRef(*StrictAlignIter) == "+strict-align")
1383 CmdArgs.push_back("-Wunaligned-access");
1384}
1385}
1386
1387static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1388 ArgStringList &CmdArgs, bool isAArch64) {
1389 const llvm::Triple &Triple = TC.getEffectiveTriple();
1390 const Arg *A = isAArch64
1391 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1392 options::OPT_mbranch_protection_EQ)
1393 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1394 if (!A) {
1395 if ((Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64) {
1396 CmdArgs.push_back("-msign-return-address=non-leaf");
1397 CmdArgs.push_back("-msign-return-address-key=a_key");
1398 CmdArgs.push_back("-mbranch-target-enforce");
1399 }
1400 return;
1401 }
1402
1403 const Driver &D = TC.getDriver();
1404 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1405 D.Diag(diag::warn_incompatible_branch_protection_option)
1406 << Triple.getArchName();
1407
1408 StringRef Scope, Key;
1409 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1410
1411 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1412 Scope = A->getValue();
1413 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1414 D.Diag(diag::err_drv_unsupported_option_argument)
1415 << A->getSpelling() << Scope;
1416 Key = "a_key";
1417 IndirectBranches =
1418 (Triple.isOSOpenBSD() || Triple.isAndroid()) && isAArch64;
1419 BranchProtectionPAuthLR = false;
1420 GuardedControlStack = false;
1421 } else {
1422 StringRef DiagMsg;
1423 llvm::ARM::ParsedBranchProtection PBP;
1424 bool EnablePAuthLR = false;
1425
1426 // To know if we need to enable PAuth-LR As part of the standard branch
1427 // protection option, it needs to be determined if the feature has been
1428 // activated in the `march` argument. This information is stored within the
1429 // CmdArgs variable and can be found using a search.
1430 if (isAArch64) {
1431 auto isPAuthLR = [](const char *member) {
1432 llvm::AArch64::ExtensionInfo pauthlr_extension =
1433 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1434 return llvm::AArch64::StrTab[pauthlr_extension.PosTargetFeature] ==
1435 member;
1436 };
1437
1438 if (llvm::any_of(CmdArgs, isPAuthLR))
1439 EnablePAuthLR = true;
1440 }
1441 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg, Triple,
1442 EnablePAuthLR))
1443 D.Diag(diag::err_drv_unsupported_option_argument)
1444 << A->getSpelling() << DiagMsg;
1445 if (!isAArch64 && PBP.Key == "b_key")
1446 D.Diag(diag::warn_unsupported_branch_protection)
1447 << "b-key" << A->getAsString(Args);
1448 Scope = PBP.Scope;
1449 Key = PBP.Key;
1450 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1451 IndirectBranches = PBP.BranchTargetEnforcement;
1452 GuardedControlStack = PBP.GuardedControlStack;
1453 }
1454
1455 Arg *PtrauthReturnsArg = Args.getLastArg(options::OPT_fptrauth_returns,
1456 options::OPT_fno_ptrauth_returns);
1457 bool HasPtrauthReturns =
1458 PtrauthReturnsArg &&
1459 PtrauthReturnsArg->getOption().matches(options::OPT_fptrauth_returns);
1460 // GCS is currently untested with ptrauth-returns, but enabling this could be
1461 // allowed in future after testing with a suitable system.
1462 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1463 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1464 D.Diag(diag::err_drv_unsupported_opt_for_target)
1465 << A->getAsString(Args) << Triple.getTriple();
1466 else if (HasPtrauthReturns)
1467 D.Diag(diag::err_drv_incompatible_options)
1468 << A->getAsString(Args) << "-fptrauth-returns";
1469 }
1470
1471 CmdArgs.push_back(
1472 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1473 if (Scope != "none")
1474 CmdArgs.push_back(
1475 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1476 if (BranchProtectionPAuthLR)
1477 CmdArgs.push_back(
1478 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1479 if (IndirectBranches)
1480 CmdArgs.push_back("-mbranch-target-enforce");
1481
1482 if (GuardedControlStack)
1483 CmdArgs.push_back("-mguarded-control-stack");
1484}
1485
1486void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1487 ArgStringList &CmdArgs, bool KernelOrKext) const {
1488 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1489
1490 // Determine floating point ABI from the options & target defaults.
1492 if (ABI == arm::FloatABI::Soft) {
1493 // Floating point operations and argument passing are soft.
1494 // FIXME: This changes CPP defines, we need -target-soft-float.
1495 CmdArgs.push_back("-msoft-float");
1496 CmdArgs.push_back("-mfloat-abi");
1497 CmdArgs.push_back("soft");
1498 } else if (ABI == arm::FloatABI::SoftFP) {
1499 // Floating point operations are hard, but argument passing is soft.
1500 CmdArgs.push_back("-mfloat-abi");
1501 CmdArgs.push_back("soft");
1502 } else {
1503 // Floating point operations and argument passing are hard.
1504 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1505 CmdArgs.push_back("-mfloat-abi");
1506 CmdArgs.push_back("hard");
1507 }
1508
1509 // Forward the -mglobal-merge option for explicit control over the pass.
1510 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1511 options::OPT_mno_global_merge)) {
1512 CmdArgs.push_back("-mllvm");
1513 if (A->getOption().matches(options::OPT_mno_global_merge))
1514 CmdArgs.push_back("-arm-global-merge=false");
1515 else
1516 CmdArgs.push_back("-arm-global-merge=true");
1517 }
1518
1519 if (!Args.hasFlag(options::OPT_mimplicit_float,
1520 options::OPT_mno_implicit_float, true))
1521 CmdArgs.push_back("-no-implicit-float");
1522
1523 if (Args.getLastArg(options::OPT_mcmse))
1524 CmdArgs.push_back("-mcmse");
1525
1526 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1527
1528 // Enable/disable return address signing and indirect branch targets.
1529 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1530
1531 AddUnalignedAccessWarning(CmdArgs);
1532}
1533
1534void Clang::AddAMDGPUTargetArgs(const ArgList &Args,
1535 ArgStringList &CmdArgs) const {
1536 // Pass through -mxnack/-mno-xnack and -msramecc/-mno-sramecc flags to cc1.
1537 if (Arg *A = Args.getLastArg(options::OPT_mxnack, options::OPT_mno_xnack))
1538 A->render(Args, CmdArgs);
1539 if (Arg *A = Args.getLastArg(options::OPT_msramecc, options::OPT_mno_sramecc))
1540 A->render(Args, CmdArgs);
1541}
1542
1543void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1544 const ArgList &Args, bool KernelOrKext,
1545 ArgStringList &CmdArgs) const {
1546 const ToolChain &TC = getToolChain();
1547
1548 // Add the target features
1549 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1550
1551 // Add target specific flags.
1552 switch (TC.getArch()) {
1553 default:
1554 break;
1555
1556 case llvm::Triple::arm:
1557 case llvm::Triple::armeb:
1558 case llvm::Triple::thumb:
1559 case llvm::Triple::thumbeb:
1560 // Use the effective triple, which takes into account the deployment target.
1561 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1562 break;
1563
1564 case llvm::Triple::aarch64:
1565 case llvm::Triple::aarch64_32:
1566 case llvm::Triple::aarch64_be:
1567 AddAArch64TargetArgs(Args, CmdArgs);
1568 break;
1569
1570 case llvm::Triple::amdgpu:
1571 AddAMDGPUTargetArgs(Args, CmdArgs);
1572 break;
1573
1574 case llvm::Triple::loongarch32:
1575 case llvm::Triple::loongarch64:
1576 AddLoongArchTargetArgs(Args, CmdArgs);
1577 break;
1578
1579 case llvm::Triple::mips:
1580 case llvm::Triple::mipsel:
1581 case llvm::Triple::mips64:
1582 case llvm::Triple::mips64el:
1583 AddMIPSTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::ppc:
1587 case llvm::Triple::ppcle:
1588 case llvm::Triple::ppc64:
1589 case llvm::Triple::ppc64le:
1590 AddPPCTargetArgs(Args, CmdArgs);
1591 break;
1592
1593 case llvm::Triple::riscv32:
1594 case llvm::Triple::riscv64:
1595 case llvm::Triple::riscv32be:
1596 case llvm::Triple::riscv64be:
1597 AddRISCVTargetArgs(Args, CmdArgs);
1598 break;
1599
1600 case llvm::Triple::sparc:
1601 case llvm::Triple::sparcel:
1602 case llvm::Triple::sparcv9:
1603 AddSparcTargetArgs(Args, CmdArgs);
1604 break;
1605
1606 case llvm::Triple::systemz:
1607 AddSystemZTargetArgs(Args, CmdArgs);
1608 break;
1609
1610 case llvm::Triple::x86:
1611 case llvm::Triple::x86_64:
1612 AddX86TargetArgs(Args, CmdArgs);
1613 break;
1614
1615 case llvm::Triple::lanai:
1616 AddLanaiTargetArgs(Args, CmdArgs);
1617 break;
1618
1619 case llvm::Triple::hexagon:
1620 AddHexagonTargetArgs(Args, CmdArgs);
1621 break;
1622
1623 case llvm::Triple::wasm32:
1624 case llvm::Triple::wasm64:
1625 AddWebAssemblyTargetArgs(Args, CmdArgs);
1626 break;
1627
1628 case llvm::Triple::ve:
1629 AddVETargetArgs(Args, CmdArgs);
1630 break;
1631 }
1632}
1633
1634namespace {
1635void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1636 ArgStringList &CmdArgs) {
1637 const char *ABIName = nullptr;
1638 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1639 ABIName = A->getValue();
1640 else if (Triple.isOSDarwin())
1641 ABIName = "darwinpcs";
1642 // TODO: we probably want to have some target hook here.
1643 else if (Triple.isOSLinux() &&
1644 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1645 ABIName = "pauthtest";
1646 else
1647 ABIName = "aapcs";
1648
1649 CmdArgs.push_back("-target-abi");
1650 CmdArgs.push_back(ABIName);
1651}
1652}
1653
1654void Clang::AddAArch64TargetArgs(const ArgList &Args,
1655 ArgStringList &CmdArgs) const {
1656 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1657
1658 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1659 Args.hasArg(options::OPT_mkernel) ||
1660 Args.hasArg(options::OPT_fapple_kext))
1661 CmdArgs.push_back("-disable-red-zone");
1662
1663 if (!Args.hasFlag(options::OPT_mimplicit_float,
1664 options::OPT_mno_implicit_float, true))
1665 CmdArgs.push_back("-no-implicit-float");
1666
1667 RenderAArch64ABI(Triple, Args, CmdArgs);
1668
1669 // Forward the -mglobal-merge option for explicit control over the pass.
1670 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1671 options::OPT_mno_global_merge)) {
1672 CmdArgs.push_back("-mllvm");
1673 if (A->getOption().matches(options::OPT_mno_global_merge))
1674 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1675 else
1676 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1677 }
1678
1679 // Handle -msve_vector_bits=<bits>
1680 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1681 StringRef VScaleMax) {
1682 StringRef Val = A->getValue();
1683 const Driver &D = getToolChain().getDriver();
1684 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1685 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1686 Val == "1024+" || Val == "2048+") {
1687 unsigned Bits = 0;
1688 if (!Val.consume_back("+")) {
1689 bool Invalid = Val.getAsInteger(10, Bits);
1690 (void)Invalid;
1691 assert(!Invalid && "Failed to parse value");
1692 CmdArgs.push_back(
1693 Args.MakeArgString(VScaleMax + llvm::Twine(Bits / 128)));
1694 }
1695
1696 bool Invalid = Val.getAsInteger(10, Bits);
1697 (void)Invalid;
1698 assert(!Invalid && "Failed to parse value");
1699
1700 CmdArgs.push_back(
1701 Args.MakeArgString(VScaleMin + llvm::Twine(Bits / 128)));
1702 } else if (Val == "scalable") {
1703 // Silently drop requests for vector-length agnostic code as it's implied.
1704 } else {
1705 // Handle the unsupported values passed to msve-vector-bits.
1706 D.Diag(diag::err_drv_unsupported_option_argument)
1707 << A->getSpelling() << Val;
1708 }
1709 };
1710 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ))
1711 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1712 if (Arg *A = Args.getLastArg(options::OPT_msve_streaming_vector_bits_EQ))
1713 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1714
1715 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1716
1717 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1718 CmdArgs.push_back("-tune-cpu");
1719 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
1720 }
1721
1722 AddUnalignedAccessWarning(CmdArgs);
1723
1724 if (Triple.isOSDarwin() ||
1725 (Triple.isOSLinux() &&
1726 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1727 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1728 options::OPT_fno_ptrauth_intrinsics);
1729 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1730 options::OPT_fno_ptrauth_calls);
1731 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1732 options::OPT_fno_ptrauth_returns);
1733 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1734 options::OPT_fno_ptrauth_auth_traps);
1735 Args.addOptInFlag(
1736 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1737 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1738 Args.addOptInFlag(
1739 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1740 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1741 Args.addOptInFlag(
1742 CmdArgs, options::OPT_fptrauth_vtt_vtable_pointer_discrimination,
1743 options::OPT_fno_ptrauth_vtt_vtable_pointer_discrimination);
1744 Args.addOptInFlag(
1745 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1746 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1747 Args.addOptInFlag(
1748 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1749 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1750 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1751 options::OPT_fno_ptrauth_indirect_gotos);
1752 }
1753 if (Triple.isOSLinux() &&
1754 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1755 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1756 options::OPT_fno_ptrauth_init_fini);
1757 Args.addOptInFlag(
1758 CmdArgs, options::OPT_fptrauth_init_fini_address_discrimination,
1759 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1760 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_elf_got,
1761 options::OPT_fno_ptrauth_elf_got);
1762 }
1763 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1764 options::OPT_fno_aarch64_jump_table_hardening);
1765
1766 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_isa,
1767 options::OPT_fno_ptrauth_objc_isa);
1768 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_interface_sel,
1769 options::OPT_fno_ptrauth_objc_interface_sel);
1770 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
1771 options::OPT_fno_ptrauth_objc_class_ro);
1772
1773 // Enable/disable return address signing and indirect branch targets.
1774 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1775}
1776
1777void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1778 ArgStringList &CmdArgs) const {
1779 const llvm::Triple &Triple = getToolChain().getTriple();
1780
1781 CmdArgs.push_back("-target-abi");
1782 CmdArgs.push_back(
1783 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1784 .data());
1785
1786 // Handle -mtune.
1787 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1788 std::string TuneCPU = A->getValue();
1789 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1790 CmdArgs.push_back("-tune-cpu");
1791 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1792 }
1793
1794 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1795 options::OPT_mno_annotate_tablejump)) {
1796 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1797 CmdArgs.push_back("-mllvm");
1798 CmdArgs.push_back("-loongarch-annotate-tablejump");
1799 }
1800 }
1801}
1802
1803void Clang::AddMIPSTargetArgs(const ArgList &Args,
1804 ArgStringList &CmdArgs) const {
1805 const Driver &D = getToolChain().getDriver();
1806 StringRef CPUName;
1807 StringRef ABIName;
1808 const llvm::Triple &Triple = getToolChain().getTriple();
1809 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1810
1811 CmdArgs.push_back("-target-abi");
1812 CmdArgs.push_back(ABIName.data());
1813
1814 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1815 if (ABI == mips::FloatABI::Soft) {
1816 // Floating point operations and argument passing are soft.
1817 CmdArgs.push_back("-msoft-float");
1818 CmdArgs.push_back("-mfloat-abi");
1819 CmdArgs.push_back("soft");
1820 } else {
1821 // Floating point operations and argument passing are hard.
1822 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1823 CmdArgs.push_back("-mfloat-abi");
1824 CmdArgs.push_back("hard");
1825 }
1826
1827 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1828 options::OPT_mno_ldc1_sdc1)) {
1829 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1830 CmdArgs.push_back("-mllvm");
1831 CmdArgs.push_back("-mno-ldc1-sdc1");
1832 }
1833 }
1834
1835 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1836 options::OPT_mno_check_zero_division)) {
1837 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1838 CmdArgs.push_back("-mllvm");
1839 CmdArgs.push_back("-mno-check-zero-division");
1840 }
1841 }
1842
1843 if (Args.getLastArg(options::OPT_mfix4300)) {
1844 CmdArgs.push_back("-mllvm");
1845 CmdArgs.push_back("-mfix4300");
1846 }
1847
1848 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1849 StringRef v = A->getValue();
1850 CmdArgs.push_back("-mllvm");
1851 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1852 A->claim();
1853 }
1854
1855 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1856 Arg *ABICalls =
1857 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1858
1859 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1860 // -mgpopt is the default for static, -fno-pic environments but these two
1861 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1862 // the only case where -mllvm -mgpopt is passed.
1863 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1864 // passed explicitly when compiling something with -mabicalls
1865 // (implictly) in affect. Currently the warning is in the backend.
1866 //
1867 // When the ABI in use is N64, we also need to determine the PIC mode that
1868 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1869 bool NoABICalls =
1870 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1871
1872 llvm::Reloc::Model RelocationModel;
1873 unsigned PICLevel;
1874 bool IsPIE;
1875 std::tie(RelocationModel, PICLevel, IsPIE) =
1876 ParsePICArgs(getToolChain(), Args);
1877
1878 NoABICalls = NoABICalls ||
1879 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1880
1881 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1882 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1883 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1884 CmdArgs.push_back("-mllvm");
1885 CmdArgs.push_back("-mgpopt");
1886
1887 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1888 options::OPT_mno_local_sdata);
1889 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1890 options::OPT_mno_extern_sdata);
1891 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1892 options::OPT_mno_embedded_data);
1893 if (LocalSData) {
1894 CmdArgs.push_back("-mllvm");
1895 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1896 CmdArgs.push_back("-mlocal-sdata=1");
1897 } else {
1898 CmdArgs.push_back("-mlocal-sdata=0");
1899 }
1900 LocalSData->claim();
1901 }
1902
1903 if (ExternSData) {
1904 CmdArgs.push_back("-mllvm");
1905 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1906 CmdArgs.push_back("-mextern-sdata=1");
1907 } else {
1908 CmdArgs.push_back("-mextern-sdata=0");
1909 }
1910 ExternSData->claim();
1911 }
1912
1913 if (EmbeddedData) {
1914 CmdArgs.push_back("-mllvm");
1915 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1916 CmdArgs.push_back("-membedded-data=1");
1917 } else {
1918 CmdArgs.push_back("-membedded-data=0");
1919 }
1920 EmbeddedData->claim();
1921 }
1922
1923 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1924 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1925
1926 if (GPOpt)
1927 GPOpt->claim();
1928
1929 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1930 StringRef Val = StringRef(A->getValue());
1931 if (mips::hasCompactBranches(CPUName)) {
1932 if (Val == "never" || Val == "always" || Val == "optimal") {
1933 CmdArgs.push_back("-mllvm");
1934 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1935 } else
1936 D.Diag(diag::err_drv_unsupported_option_argument)
1937 << A->getSpelling() << Val;
1938 } else
1939 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1940 }
1941
1942 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1943 options::OPT_mno_relax_pic_calls)) {
1944 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1945 CmdArgs.push_back("-mllvm");
1946 CmdArgs.push_back("-mips-jalr-reloc=0");
1947 }
1948 }
1949}
1950
1951void Clang::AddPPCTargetArgs(const ArgList &Args,
1952 ArgStringList &CmdArgs) const {
1953 const Driver &D = getToolChain().getDriver();
1954 const llvm::Triple &T = getToolChain().getTriple();
1955 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1956 CmdArgs.push_back("-tune-cpu");
1957 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
1958 CmdArgs.push_back(Args.MakeArgString(CPU));
1959 }
1960
1961 // Select the ABI to use.
1962 const char *ABIName = nullptr;
1963 if (T.isOSBinFormatELF()) {
1964 switch (getToolChain().getArch()) {
1965 case llvm::Triple::ppc64: {
1966 if (T.isPPC64ELFv2ABI())
1967 ABIName = "elfv2";
1968 else
1969 ABIName = "elfv1";
1970 break;
1971 }
1972 case llvm::Triple::ppc64le:
1973 ABIName = "elfv2";
1974 break;
1975 default:
1976 break;
1977 }
1978 }
1979
1980 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1981 bool VecExtabi = false;
1982 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1983 StringRef V = A->getValue();
1984 if (V == "ieeelongdouble") {
1985 IEEELongDouble = true;
1986 A->claim();
1987 } else if (V == "ibmlongdouble") {
1988 IEEELongDouble = false;
1989 A->claim();
1990 } else if (V == "vec-default") {
1991 VecExtabi = false;
1992 A->claim();
1993 } else if (V == "vec-extabi") {
1994 VecExtabi = true;
1995 A->claim();
1996 } else if (V == "elfv1") {
1997 ABIName = "elfv1";
1998 A->claim();
1999 } else if (V == "elfv2") {
2000 ABIName = "elfv2";
2001 A->claim();
2002 } else if (V != "altivec")
2003 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2004 // the option if given as we don't have backend support for any targets
2005 // that don't use the altivec abi.
2006 ABIName = A->getValue();
2007 }
2008 if (IEEELongDouble)
2009 CmdArgs.push_back("-mabi=ieeelongdouble");
2010 if (VecExtabi) {
2011 if (!T.isOSAIX())
2012 D.Diag(diag::err_drv_unsupported_opt_for_target)
2013 << "-mabi=vec-extabi" << T.str();
2014 CmdArgs.push_back("-mabi=vec-extabi");
2015 }
2016
2017 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2018 CmdArgs.push_back("-disable-red-zone");
2019
2021 if (FloatABI == ppc::FloatABI::Soft) {
2022 // Floating point operations and argument passing are soft.
2023 CmdArgs.push_back("-msoft-float");
2024 CmdArgs.push_back("-mfloat-abi");
2025 CmdArgs.push_back("soft");
2026 } else {
2027 // Floating point operations and argument passing are hard.
2028 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2029 CmdArgs.push_back("-mfloat-abi");
2030 CmdArgs.push_back("hard");
2031 }
2032
2033 if (ABIName) {
2034 CmdArgs.push_back("-target-abi");
2035 CmdArgs.push_back(ABIName);
2036 }
2037}
2038
2039void Clang::AddRISCVTargetArgs(const ArgList &Args,
2040 ArgStringList &CmdArgs) const {
2041 const llvm::Triple &Triple = getToolChain().getTriple();
2042 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2043
2044 CmdArgs.push_back("-target-abi");
2045 CmdArgs.push_back(ABIName.data());
2046
2047 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2048 CmdArgs.push_back("-msmall-data-limit");
2049 CmdArgs.push_back(A->getValue());
2050 }
2051
2052 if (!Args.hasFlag(options::OPT_mimplicit_float,
2053 options::OPT_mno_implicit_float, true))
2054 CmdArgs.push_back("-no-implicit-float");
2055
2056 auto TuneCPU = riscv::getRISCVTuneCPU(getToolChain().getDriver(), Args);
2057 if (!TuneCPU)
2058 return;
2059 if (!TuneCPU->empty()) {
2060 CmdArgs.push_back("-tune-cpu");
2061 // TuneCPU might or might not be the original -mtune string, so we
2062 // have to create a new copy here.
2063 CmdArgs.push_back(Args.MakeArgString(*TuneCPU));
2064 }
2065
2066 // Handle -mrvv-vector-bits=<bits>
2067 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2068 StringRef Val = A->getValue();
2069 const Driver &D = getToolChain().getDriver();
2070
2071 // Get minimum VLen from march.
2072 unsigned MinVLen = 0;
2073 std::string Arch = riscv::getRISCVArch(Args, Triple);
2074 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2075 Arch, /*EnableExperimentalExtensions*/ true);
2076 // Ignore parsing error.
2077 if (!errorToBool(ISAInfo.takeError()))
2078 MinVLen = (*ISAInfo)->getMinVLen();
2079
2080 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2081 // as integer as long as we have a MinVLen.
2082 unsigned Bits = 0;
2083 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2084 Bits = MinVLen;
2085 } else if (!Val.getAsInteger(10, Bits)) {
2086 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2087 // at least MinVLen.
2088 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2089 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2090 Bits = 0;
2091 }
2092
2093 // If we got a valid value try to use it.
2094 if (Bits != 0) {
2095 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2096 CmdArgs.push_back(
2097 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2098 CmdArgs.push_back(
2099 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2100 } else if (Val != "scalable") {
2101 // Handle the unsupported values passed to mrvv-vector-bits.
2102 D.Diag(diag::err_drv_unsupported_option_argument)
2103 << A->getSpelling() << Val;
2104 }
2105 }
2106}
2107
2108void Clang::AddSparcTargetArgs(const ArgList &Args,
2109 ArgStringList &CmdArgs) const {
2111 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2112
2113 if (FloatABI == sparc::FloatABI::Soft) {
2114 // Floating point operations and argument passing are soft.
2115 CmdArgs.push_back("-msoft-float");
2116 CmdArgs.push_back("-mfloat-abi");
2117 CmdArgs.push_back("soft");
2118 } else {
2119 // Floating point operations and argument passing are hard.
2120 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2121 CmdArgs.push_back("-mfloat-abi");
2122 CmdArgs.push_back("hard");
2123 }
2124
2125 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2126 StringRef Name = A->getValue();
2127 std::string TuneCPU;
2128 if (Name == "native")
2129 TuneCPU = std::string(llvm::sys::getHostCPUName());
2130 else
2131 TuneCPU = std::string(Name);
2132
2133 CmdArgs.push_back("-tune-cpu");
2134 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2135 }
2136}
2137
2138void Clang::AddSystemZTargetArgs(const ArgList &Args,
2139 ArgStringList &CmdArgs) const {
2140 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2141 CmdArgs.push_back("-tune-cpu");
2142 if (strcmp(A->getValue(), "native") == 0)
2143 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2144 else
2145 CmdArgs.push_back(A->getValue());
2146 }
2147
2148 bool HasBackchain =
2149 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2150 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2151 options::OPT_mno_packed_stack, false);
2153 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2154 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2155
2156 // Only hard float ABI (-mhard-float) is supported on z/OS.
2157 const Driver &D = getToolChain().getDriver();
2158 const llvm::Triple &Triple = getToolChain().getTriple();
2159 if (HasSoftFloat && Triple.isOSzOS()) {
2160 D.Diag(diag::err_drv_unsupported_opt_for_target)
2161 << "-msoft-float" << Triple.str();
2162 }
2163 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2164 D.Diag(diag::err_drv_unsupported_opt)
2165 << "-mpacked-stack -mbackchain -mhard-float";
2166 }
2167 if (HasBackchain)
2168 CmdArgs.push_back("-mbackchain");
2169 if (HasPackedStack)
2170 CmdArgs.push_back("-mpacked-stack");
2171 if (HasSoftFloat) {
2172 // Floating point operations and argument passing are soft.
2173 CmdArgs.push_back("-msoft-float");
2174 CmdArgs.push_back("-mfloat-abi");
2175 CmdArgs.push_back("soft");
2176 }
2177
2178 if (Triple.isOSzOS())
2179 Args.AddLastArg(CmdArgs, options::OPT_mzos_ppa1_name,
2180 options::OPT_mno_zos_ppa1_name);
2181}
2182
2183void Clang::AddX86TargetArgs(const ArgList &Args,
2184 ArgStringList &CmdArgs) const {
2185 const Driver &D = getToolChain().getDriver();
2186 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2187
2188 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2189 Args.hasArg(options::OPT_mkernel) ||
2190 Args.hasArg(options::OPT_fapple_kext))
2191 CmdArgs.push_back("-disable-red-zone");
2192
2193 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2194 options::OPT_mno_tls_direct_seg_refs, true))
2195 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2196
2197 // Default to avoid implicit floating-point for kernel/kext code, but allow
2198 // that to be overridden with -mno-soft-float.
2199 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2200 Args.hasArg(options::OPT_fapple_kext));
2201 if (Arg *A = Args.getLastArg(
2202 options::OPT_msoft_float, options::OPT_mno_soft_float,
2203 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2204 const Option &O = A->getOption();
2205 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2206 O.matches(options::OPT_msoft_float));
2207 }
2208 if (NoImplicitFloat)
2209 CmdArgs.push_back("-no-implicit-float");
2210
2211 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2212 StringRef Value = A->getValue();
2213 if (Value == "intel" || Value == "att") {
2214 CmdArgs.push_back("-mllvm");
2215 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2216 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2217 } else {
2218 D.Diag(diag::err_drv_unsupported_option_argument)
2219 << A->getSpelling() << Value;
2220 }
2221 } else if (D.IsCLMode()) {
2222 CmdArgs.push_back("-mllvm");
2223 CmdArgs.push_back("-x86-asm-syntax=intel");
2224 }
2225
2226 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2227 options::OPT_mno_skip_rax_setup))
2228 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2229 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2230
2231 // Set flags to support MCU ABI.
2232 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2233 CmdArgs.push_back("-mfloat-abi");
2234 CmdArgs.push_back("soft");
2235 CmdArgs.push_back("-mstack-alignment=4");
2236 }
2237
2238 // Handle -mtune.
2239
2240 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2241 std::string TuneCPU;
2242 if (!Args.hasArg(options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2243 TuneCPU = "generic";
2244
2245 // Override based on -mtune.
2246 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2247 StringRef Name = A->getValue();
2248
2249 if (Name == "native") {
2250 Name = llvm::sys::getHostCPUName();
2251 if (!Name.empty())
2252 TuneCPU = std::string(Name);
2253 } else
2254 TuneCPU = std::string(Name);
2255 }
2256
2257 if (!TuneCPU.empty()) {
2258 CmdArgs.push_back("-tune-cpu");
2259 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2260 }
2261}
2262
2263static StringRef getOptionName(StringRef Option, const char Delimiter = '=') {
2264 size_t Index = Option.find(Delimiter);
2265 if (Index != StringRef::npos)
2266 Option = Option.substr(0, Index);
2267 return Option;
2268}
2269
2270static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt) {
2271 Opt = getOptionName(Opt);
2272 if (CmdArgs.size() < 2)
2273 return;
2274
2275 for (auto It = std::next(CmdArgs.begin()); It != CmdArgs.end(); ++It) {
2276 StringRef Option = *It;
2277 if (!Option.starts_with(Opt))
2278 continue;
2279 Option = getOptionName(Option);
2280 if (Option != Opt)
2281 continue;
2282 if (StringRef(*(It - 1)) != "-mllvm")
2283 continue;
2284
2285 It = CmdArgs.erase(It);
2286 CmdArgs.erase(It - 1);
2287 return;
2288 }
2289}
2290
2291static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A) {
2292 checkAndRemoveLLVMArg(CmdArgs, A);
2293 CmdArgs.push_back("-mllvm");
2294 CmdArgs.push_back(A);
2295}
2296
2297static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs) {
2298 for (auto It = CmdArgs.begin(), Ie = CmdArgs.end(); It != Ie;) {
2299 StringRef Option = *It;
2300 if (Option == "-fmath-errno" || Option == "-ffp-contract=on") {
2301 It = CmdArgs.erase(It);
2302 Ie = CmdArgs.end();
2303 } else {
2304 ++It;
2305 }
2306 }
2307
2308 CmdArgs.push_back("-menable-no-infs");
2309 CmdArgs.push_back("-menable-no-nans");
2310 CmdArgs.push_back("-fapprox-func");
2311 CmdArgs.push_back("-funsafe-math-optimizations");
2312 CmdArgs.push_back("-fno-signed-zeros");
2313 CmdArgs.push_back("-mreassociate");
2314 CmdArgs.push_back("-freciprocal-math");
2315 CmdArgs.push_back("-ffp-contract=fast");
2316 CmdArgs.push_back("-ffast-math");
2317 CmdArgs.push_back("-ffinite-math-only");
2318 CmdArgs.push_back("-D__FAST_MATH__");
2319 pushBackLLVMArg(CmdArgs, "-fast-math=true");
2320}
2321
2322static void addQFloatBackendArg(const Driver &D, const ArgList &Args,
2323 ArgStringList &CmdArgs) {
2324 auto HvxVerOpt = toolchains::HexagonToolChain::GetHVXVersion(Args);
2325 bool HasHVX = HvxVerOpt.has_value();
2326 std::string HvxVer = HasHVX ? *HvxVerOpt : std::string();
2327 if (!Args.hasArg(options::OPT_mhexagon_hvx, options::OPT_mhexagon_hvx_EQ,
2328 options::OPT_mhexagon_hvx_ieee_fp) ||
2329 !HasHVX)
2330 return;
2331 unsigned HvxVerNum = 0;
2332 if (StringRef(HvxVer).drop_front(1).getAsInteger(10, HvxVerNum))
2333 HvxVerNum = 0;
2334
2335 if (Arg *A = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2336 options::OPT_mhexagon_hvx_qfloat_EQ,
2337 options::OPT_mhexagon_hvx_ieee_fp)) {
2338 if (HvxVerNum >= 79) {
2339 if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2340 const char *Mode =
2341 llvm::StringSwitch<const char *>(StringRef(A->getValue()).lower())
2342 .Case("strict-ieee", "-hexagon-qfloat-mode=strict-ieee")
2343 .Case("ieee", "-hexagon-qfloat-mode=ieee")
2344 .Case("lossy", "-hexagon-qfloat-mode=lossy")
2345 .Case("legacy", "-hexagon-qfloat-mode=legacy")
2346 .Default(nullptr);
2347 if (!Mode) {
2348 D.Diag(diag::err_drv_invalid_value)
2349 << A->getAsString(Args) << A->getValue();
2350 return;
2351 }
2352 pushBackLLVMArg(CmdArgs, Mode);
2353 if (strcmp(Mode, "-hexagon-qfloat-mode=lossy") == 0)
2355 } else if (A->getOption().matches(options::OPT_mhexagon_hvx_qfloat)) {
2356 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=lossy");
2358 } else {
2359 pushBackLLVMArg(CmdArgs, "-hexagon-qfloat-mode=ieee");
2360 }
2361 } else {
2362 if (Arg *QFloatArg = Args.getLastArg(options::OPT_mhexagon_hvx_qfloat,
2363 options::OPT_mhexagon_hvx_qfloat_EQ,
2364 options::OPT_mno_hexagon_hvx_qfloat);
2365 QFloatArg &&
2366 QFloatArg->getOption().matches(options::OPT_mhexagon_hvx_qfloat_EQ)) {
2367 D.Diag(diag::warn_drv_unsupported_option_part_for_target)
2368 << QFloatArg->getValue() << QFloatArg->getAsString(Args)
2369 << (std::string("HVX ") + HvxVer +
2370 "; falling back to legacy qfloat mode");
2371 }
2372 }
2373 }
2374}
2375
2376void Clang::AddHexagonTargetArgs(const ArgList &Args,
2377 ArgStringList &CmdArgs) const {
2378 CmdArgs.push_back("-mqdsp6-compat");
2379 CmdArgs.push_back("-Wreturn-type");
2380
2382 CmdArgs.push_back("-mllvm");
2383 CmdArgs.push_back(
2384 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2385 }
2386
2387 if (!Args.hasArg(options::OPT_fno_short_enums))
2388 CmdArgs.push_back("-fshort-enums");
2389 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2390 CmdArgs.push_back("-mllvm");
2391 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2392 }
2393 CmdArgs.push_back("-mllvm");
2394 CmdArgs.push_back("-machine-sink-split=0");
2395
2396 addQFloatBackendArg(getToolChain().getDriver(), Args, CmdArgs);
2397}
2398
2399void Clang::AddLanaiTargetArgs(const ArgList &Args,
2400 ArgStringList &CmdArgs) const {
2401 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2402 StringRef CPUName = A->getValue();
2403
2404 CmdArgs.push_back("-target-cpu");
2405 CmdArgs.push_back(Args.MakeArgString(CPUName));
2406 }
2407 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2408 StringRef Value = A->getValue();
2409 // Only support mregparm=4 to support old usage. Report error for all other
2410 // cases.
2411 int Mregparm;
2412 if (Value.getAsInteger(10, Mregparm)) {
2413 if (Mregparm != 4) {
2415 diag::err_drv_unsupported_option_argument)
2416 << A->getSpelling() << Value;
2417 }
2418 }
2419 }
2420}
2421
2422void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2423 ArgStringList &CmdArgs) const {
2424 // Default to "hidden" visibility.
2425 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2426 options::OPT_fvisibility_ms_compat))
2427 CmdArgs.push_back("-fvisibility=hidden");
2428}
2429
2430void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2431 // Floating point operations and argument passing are hard.
2432 CmdArgs.push_back("-mfloat-abi");
2433 CmdArgs.push_back("hard");
2434}
2435
2436void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2437 StringRef Target, const InputInfo &Output,
2438 const InputInfo &Input, const ArgList &Args) const {
2439 // If this is a dry run, do not create the compilation database file.
2440 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2441 return;
2442
2443 using llvm::yaml::escape;
2444 const Driver &D = getToolChain().getDriver();
2445
2446 if (!CompilationDatabase) {
2447 std::error_code EC;
2448 auto File = std::make_unique<llvm::raw_fd_ostream>(
2449 Filename, EC,
2450 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2451 if (EC) {
2452 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2453 << EC.message();
2454 return;
2455 }
2456 CompilationDatabase = std::move(File);
2457 }
2458 auto &CDB = *CompilationDatabase;
2459 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2460 if (!CWD)
2461 CWD = ".";
2462 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2463 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2464 if (Output.isFilename())
2465 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2466 CDB << ", \"arguments\": [\"" << escape(D.DriverExecutable) << "\"";
2467 SmallString<128> Buf;
2468 Buf = "-x";
2469 Buf += types::getTypeName(Input.getType());
2470 CDB << ", \"" << escape(Buf) << "\"";
2471 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2472 Buf = "--sysroot=";
2473 Buf += D.SysRoot;
2474 CDB << ", \"" << escape(Buf) << "\"";
2475 }
2476 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2477 if (Output.isFilename())
2478 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2479 for (auto &A: Args) {
2480 auto &O = A->getOption();
2481 // Skip language selection, which is positional.
2482 if (O.getID() == options::OPT_x)
2483 continue;
2484 // Skip writing dependency output and the compilation database itself.
2485 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2486 continue;
2487 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2488 continue;
2489 // Skip inputs.
2490 if (O.getKind() == Option::InputClass)
2491 continue;
2492 // Skip output.
2493 if (O.getID() == options::OPT_o)
2494 continue;
2495 // All other arguments are quoted and appended.
2496 ArgStringList ASL;
2497 A->render(Args, ASL);
2498 for (auto &it: ASL)
2499 CDB << ", \"" << escape(it) << "\"";
2500 }
2501 Buf = "--target=";
2502 Buf += Target;
2503 CDB << ", \"" << escape(Buf) << "\"]},\n";
2504}
2505
2506void Clang::DumpCompilationDatabaseFragmentToDir(
2507 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2508 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2509 // If this is a dry run, do not create the compilation database file.
2510 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2511 return;
2512
2513 if (CompilationDatabase)
2514 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2515
2516 SmallString<256> Path = Dir;
2517 const auto &Driver = C.getDriver();
2518 Driver.getVFS().makeAbsolute(Path);
2519 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2520 if (Err) {
2521 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2522 return;
2523 }
2524
2525 llvm::sys::path::append(
2526 Path,
2527 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2528 int FD;
2529 SmallString<256> TempPath;
2530 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2531 llvm::sys::fs::OF_Text);
2532 if (Err) {
2533 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2534 return;
2535 }
2536 CompilationDatabase =
2537 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2538 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2539}
2540
2541static bool CheckARMImplicitITArg(StringRef Value) {
2542 return Value == "always" || Value == "never" || Value == "arm" ||
2543 Value == "thumb";
2544}
2545
2546static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2547 StringRef Value) {
2548 CmdArgs.push_back("-mllvm");
2549 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2550}
2551
2553 const ArgList &Args,
2554 ArgStringList &CmdArgs,
2555 const Driver &D) {
2556 // Default to -mno-relax-all.
2557 //
2558 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2559 // cannot be done by assembler branch relaxation as it needs a free temporary
2560 // register. Because of this, branch relaxation is handled by a MachineIR pass
2561 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2562 // MachineIR branch relaxation inaccurate and it will miss cases where an
2563 // indirect branch is necessary.
2564 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2565 options::OPT_mno_relax_all);
2566
2567 Args.AddLastArg(CmdArgs, options::OPT_mincremental_linker_compatible,
2568 options::OPT_mno_incremental_linker_compatible);
2569
2570 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2571
2572 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2573 options::OPT_fno_emit_compact_unwind_non_canonical);
2574
2575 // If you add more args here, also add them to the block below that
2576 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2577
2578 // When passing -I arguments to the assembler we sometimes need to
2579 // unconditionally take the next argument. For example, when parsing
2580 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2581 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2582 // arg after parsing the '-I' arg.
2583 bool TakeNextArg = false;
2584
2585 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2586 bool IsELF = Triple.isOSBinFormatELF();
2587 bool Crel = false, ExperimentalCrel = false;
2588 StringRef RelocSectionSym;
2589 bool SFrame = false, ExperimentalSFrame = false;
2590 bool ImplicitMapSyms = false;
2591 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2592 bool UseNoExecStack = false;
2593 bool Msa = false;
2594 const char *MipsTargetFeature = nullptr;
2595 llvm::SmallVector<const char *> SparcTargetFeatures;
2596 StringRef ImplicitIt;
2597 for (const Arg *A :
2598 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2599 options::OPT_mimplicit_it_EQ)) {
2600 A->claim();
2601
2602 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2603 switch (C.getDefaultToolChain().getArch()) {
2604 case llvm::Triple::arm:
2605 case llvm::Triple::armeb:
2606 case llvm::Triple::thumb:
2607 case llvm::Triple::thumbeb:
2608 // Only store the value; the last value set takes effect.
2609 ImplicitIt = A->getValue();
2610 if (!CheckARMImplicitITArg(ImplicitIt))
2611 D.Diag(diag::err_drv_unsupported_option_argument)
2612 << A->getSpelling() << ImplicitIt;
2613 continue;
2614 default:
2615 break;
2616 }
2617 }
2618
2619 for (StringRef Value : A->getValues()) {
2620 if (TakeNextArg) {
2621 CmdArgs.push_back(Value.data());
2622 TakeNextArg = false;
2623 continue;
2624 }
2625
2626 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2627 Value == "-mbig-obj")
2628 continue; // LLVM handles bigobj automatically
2629
2630 auto Equal = Value.split('=');
2631 auto checkArg = [&](bool ValidTarget,
2632 std::initializer_list<const char *> Set) {
2633 if (!ValidTarget) {
2634 D.Diag(diag::err_drv_unsupported_opt_for_target)
2635 << (Twine("-Wa,") + Equal.first + "=").str()
2636 << Triple.getTriple();
2637 } else if (!llvm::is_contained(Set, Equal.second)) {
2638 D.Diag(diag::err_drv_unsupported_option_argument)
2639 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2640 }
2641 };
2642 switch (C.getDefaultToolChain().getArch()) {
2643 default:
2644 break;
2645 case llvm::Triple::x86:
2646 case llvm::Triple::x86_64:
2647 if (Equal.first == "-mrelax-relocations" ||
2648 Equal.first == "--mrelax-relocations") {
2649 UseRelaxRelocations = Equal.second == "yes";
2650 checkArg(IsELF, {"yes", "no"});
2651 continue;
2652 }
2653 if (Value == "-msse2avx") {
2654 CmdArgs.push_back("-msse2avx");
2655 continue;
2656 }
2657 break;
2658 case llvm::Triple::wasm32:
2659 case llvm::Triple::wasm64:
2660 if (Value == "--no-type-check") {
2661 CmdArgs.push_back("-mno-type-check");
2662 continue;
2663 }
2664 break;
2665 case llvm::Triple::thumb:
2666 case llvm::Triple::thumbeb:
2667 case llvm::Triple::arm:
2668 case llvm::Triple::armeb:
2669 if (Equal.first == "-mimplicit-it") {
2670 // Only store the value; the last value set takes effect.
2671 ImplicitIt = Equal.second;
2672 checkArg(true, {"always", "never", "arm", "thumb"});
2673 continue;
2674 }
2675 if (Value == "-mthumb")
2676 // -mthumb has already been processed in ComputeLLVMTriple()
2677 // recognize but skip over here.
2678 continue;
2679 break;
2680 case llvm::Triple::aarch64:
2681 case llvm::Triple::aarch64_be:
2682 case llvm::Triple::aarch64_32:
2683 if (Equal.first == "-mmapsyms") {
2684 ImplicitMapSyms = Equal.second == "implicit";
2685 checkArg(IsELF, {"default", "implicit"});
2686 continue;
2687 }
2688 break;
2689 case llvm::Triple::mips:
2690 case llvm::Triple::mipsel:
2691 case llvm::Triple::mips64:
2692 case llvm::Triple::mips64el:
2693 if (Value == "--trap") {
2694 CmdArgs.push_back("-target-feature");
2695 CmdArgs.push_back("+use-tcc-in-div");
2696 continue;
2697 }
2698 if (Value == "--break") {
2699 CmdArgs.push_back("-target-feature");
2700 CmdArgs.push_back("-use-tcc-in-div");
2701 continue;
2702 }
2703 if (Value.starts_with("-msoft-float")) {
2704 CmdArgs.push_back("-target-feature");
2705 CmdArgs.push_back("+soft-float");
2706 continue;
2707 }
2708 if (Value.starts_with("-mhard-float")) {
2709 CmdArgs.push_back("-target-feature");
2710 CmdArgs.push_back("-soft-float");
2711 continue;
2712 }
2713 if (Value == "-mmsa") {
2714 Msa = true;
2715 continue;
2716 }
2717 if (Value == "-mno-msa") {
2718 Msa = false;
2719 continue;
2720 }
2721 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2722 .Case("-mips1", "+mips1")
2723 .Case("-mips2", "+mips2")
2724 .Case("-mips3", "+mips3")
2725 .Case("-mips4", "+mips4")
2726 .Case("-mips5", "+mips5")
2727 .Case("-mips32", "+mips32")
2728 .Case("-mips32r2", "+mips32r2")
2729 .Case("-mips32r3", "+mips32r3")
2730 .Case("-mips32r5", "+mips32r5")
2731 .Case("-mips32r6", "+mips32r6")
2732 .Case("-mips64", "+mips64")
2733 .Case("-mips64r2", "+mips64r2")
2734 .Case("-mips64r3", "+mips64r3")
2735 .Case("-mips64r5", "+mips64r5")
2736 .Case("-mips64r6", "+mips64r6")
2737 .Default(nullptr);
2738 if (MipsTargetFeature)
2739 continue;
2740 break;
2741
2742 case llvm::Triple::sparc:
2743 case llvm::Triple::sparcel:
2744 case llvm::Triple::sparcv9:
2745 if (Value == "--undeclared-regs") {
2746 // LLVM already allows undeclared use of G registers, so this option
2747 // becomes a no-op. This solely exists for GNU compatibility.
2748 // TODO implement --no-undeclared-regs
2749 continue;
2750 }
2751 SparcTargetFeatures =
2752 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2753 .Case("-Av8", {"-v8plus"})
2754 .Case("-Av8plus", {"+v8plus", "+v9"})
2755 .Case("-Av8plusa", {"+v8plus", "+v9", "+vis"})
2756 .Case("-Av8plusb", {"+v8plus", "+v9", "+vis", "+vis2"})
2757 .Case("-Av8plusd", {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2758 .Case("-Av9", {"+v9"})
2759 .Case("-Av9a", {"+v9", "+vis"})
2760 .Case("-Av9b", {"+v9", "+vis", "+vis2"})
2761 .Case("-Av9d", {"+v9", "+vis", "+vis2", "+vis3"})
2762 .Default({});
2763 if (!SparcTargetFeatures.empty())
2764 continue;
2765 break;
2766 }
2767
2768 if (Value == "-force_cpusubtype_ALL") {
2769 // Do nothing, this is the default and we don't support anything else.
2770 } else if (Value == "-L") {
2771 CmdArgs.push_back("-msave-temp-labels");
2772 } else if (Value == "--fatal-warnings") {
2773 CmdArgs.push_back("-massembler-fatal-warnings");
2774 } else if (Value == "--no-warn" || Value == "-W") {
2775 CmdArgs.push_back("-massembler-no-warn");
2776 } else if (Value == "--noexecstack") {
2777 UseNoExecStack = true;
2778 } else if (Value.starts_with("-compress-debug-sections") ||
2779 Value.starts_with("--compress-debug-sections") ||
2780 Value == "-nocompress-debug-sections" ||
2781 Value == "--nocompress-debug-sections") {
2782 CmdArgs.push_back(Value.data());
2783 } else if (Value == "--crel") {
2784 Crel = true;
2785 } else if (Value == "--no-crel") {
2786 Crel = false;
2787 } else if (Value == "--allow-experimental-crel") {
2788 ExperimentalCrel = true;
2789 } else if (Value.starts_with("--reloc-section-sym=")) {
2790 RelocSectionSym = Value.substr(strlen("--reloc-section-sym="));
2791 } else if (Value.starts_with("-I")) {
2792 CmdArgs.push_back(Value.data());
2793 // We need to consume the next argument if the current arg is a plain
2794 // -I. The next arg will be the include directory.
2795 if (Value == "-I")
2796 TakeNextArg = true;
2797 } else if (Value.starts_with("-gdwarf-")) {
2798 // "-gdwarf-N" options are not cc1as options.
2799 unsigned DwarfVersion = DwarfVersionNum(Value);
2800 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2801 CmdArgs.push_back(Value.data());
2802 } else {
2803 RenderDebugEnablingArgs(Args, CmdArgs,
2804 llvm::codegenoptions::DebugInfoConstructor,
2805 DwarfVersion, llvm::DebuggerKind::Default);
2806 }
2807 } else if (Value == "--gsframe") {
2808 SFrame = true;
2809 } else if (Value == "--allow-experimental-sframe") {
2810 ExperimentalSFrame = true;
2811 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2812 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2813 // Do nothing, we'll validate it later.
2814 } else if (Value == "-defsym" || Value == "--defsym") {
2815 if (A->getNumValues() != 2) {
2816 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2817 break;
2818 }
2819 const char *S = A->getValue(1);
2820 auto Pair = StringRef(S).split('=');
2821 auto Sym = Pair.first;
2822 auto SVal = Pair.second;
2823
2824 if (Sym.empty() || SVal.empty()) {
2825 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2826 break;
2827 }
2828 int64_t IVal;
2829 if (SVal.getAsInteger(0, IVal)) {
2830 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2831 break;
2832 }
2833 CmdArgs.push_back("--defsym");
2834 TakeNextArg = true;
2835 } else if (Value == "-fdebug-compilation-dir") {
2836 CmdArgs.push_back("-fdebug-compilation-dir");
2837 TakeNextArg = true;
2838 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2839 // The flag is a -Wa / -Xassembler argument and Options doesn't
2840 // parse the argument, so this isn't automatically aliased to
2841 // -fdebug-compilation-dir (without '=') here.
2842 CmdArgs.push_back("-fdebug-compilation-dir");
2843 CmdArgs.push_back(Value.data());
2844 } else if (Value == "--version") {
2845 D.PrintVersion(C, llvm::outs());
2846 } else {
2847 D.Diag(diag::err_drv_unsupported_option_argument)
2848 << A->getSpelling() << Value;
2849 }
2850 }
2851 }
2852 if (ImplicitIt.size())
2853 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2854 if (Crel) {
2855 if (!ExperimentalCrel)
2856 D.Diag(diag::err_drv_experimental_crel);
2857 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2858 CmdArgs.push_back("--crel");
2859 } else {
2860 D.Diag(diag::err_drv_unsupported_opt_for_target)
2861 << "-Wa,--crel" << D.getTargetTriple();
2862 }
2863 }
2864 if (!RelocSectionSym.empty()) {
2865 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2866 RelocSectionSym != "none")
2867 D.Diag(diag::err_drv_invalid_value)
2868 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2869 << RelocSectionSym;
2870 else if (Triple.isOSBinFormatELF())
2871 CmdArgs.push_back(
2872 Args.MakeArgString("--reloc-section-sym=" + RelocSectionSym));
2873 else
2874 D.Diag(diag::err_drv_unsupported_opt_for_target)
2875 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2876 }
2877 if (SFrame) {
2878 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2879 if (!ExperimentalSFrame)
2880 D.Diag(diag::err_drv_experimental_sframe);
2881 else
2882 CmdArgs.push_back("--gsframe");
2883 } else {
2884 D.Diag(diag::err_drv_unsupported_opt_for_target)
2885 << "-Wa,--gsframe" << D.getTargetTriple();
2886 }
2887 }
2888 if (ImplicitMapSyms)
2889 CmdArgs.push_back("-mmapsyms=implicit");
2890 if (Msa)
2891 CmdArgs.push_back("-mmsa");
2892 if (!UseRelaxRelocations)
2893 CmdArgs.push_back("-mrelax-relocations=no");
2894 if (UseNoExecStack)
2895 CmdArgs.push_back("-mnoexecstack");
2896 if (MipsTargetFeature != nullptr) {
2897 CmdArgs.push_back("-target-feature");
2898 CmdArgs.push_back(MipsTargetFeature);
2899 }
2900
2901 for (const char *Feature : SparcTargetFeatures) {
2902 CmdArgs.push_back("-target-feature");
2903 CmdArgs.push_back(Feature);
2904 }
2905
2906 // forward -fembed-bitcode to assmebler
2907 if (C.getDriver().embedBitcodeEnabled() ||
2908 C.getDriver().embedBitcodeMarkerOnly())
2909 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2910
2911 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2912 CmdArgs.push_back("-as-secure-log-file");
2913 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2914 }
2915}
2916
2917static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2918 bool OFastEnabled, const ArgList &Args,
2919 ArgStringList &CmdArgs,
2920 const JobAction &JA) {
2921 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2922 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2923 llvm::StringLiteral("SLEEF")};
2924 bool NoMathErrnoWasImpliedByVecLib = false;
2925 const Arg *VecLibArg = nullptr;
2926 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2927 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2928
2929 // Handle various floating point optimization flags, mapping them to the
2930 // appropriate LLVM code generation flags. This is complicated by several
2931 // "umbrella" flags, so we do this by stepping through the flags incrementally
2932 // adjusting what we think is enabled/disabled, then at the end setting the
2933 // LLVM flags based on the final state.
2934 bool HonorINFs = true;
2935 bool HonorNaNs = true;
2936 bool ApproxFunc = false;
2937 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2938 bool MathErrno = TC.IsMathErrnoDefault();
2939 bool AssociativeMath = false;
2940 bool ReciprocalMath = false;
2941 bool SignedZeros = true;
2942 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2943 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2944 // overriden by ffp-exception-behavior?
2945 bool RoundingFPMath = false;
2946 // -ffp-model values: strict, fast, precise
2947 StringRef FPModel = "";
2948 // -ffp-exception-behavior options: strict, maytrap, ignore
2949 StringRef FPExceptionBehavior = "";
2950 // -ffp-eval-method options: double, extended, source
2951 StringRef FPEvalMethod = "";
2952 llvm::DenormalMode DenormalFPMath =
2953 TC.getDefaultDenormalModeForType(Args, JA);
2954 llvm::DenormalMode DenormalFP32Math =
2955 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2956
2957 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2958 // If one wasn't given by the user, don't pass it here.
2959 StringRef FPContract;
2960 StringRef LastSeenFfpContractOption;
2961 StringRef LastFpContractOverrideOption;
2962 bool SeenUnsafeMathModeOption = false;
2965 FPContract = "on";
2966 bool StrictFPModel = false;
2967 StringRef Float16ExcessPrecision = "";
2968 StringRef BFloat16ExcessPrecision = "";
2970 std::string ComplexRangeStr;
2971 StringRef LastComplexRangeOption;
2972
2973 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2974 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2975 if (Aggressive) {
2976 HonorINFs = false;
2977 HonorNaNs = false;
2979 LastComplexRangeOption, Range);
2980 } else {
2981 HonorINFs = true;
2982 HonorNaNs = true;
2983 setComplexRange(D, CallerOption,
2985 LastComplexRangeOption, Range);
2986 }
2987 MathErrno = false;
2988 AssociativeMath = true;
2989 ReciprocalMath = true;
2990 ApproxFunc = true;
2991 SignedZeros = false;
2992 TrappingMath = false;
2993 RoundingFPMath = false;
2994 FPExceptionBehavior = "";
2995 FPContract = "fast";
2996 SeenUnsafeMathModeOption = true;
2997 };
2998
2999 // Lambda to consolidate common handling for fp-contract
3000 auto restoreFPContractState = [&]() {
3001 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
3002 // For other targets, if the state has been changed by one of the
3003 // unsafe-math umbrella options a subsequent -fno-fast-math or
3004 // -fno-unsafe-math-optimizations option reverts to the last value seen for
3005 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
3006 // option. If we have not seen an unsafe-math option or -ffp-contract,
3007 // we leave the FPContract state unchanged.
3010 if (LastSeenFfpContractOption != "")
3011 FPContract = LastSeenFfpContractOption;
3012 else if (SeenUnsafeMathModeOption)
3013 FPContract = "on";
3014 }
3015 // In this case, we're reverting to the last explicit fp-contract option
3016 // or the platform default
3017 LastFpContractOverrideOption = "";
3018 };
3019
3020 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3021 CmdArgs.push_back("-mlimit-float-precision");
3022 CmdArgs.push_back(A->getValue());
3023 }
3024
3025 for (const Arg *A : Args) {
3026 llvm::scope_exit CheckMathErrnoForVecLib(
3027 [&, MathErrnoBeforeArg = MathErrno] {
3028 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3029 ArgThatEnabledMathErrnoAfterVecLib = A;
3030 });
3031
3032 switch (A->getOption().getID()) {
3033 // If this isn't an FP option skip the claim below
3034 default: continue;
3035
3036 case options::OPT_fcx_limited_range:
3037 setComplexRange(D, A->getSpelling(),
3039 LastComplexRangeOption, Range);
3040 break;
3041 case options::OPT_fno_cx_limited_range:
3042 setComplexRange(D, A->getSpelling(),
3044 LastComplexRangeOption, Range);
3045 break;
3046 case options::OPT_fcx_fortran_rules:
3047 setComplexRange(D, A->getSpelling(),
3049 LastComplexRangeOption, Range);
3050 break;
3051 case options::OPT_fno_cx_fortran_rules:
3052 setComplexRange(D, A->getSpelling(),
3054 LastComplexRangeOption, Range);
3055 break;
3056 case options::OPT_fcomplex_arithmetic_EQ: {
3058 StringRef Val = A->getValue();
3059 if (Val == "full")
3061 else if (Val == "improved")
3063 else if (Val == "promoted")
3065 else if (Val == "basic")
3067 else {
3068 D.Diag(diag::err_drv_unsupported_option_argument)
3069 << A->getSpelling() << Val;
3070 break;
3071 }
3072 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), RangeVal,
3073 LastComplexRangeOption, Range);
3074 break;
3075 }
3076 case options::OPT_ffp_model_EQ: {
3077 // If -ffp-model= is seen, reset to fno-fast-math
3078 HonorINFs = true;
3079 HonorNaNs = true;
3080 ApproxFunc = false;
3081 // Turning *off* -ffast-math restores the toolchain default.
3082 MathErrno = TC.IsMathErrnoDefault();
3083 AssociativeMath = false;
3084 ReciprocalMath = false;
3085 SignedZeros = true;
3086
3087 StringRef Val = A->getValue();
3088 if (OFastEnabled && Val != "aggressive") {
3089 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3090 D.Diag(clang::diag::warn_drv_overriding_option)
3091 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3092 break;
3093 }
3094 StrictFPModel = false;
3095 if (!FPModel.empty() && FPModel != Val)
3096 D.Diag(clang::diag::warn_drv_overriding_option)
3097 << Args.MakeArgString("-ffp-model=" + FPModel)
3098 << Args.MakeArgString("-ffp-model=" + Val);
3099 if (Val == "fast") {
3100 FPModel = Val;
3101 applyFastMath(false, Args.MakeArgString(A->getSpelling() + Val));
3102 // applyFastMath sets fp-contract="fast"
3103 LastFpContractOverrideOption = "-ffp-model=fast";
3104 } else if (Val == "aggressive") {
3105 FPModel = Val;
3106 applyFastMath(true, Args.MakeArgString(A->getSpelling() + Val));
3107 // applyFastMath sets fp-contract="fast"
3108 LastFpContractOverrideOption = "-ffp-model=aggressive";
3109 } else if (Val == "precise") {
3110 FPModel = Val;
3111 FPContract = "on";
3112 LastFpContractOverrideOption = "-ffp-model=precise";
3113 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3115 LastComplexRangeOption, Range);
3116 } else if (Val == "strict") {
3117 StrictFPModel = true;
3118 FPExceptionBehavior = "strict";
3119 FPModel = Val;
3120 FPContract = "off";
3121 LastFpContractOverrideOption = "-ffp-model=strict";
3122 TrappingMath = true;
3123 RoundingFPMath = true;
3124 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val),
3126 LastComplexRangeOption, Range);
3127 } else
3128 D.Diag(diag::err_drv_unsupported_option_argument)
3129 << A->getSpelling() << Val;
3130 break;
3131 }
3132
3133 // Options controlling individual features
3134 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3135 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3136 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3137 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3138 case options::OPT_fapprox_func: ApproxFunc = true; break;
3139 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3140 case options::OPT_fmath_errno: MathErrno = true; break;
3141 case options::OPT_fno_math_errno: MathErrno = false; break;
3142 case options::OPT_fassociative_math: AssociativeMath = true; break;
3143 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3144 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3145 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3146 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3147 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3148 case options::OPT_ftrapping_math:
3149 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3150 FPExceptionBehavior != "strict")
3151 // Warn that previous value of option is overridden.
3152 D.Diag(clang::diag::warn_drv_overriding_option)
3153 << Args.MakeArgString("-ffp-exception-behavior=" +
3154 FPExceptionBehavior)
3155 << "-ftrapping-math";
3156 TrappingMath = true;
3157 TrappingMathPresent = true;
3158 FPExceptionBehavior = "strict";
3159 break;
3160 case options::OPT_fveclib:
3161 VecLibArg = A;
3162 NoMathErrnoWasImpliedByVecLib =
3163 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3164 if (NoMathErrnoWasImpliedByVecLib)
3165 MathErrno = false;
3166 break;
3167 case options::OPT_fno_trapping_math:
3168 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3169 FPExceptionBehavior != "ignore")
3170 // Warn that previous value of option is overridden.
3171 D.Diag(clang::diag::warn_drv_overriding_option)
3172 << Args.MakeArgString("-ffp-exception-behavior=" +
3173 FPExceptionBehavior)
3174 << "-fno-trapping-math";
3175 TrappingMath = false;
3176 TrappingMathPresent = true;
3177 FPExceptionBehavior = "ignore";
3178 break;
3179
3180 case options::OPT_frounding_math:
3181 RoundingFPMath = true;
3182 break;
3183
3184 case options::OPT_fno_rounding_math:
3185 RoundingFPMath = false;
3186 break;
3187
3188 case options::OPT_fdenormal_fp_math_EQ:
3189 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3190 DenormalFP32Math = DenormalFPMath;
3191 if (!DenormalFPMath.isValid()) {
3192 D.Diag(diag::err_drv_invalid_value)
3193 << A->getAsString(Args) << A->getValue();
3194 }
3195 break;
3196
3197 case options::OPT_fdenormal_fp_math_f32_EQ:
3198 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3199 if (!DenormalFP32Math.isValid()) {
3200 D.Diag(diag::err_drv_invalid_value)
3201 << A->getAsString(Args) << A->getValue();
3202 }
3203 break;
3204
3205 // Validate and pass through -ffp-contract option.
3206 case options::OPT_ffp_contract: {
3207 StringRef Val = A->getValue();
3208 if (Val == "fast" || Val == "on" || Val == "off" ||
3209 Val == "fast-honor-pragmas") {
3210 if (Val != FPContract && LastFpContractOverrideOption != "") {
3211 D.Diag(clang::diag::warn_drv_overriding_option)
3212 << LastFpContractOverrideOption
3213 << Args.MakeArgString("-ffp-contract=" + Val);
3214 }
3215
3216 FPContract = Val;
3217 LastSeenFfpContractOption = Val;
3218 LastFpContractOverrideOption = "";
3219 } else
3220 D.Diag(diag::err_drv_unsupported_option_argument)
3221 << A->getSpelling() << Val;
3222 break;
3223 }
3224
3225 // Validate and pass through -ffp-exception-behavior option.
3226 case options::OPT_ffp_exception_behavior_EQ: {
3227 StringRef Val = A->getValue();
3228 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3229 FPExceptionBehavior != Val)
3230 // Warn that previous value of option is overridden.
3231 D.Diag(clang::diag::warn_drv_overriding_option)
3232 << Args.MakeArgString("-ffp-exception-behavior=" +
3233 FPExceptionBehavior)
3234 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3235 TrappingMath = TrappingMathPresent = false;
3236 if (Val == "ignore" || Val == "maytrap")
3237 FPExceptionBehavior = Val;
3238 else if (Val == "strict") {
3239 FPExceptionBehavior = Val;
3240 TrappingMath = TrappingMathPresent = true;
3241 } else
3242 D.Diag(diag::err_drv_unsupported_option_argument)
3243 << A->getSpelling() << Val;
3244 break;
3245 }
3246
3247 // Validate and pass through -ffp-eval-method option.
3248 case options::OPT_ffp_eval_method_EQ: {
3249 StringRef Val = A->getValue();
3250 if (Val == "double" || Val == "extended" || Val == "source")
3251 FPEvalMethod = Val;
3252 else
3253 D.Diag(diag::err_drv_unsupported_option_argument)
3254 << A->getSpelling() << Val;
3255 break;
3256 }
3257
3258 case options::OPT_fexcess_precision_EQ: {
3259 StringRef Val = A->getValue();
3260 const llvm::Triple::ArchType Arch = TC.getArch();
3261 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3262 if (Val == "standard" || Val == "fast")
3263 Float16ExcessPrecision = Val;
3264 // To make it GCC compatible, allow the value of "16" which
3265 // means disable excess precision, the same meaning than clang's
3266 // equivalent value "none".
3267 else if (Val == "16")
3268 Float16ExcessPrecision = "none";
3269 else
3270 D.Diag(diag::err_drv_unsupported_option_argument)
3271 << A->getSpelling() << Val;
3272 } else {
3273 if (!(Val == "standard" || Val == "fast"))
3274 D.Diag(diag::err_drv_unsupported_option_argument)
3275 << A->getSpelling() << Val;
3276 }
3277 BFloat16ExcessPrecision = Float16ExcessPrecision;
3278 break;
3279 }
3280 case options::OPT_ffinite_math_only:
3281 HonorINFs = false;
3282 HonorNaNs = false;
3283 break;
3284 case options::OPT_fno_finite_math_only:
3285 HonorINFs = true;
3286 HonorNaNs = true;
3287 break;
3288
3289 case options::OPT_funsafe_math_optimizations:
3290 AssociativeMath = true;
3291 ReciprocalMath = true;
3292 SignedZeros = false;
3293 ApproxFunc = true;
3294 TrappingMath = false;
3295 FPExceptionBehavior = "";
3296 FPContract = "fast";
3297 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3298 SeenUnsafeMathModeOption = true;
3299 break;
3300 case options::OPT_fno_unsafe_math_optimizations:
3301 AssociativeMath = false;
3302 ReciprocalMath = false;
3303 SignedZeros = true;
3304 ApproxFunc = false;
3305 restoreFPContractState();
3306 break;
3307
3308 case options::OPT_cl_fast_relaxed_math:
3309 applyFastMath(true, A->getSpelling());
3310 break;
3311
3312 case options::OPT_Ofast:
3313 // If -Ofast is the optimization level, then -ffast-math should be enabled
3314 if (!OFastEnabled)
3315 continue;
3316 [[fallthrough]];
3317 case options::OPT_ffast_math:
3318 applyFastMath(true, A->getSpelling());
3319 if (A->getOption().getID() == options::OPT_Ofast)
3320 LastFpContractOverrideOption = "-Ofast";
3321 else
3322 LastFpContractOverrideOption = "-ffast-math";
3323 break;
3324 case options::OPT_fno_fast_math:
3325 HonorINFs = true;
3326 HonorNaNs = true;
3327 // Turning on -ffast-math (with either flag) removes the need for
3328 // MathErrno. However, turning *off* -ffast-math merely restores the
3329 // toolchain default (which may be false).
3330 MathErrno = TC.IsMathErrnoDefault();
3331 AssociativeMath = false;
3332 ReciprocalMath = false;
3333 ApproxFunc = false;
3334 SignedZeros = true;
3335 restoreFPContractState();
3337 setComplexRange(D, A->getSpelling(),
3339 LastComplexRangeOption, Range);
3340 else
3342 LastComplexRangeOption = "";
3343 LastFpContractOverrideOption = "";
3344 break;
3345 } // End switch (A->getOption().getID())
3346
3347 // The StrictFPModel local variable is needed to report warnings
3348 // in the way we intend. If -ffp-model=strict has been used, we
3349 // want to report a warning for the next option encountered that
3350 // takes us out of the settings described by fp-model=strict, but
3351 // we don't want to continue issuing warnings for other conflicting
3352 // options after that.
3353 if (StrictFPModel) {
3354 // If -ffp-model=strict has been specified on command line but
3355 // subsequent options conflict then emit warning diagnostic.
3356 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3357 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3358 FPContract == "off")
3359 // OK: Current Arg doesn't conflict with -ffp-model=strict
3360 ;
3361 else {
3362 StrictFPModel = false;
3363 FPModel = "";
3364 // The warning for -ffp-contract would have been reported by the
3365 // OPT_ffp_contract_EQ handler above. A special check here is needed
3366 // to avoid duplicating the warning.
3367 auto RHS = (A->getNumValues() == 0)
3368 ? A->getSpelling()
3369 : Args.MakeArgString(A->getSpelling() + A->getValue());
3370 if (A->getSpelling() != "-ffp-contract=") {
3371 if (RHS != "-ffp-model=strict")
3372 D.Diag(clang::diag::warn_drv_overriding_option)
3373 << "-ffp-model=strict" << RHS;
3374 }
3375 }
3376 }
3377
3378 // If we handled this option claim it
3379 A->claim();
3380 }
3381
3382 if (!HonorINFs)
3383 CmdArgs.push_back("-menable-no-infs");
3384
3385 if (!HonorNaNs)
3386 CmdArgs.push_back("-menable-no-nans");
3387
3388 if (ApproxFunc)
3389 CmdArgs.push_back("-fapprox-func");
3390
3391 if (MathErrno) {
3392 CmdArgs.push_back("-fmath-errno");
3393 if (NoMathErrnoWasImpliedByVecLib)
3394 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3395 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3396 << VecLibArg->getAsString(Args);
3397 }
3398
3399 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3400 !TrappingMath)
3401 CmdArgs.push_back("-funsafe-math-optimizations");
3402
3403 if (!SignedZeros)
3404 CmdArgs.push_back("-fno-signed-zeros");
3405
3406 if (AssociativeMath && !SignedZeros && !TrappingMath)
3407 CmdArgs.push_back("-mreassociate");
3408
3409 if (ReciprocalMath)
3410 CmdArgs.push_back("-freciprocal-math");
3411
3412 if (TrappingMath) {
3413 // FP Exception Behavior is also set to strict
3414 assert(FPExceptionBehavior == "strict");
3415 }
3416
3417 // The default is IEEE.
3418 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3419 llvm::SmallString<64> DenormFlag;
3420 llvm::raw_svector_ostream ArgStr(DenormFlag);
3421 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3422 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3423 }
3424
3425 // Add f32 specific denormal mode flag if it's different.
3426 if (DenormalFP32Math != DenormalFPMath) {
3427 llvm::SmallString<64> DenormFlag;
3428 llvm::raw_svector_ostream ArgStr(DenormFlag);
3429 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3430 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3431 }
3432
3433 if (!FPContract.empty())
3434 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3435
3436 if (RoundingFPMath)
3437 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3438 else
3439 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3440
3441 if (!FPExceptionBehavior.empty())
3442 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3443 FPExceptionBehavior));
3444
3445 if (!FPEvalMethod.empty())
3446 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3447
3448 if (!Float16ExcessPrecision.empty())
3449 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3450 Float16ExcessPrecision));
3451 if (!BFloat16ExcessPrecision.empty())
3452 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3453 BFloat16ExcessPrecision));
3454
3455 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
3456 if (!Recip.empty())
3457 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
3458
3459 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3460 // individual features enabled by -ffast-math instead of the option itself as
3461 // that's consistent with gcc's behaviour.
3462 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3463 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3464 CmdArgs.push_back("-ffast-math");
3465
3466 // Handle __FINITE_MATH_ONLY__ similarly.
3467 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3468 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3469 // -menable-no-nans are set by the user.
3470 bool shouldAddFiniteMathOnly = false;
3471 if (!HonorINFs && !HonorNaNs) {
3472 shouldAddFiniteMathOnly = true;
3473 } else {
3474 bool InfValues = true;
3475 bool NanValues = true;
3476 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3477 StringRef ArgValue = Arg->getValue();
3478 if (ArgValue == "-menable-no-nans")
3479 NanValues = false;
3480 else if (ArgValue == "-menable-no-infs")
3481 InfValues = false;
3482 }
3483 if (!NanValues && !InfValues)
3484 shouldAddFiniteMathOnly = true;
3485 }
3486 if (shouldAddFiniteMathOnly) {
3487 CmdArgs.push_back("-ffinite-math-only");
3488 }
3489 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3490 CmdArgs.push_back("-mfpmath");
3491 CmdArgs.push_back(A->getValue());
3492 }
3493
3494 // Disable a codegen optimization for floating-point casts.
3495 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3496 options::OPT_fstrict_float_cast_overflow, false))
3497 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3498
3500 ComplexRangeStr = renderComplexRangeOption(Range);
3501 if (!ComplexRangeStr.empty()) {
3502 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3503 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3504 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3505 complexRangeKindToStr(Range)));
3506 }
3507 if (Args.hasArg(options::OPT_fcx_limited_range))
3508 CmdArgs.push_back("-fcx-limited-range");
3509 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3510 CmdArgs.push_back("-fcx-fortran-rules");
3511 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3512 CmdArgs.push_back("-fno-cx-limited-range");
3513 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3514 CmdArgs.push_back("-fno-cx-fortran-rules");
3515}
3516
3517static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3518 const llvm::Triple &Triple,
3519 const InputInfo &Input) {
3520 // Add default argument set.
3521 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3522 CmdArgs.push_back("-analyzer-checker=core");
3523 CmdArgs.push_back("-analyzer-checker=apiModeling");
3524
3525 if (!Triple.isWindowsMSVCEnvironment()) {
3526 CmdArgs.push_back("-analyzer-checker=unix");
3527 } else {
3528 // Enable "unix" checkers that also work on Windows.
3529 CmdArgs.push_back("-analyzer-checker=unix.API");
3530 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3531 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3532 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3533 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3534 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3535 }
3536
3537 // Disable some unix checkers for PS4/PS5.
3538 if (Triple.isPS()) {
3539 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3540 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3541 }
3542
3543 if (Triple.isOSDarwin()) {
3544 CmdArgs.push_back("-analyzer-checker=osx");
3545 CmdArgs.push_back(
3546 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3547 }
3548 else if (Triple.isOSFuchsia())
3549 CmdArgs.push_back("-analyzer-checker=fuchsia");
3550
3551 CmdArgs.push_back("-analyzer-checker=deadcode");
3552
3553 if (types::isCXX(Input.getType()))
3554 CmdArgs.push_back("-analyzer-checker=cplusplus");
3555
3556 if (!Triple.isPS()) {
3557 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3558 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3559 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3560 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3561 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3562 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3563 }
3564
3565 // Default nullability checks.
3566 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3567 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3568 }
3569
3570 // Set the output format. The default is plist, for (lame) historical reasons.
3571 CmdArgs.push_back("-analyzer-output");
3572 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3573 CmdArgs.push_back(A->getValue());
3574 else
3575 CmdArgs.push_back("plist");
3576
3577 // Disable the presentation of standard compiler warnings when using
3578 // --analyze. We only want to show static analyzer diagnostics or frontend
3579 // errors.
3580 CmdArgs.push_back("-w");
3581
3582 // Add -Xanalyzer arguments when running as analyzer.
3583 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3584}
3585
3586static bool isValidSymbolName(StringRef S) {
3587 if (S.empty())
3588 return false;
3589
3590 if (std::isdigit(S[0]))
3591 return false;
3592
3593 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3594}
3595
3596static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3597 const ArgList &Args, ArgStringList &CmdArgs,
3598 bool KernelOrKext) {
3599 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3600
3601 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3602 // doesn't even have a stack!
3603 if (EffectiveTriple.isNVPTX())
3604 return;
3605
3606 // -stack-protector=0 is default.
3608 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3609 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3610
3611 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3612 options::OPT_fstack_protector_all,
3613 options::OPT_fstack_protector_strong,
3614 options::OPT_fstack_protector)) {
3615 if (A->getOption().matches(options::OPT_fstack_protector))
3616 StackProtectorLevel =
3617 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3618 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3619 StackProtectorLevel = LangOptions::SSPStrong;
3620 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3621 StackProtectorLevel = LangOptions::SSPReq;
3622
3623 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3624 D.Diag(diag::warn_drv_unsupported_option_for_target)
3625 << A->getSpelling() << EffectiveTriple.getTriple();
3626 StackProtectorLevel = DefaultStackProtectorLevel;
3627 }
3628 } else {
3629 StackProtectorLevel = DefaultStackProtectorLevel;
3630 }
3631
3632 if (StackProtectorLevel) {
3633 CmdArgs.push_back("-stack-protector");
3634 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3635 }
3636
3637 // --param ssp-buffer-size=
3638 for (const Arg *A : Args.filtered(options::OPT__param)) {
3639 StringRef Str(A->getValue());
3640 if (Str.consume_front("ssp-buffer-size=")) {
3641 if (StackProtectorLevel) {
3642 CmdArgs.push_back("-stack-protector-buffer-size");
3643 // FIXME: Verify the argument is a valid integer.
3644 CmdArgs.push_back(Args.MakeArgString(Str));
3645 }
3646 A->claim();
3647 }
3648 }
3649
3650 const std::string &TripleStr = EffectiveTriple.getTriple();
3651 StringRef GuardValue;
3652 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3653 GuardValue = A->getValue();
3654 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3655 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3656 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC() &&
3657 !EffectiveTriple.isSystemZ())
3658 D.Diag(diag::err_drv_unsupported_opt_for_target)
3659 << A->getAsString(Args) << TripleStr;
3660 // z/OS only supports the tls mode.
3661 if (EffectiveTriple.isOSzOS() && GuardValue != "tls") {
3662 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3663 << A->getOption().getName() << GuardValue << "tls";
3664 return;
3665 }
3666 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3667 EffectiveTriple.isThumb() || EffectiveTriple.isSystemZ()) &&
3668 GuardValue != "tls" && GuardValue != "global") {
3669 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3670 << A->getOption().getName() << GuardValue << "tls global";
3671 return;
3672 }
3673 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3674 GuardValue == "tls") {
3675 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3676 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3677 << A->getAsString(Args);
3678 return;
3679 }
3680 // Check whether the target subarch supports the hardware TLS register
3681 if (!arm::isHardTPSupported(EffectiveTriple)) {
3682 D.Diag(diag::err_target_unsupported_tp_hard)
3683 << EffectiveTriple.getArchName();
3684 return;
3685 }
3686 // Check whether the user asked for something other than -mtp=cp15
3687 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3688 StringRef Value = A->getValue();
3689 if (Value != "cp15") {
3690 D.Diag(diag::err_drv_argument_not_allowed_with)
3691 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3692 return;
3693 }
3694 }
3695 CmdArgs.push_back("-target-feature");
3696 CmdArgs.push_back("+read-tp-tpidruro");
3697 }
3698 if (EffectiveTriple.isAArch64() && GuardValue != "sysreg" &&
3699 GuardValue != "global") {
3700 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3701 << A->getOption().getName() << GuardValue << "sysreg global";
3702 return;
3703 }
3704 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3705 if (GuardValue != "tls" && GuardValue != "global") {
3706 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3707 << A->getOption().getName() << GuardValue << "tls global";
3708 return;
3709 }
3710 if (GuardValue == "tls") {
3711 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3712 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3713 << A->getAsString(Args);
3714 return;
3715 }
3716 }
3717 }
3718 A->render(Args, CmdArgs);
3719 }
3720
3721 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3722 StringRef Value = A->getValue();
3723 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3724 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3725 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3726 D.Diag(diag::err_drv_unsupported_opt_for_target)
3727 << A->getAsString(Args) << TripleStr;
3728 int Offset;
3729 if (Value.getAsInteger(10, Offset)) {
3730 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3731 return;
3732 }
3733 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3734 (Offset < 0 || Offset > 0xfffff)) {
3735 D.Diag(diag::err_drv_invalid_int_value)
3736 << A->getOption().getName() << Value;
3737 return;
3738 }
3739 A->render(Args, CmdArgs);
3740 }
3741
3742 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3743 StringRef Value = A->getValue();
3744 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3745 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3746 D.Diag(diag::err_drv_unsupported_opt_for_target)
3747 << A->getAsString(Args) << TripleStr;
3748 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3749 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3750 << A->getOption().getName() << Value << "fs gs";
3751 return;
3752 }
3753 if (EffectiveTriple.isAArch64() &&
3754 llvm::StringSwitch<bool>(Value)
3755 .Cases({"sp_el0", "tpidrro_el0", "tpidr_el0", "tpidr_el1",
3756 "tpidr_el2", "far_el1", "far_el2"},
3757 false)
3758 .Default(true)) {
3759 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3760 << A->getOption().getName() << Value
3761 << "{sp_el0, tpidrro_el0, tpidr_el[012], far_el[12]}";
3762 return;
3763 }
3764 if (EffectiveTriple.isRISCV() && Value != "tp") {
3765 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3766 << A->getOption().getName() << Value << "tp";
3767 return;
3768 }
3769 if (EffectiveTriple.isPPC64() && Value != "r13") {
3770 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3771 << A->getOption().getName() << Value << "r13";
3772 return;
3773 }
3774 if (EffectiveTriple.isPPC32() && Value != "r2") {
3775 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3776 << A->getOption().getName() << Value << "r2";
3777 return;
3778 }
3779 A->render(Args, CmdArgs);
3780 }
3781
3782 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3783 StringRef Value = A->getValue();
3784 if (!isValidSymbolName(Value)) {
3785 D.Diag(diag::err_drv_argument_only_allowed_with)
3786 << A->getOption().getName() << "legal symbol name";
3787 return;
3788 }
3789 A->render(Args, CmdArgs);
3790 }
3791
3792 if (Arg *A =
3793 Args.getLastArg(options::OPT_mstack_protector_guard_value_width_EQ)) {
3794 if (!EffectiveTriple.isAArch64())
3795 D.Diag(diag::err_drv_unsupported_opt_for_target)
3796 << A->getAsString(Args) << TripleStr;
3797 StringRef Value = A->getValue();
3798 unsigned Width;
3799 if (Value.getAsInteger(10, Width)) {
3800 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3801 return;
3802 }
3803 if (Width != 4 && Width != 8) {
3804 D.Diag(diag::err_drv_invalid_int_value)
3805 << A->getOption().getName() << Value;
3806 }
3807 }
3808 if (Arg *A = Args.getLastArg(options::OPT_mstackprotector_guard_record)) {
3809 if (!EffectiveTriple.isSystemZ()) {
3810 D.Diag(diag::err_drv_unsupported_opt_for_target)
3811 << A->getAsString(Args) << TripleStr;
3812 return;
3813 }
3814 if (GuardValue != "global") {
3815 D.Diag(diag::err_drv_argument_only_allowed_with)
3816 << "-mstack-protector-guard-record"
3817 << "-mstack-protector-guard=global";
3818 return;
3819 }
3820 A->render(Args, CmdArgs);
3821 }
3822}
3823
3824static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3825 ArgStringList &CmdArgs) {
3826 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3827
3828 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3829 !EffectiveTriple.isOSFuchsia())
3830 return;
3831
3832 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3833 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3834 !EffectiveTriple.isRISCV() && !EffectiveTriple.isLoongArch())
3835 return;
3836
3837 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3838 options::OPT_fno_stack_clash_protection);
3839}
3840
3842 const ToolChain &TC,
3843 const ArgList &Args,
3844 ArgStringList &CmdArgs) {
3845 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3846 StringRef TrivialAutoVarInit = "";
3847
3848 for (const Arg *A : Args) {
3849 switch (A->getOption().getID()) {
3850 default:
3851 continue;
3852 case options::OPT_ftrivial_auto_var_init: {
3853 A->claim();
3854 StringRef Val = A->getValue();
3855 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3856 TrivialAutoVarInit = Val;
3857 else
3858 D.Diag(diag::err_drv_unsupported_option_argument)
3859 << A->getSpelling() << Val;
3860 break;
3861 }
3862 }
3863 }
3864
3865 if (TrivialAutoVarInit.empty())
3866 switch (DefaultTrivialAutoVarInit) {
3868 break;
3870 TrivialAutoVarInit = "pattern";
3871 break;
3873 TrivialAutoVarInit = "zero";
3874 break;
3875 }
3876
3877 if (!TrivialAutoVarInit.empty()) {
3878 CmdArgs.push_back(
3879 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3880 }
3881
3882 if (Arg *A =
3883 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3884 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3885 StringRef(
3886 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3887 "uninitialized")
3888 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3889 A->claim();
3890 StringRef Val = A->getValue();
3891 if (std::stoi(Val.str()) <= 0)
3892 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3893 CmdArgs.push_back(
3894 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3895 }
3896
3897 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3898 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3899 StringRef(
3900 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3901 "uninitialized")
3902 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3903 A->claim();
3904 StringRef Val = A->getValue();
3905 if (std::stoi(Val.str()) <= 0)
3906 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3907 CmdArgs.push_back(
3908 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3909 }
3910}
3911
3912static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3913 types::ID InputType) {
3914 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3915 // for denormal flushing handling based on the target.
3916 const unsigned ForwardedArguments[] = {
3917 options::OPT_cl_opt_disable,
3918 options::OPT_cl_strict_aliasing,
3919 options::OPT_cl_single_precision_constant,
3920 options::OPT_cl_finite_math_only,
3921 options::OPT_cl_kernel_arg_info,
3922 options::OPT_cl_unsafe_math_optimizations,
3923 options::OPT_cl_fast_relaxed_math,
3924 options::OPT_cl_mad_enable,
3925 options::OPT_cl_no_signed_zeros,
3926 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3927 options::OPT_cl_uniform_work_group_size
3928 };
3929
3930 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3931 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3932 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3933 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3934 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3935 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3936 }
3937
3938 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3939 CmdArgs.push_back("-menable-no-infs");
3940 CmdArgs.push_back("-menable-no-nans");
3941 }
3942
3943 for (const auto &Arg : ForwardedArguments)
3944 if (const auto *A = Args.getLastArg(Arg))
3945 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3946
3947 // Only add the default headers if we are compiling OpenCL sources.
3948 if ((types::isOpenCL(InputType) ||
3949 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3950 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3951 CmdArgs.push_back("-finclude-default-header");
3952 CmdArgs.push_back("-fdeclare-opencl-builtins");
3953 }
3954}
3955
3956static void RenderHLSLOptions(const Driver &D, const ArgList &Args,
3957 ArgStringList &CmdArgs, types::ID InputType) {
3958 const unsigned ForwardedArguments[] = {
3959 options::OPT_hlsl_all_resources_bound,
3960 options::OPT_dxil_validator_version,
3961 options::OPT_res_may_alias,
3962 options::OPT_D,
3963 options::OPT_I,
3964 options::OPT_O,
3965 options::OPT_emit_llvm,
3966 options::OPT_emit_obj,
3967 options::OPT_disable_llvm_passes,
3968 options::OPT_fnative_half_type,
3969 options::OPT_fnative_int16_type,
3970 options::OPT_fmatrix_memory_layout_EQ,
3971 options::OPT_hlsl_entrypoint,
3972 options::OPT_fdx_rootsignature_define,
3973 options::OPT_fdx_rootsignature_version,
3974 options::OPT_fhlsl_spv_use_unknown_image_format,
3975 options::OPT_fhlsl_spv_use_legacy_buffer_matrix_order,
3976 options::OPT_fhlsl_spv_enable_maximal_reconvergence,
3977 options::OPT_fhlsl_spv_preserve_interface};
3978 if (!types::isHLSL(InputType))
3979 return;
3980 for (const auto &Arg : ForwardedArguments)
3981 if (const auto *A = Args.getLastArg(Arg))
3982 A->renderAsInput(Args, CmdArgs);
3983 // Add the default headers if dxc_no_stdinc is not set.
3984 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3985 !Args.hasArg(options::OPT_nostdinc))
3986 CmdArgs.push_back("-finclude-default-header");
3987
3988 if (Args.hasArg(options::OPT_dxc_Zss)) {
3989 if (Args.hasArg(options::OPT_dxc_Zsb))
3990 D.Diag(diag::err_drv_dxc_invalid_shader_hash);
3991 CmdArgs.push_back("-mllvm");
3992 CmdArgs.push_back("-dx-Zss");
3993 }
3994 if (Arg *A = Args.getLastArg(options::OPT_dxc_Zsb))
3995 A->claim(); // /Zsb is the default behavior, no need to forward it to llc.
3996 if (Args.hasArg(options::OPT_dxc_source_in_debug_module)) {
3997 CmdArgs.push_back("-mllvm");
3998 CmdArgs.push_back("--dx-source-in-debug-module");
3999 }
4000 if (Args.hasArg(options::OPT_dxc_Qstrip_debug)) {
4001 CmdArgs.push_back("-mllvm");
4002 CmdArgs.push_back("--dx-strip-debug");
4003 }
4004 if (Args.hasArg(options::OPT_dxc_Qpdb_in_private)) {
4005 CmdArgs.push_back("-mllvm");
4006 CmdArgs.push_back("--dx-pdb-in-private");
4007 }
4008}
4009
4010static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
4011 ArgStringList &CmdArgs, types::ID InputType) {
4012 if (!Args.hasArg(options::OPT_fopenacc))
4013 return;
4014
4015 CmdArgs.push_back("-fopenacc");
4016}
4017
4018static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4019 const ArgList &Args, ArgStringList &CmdArgs) {
4020 // -fbuiltin is default unless -mkernel is used.
4021 bool UseBuiltins =
4022 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4023 !Args.hasArg(options::OPT_mkernel));
4024 if (!UseBuiltins)
4025 CmdArgs.push_back("-fno-builtin");
4026
4027 // -ffreestanding implies -fno-builtin.
4028 if (Args.hasArg(options::OPT_ffreestanding))
4029 UseBuiltins = false;
4030
4031 // Process the -fno-builtin-* options.
4032 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4033 A->claim();
4034
4035 // If -fno-builtin is specified, then there's no need to pass the option to
4036 // the frontend.
4037 if (UseBuiltins)
4038 A->render(Args, CmdArgs);
4039 }
4040}
4041
4043 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4044 Twine Path{Str};
4045 Path.toVector(Result);
4046 return Path.getSingleStringRef() != "";
4047 }
4048 if (llvm::sys::path::cache_directory(Result)) {
4049 llvm::sys::path::append(Result, "clang");
4050 llvm::sys::path::append(Result, "ModuleCache");
4051 return true;
4052 }
4053 return false;
4054}
4055
4058 const char *BaseInput) {
4059 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4060 return StringRef(ModuleOutputEQ->getValue());
4061
4062 SmallString<256> OutputPath;
4063 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4064 FinalOutput && Args.hasArg(options::OPT_c))
4065 OutputPath = FinalOutput->getValue();
4066 else {
4067 llvm::sys::fs::current_path(OutputPath);
4068 llvm::sys::path::append(OutputPath, llvm::sys::path::filename(BaseInput));
4069 }
4070
4071 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4072 llvm::sys::path::replace_extension(OutputPath, Extension);
4073 return OutputPath;
4074}
4075
4077 const ArgList &Args, const InputInfo &Input,
4078 const InputInfo &Output, bool HaveStd20,
4079 ArgStringList &CmdArgs) {
4080 const bool IsCXX = types::isCXX(Input.getType());
4081 const bool HaveStdCXXModules = IsCXX && HaveStd20;
4082 bool HaveModules = HaveStdCXXModules;
4083
4084 // -fmodules enables the use of precompiled modules (off by default).
4085 // Users can pass -fno-cxx-modules to turn off modules support for
4086 // C++/Objective-C++ programs.
4087 const bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4088 options::OPT_fno_cxx_modules, true);
4089 bool HaveClangModules = false;
4090 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4091 if (AllowedInCXX || !IsCXX) {
4092 CmdArgs.push_back("-fmodules");
4093 HaveClangModules = true;
4094 }
4095 }
4096
4097 HaveModules |= HaveClangModules;
4098
4099 if (HaveModules && !AllowedInCXX)
4100 CmdArgs.push_back("-fno-cxx-modules");
4101
4102 // -fmodule-maps enables implicit reading of module map files. By default,
4103 // this is enabled if we are using Clang's flavor of precompiled modules.
4104 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4105 options::OPT_fno_implicit_module_maps, HaveClangModules))
4106 CmdArgs.push_back("-fimplicit-module-maps");
4107
4108 // -fmodules-decluse checks that modules used are declared so (off by default)
4109 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4110 options::OPT_fno_modules_decluse);
4111
4112 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4113 // all #included headers are part of modules.
4114 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4115 options::OPT_fno_modules_strict_decluse, false))
4116 CmdArgs.push_back("-fmodules-strict-decluse");
4117
4118 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4119 options::OPT_fno_modulemap_allow_subdirectory_search);
4120
4121 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4122 bool ImplicitModules = false;
4123 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4124 options::OPT_fno_implicit_modules, HaveClangModules)) {
4125 if (HaveModules)
4126 CmdArgs.push_back("-fno-implicit-modules");
4127 } else if (HaveModules) {
4128 ImplicitModules = true;
4129 // -fmodule-cache-path specifies where our implicitly-built module files
4130 // should be written.
4131 SmallString<128> Path;
4132 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4133 Path = A->getValue();
4134
4135 bool HasPath = true;
4136 if (C.isForDiagnostics()) {
4137 // When generating crash reports, we want to emit the modules along with
4138 // the reproduction sources, so we ignore any provided module path.
4139 Path = Output.getFilename();
4140 llvm::sys::path::replace_extension(Path, ".cache");
4141 llvm::sys::path::append(Path, "modules");
4142 } else if (Path.empty()) {
4143 // No module path was provided: use the default.
4144 HasPath = Driver::getDefaultModuleCachePath(Path);
4145 }
4146
4147 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4148 // That being said, that failure is unlikely and not caching is harmless.
4149 if (HasPath) {
4150 const char Arg[] = "-fmodules-cache-path=";
4151 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4152 CmdArgs.push_back(Args.MakeArgString(Path));
4153 }
4154
4155 Args.AddLastArg(CmdArgs, options::OPT_fimplicit_modules_lock_timeout_EQ);
4156 }
4157
4158 if (HaveModules) {
4159 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4160 options::OPT_fno_prebuilt_implicit_modules, false))
4161 CmdArgs.push_back("-fprebuilt-implicit-modules");
4162 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4163 options::OPT_fno_modules_validate_input_files_content,
4164 false))
4165 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4166 }
4167
4168 // -fmodule-name specifies the module that is currently being built (or
4169 // used for header checking by -fmodule-maps).
4170 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4171
4172 // -fmodule-map-file can be used to specify files containing module
4173 // definitions.
4174 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4175
4176 // -fbuiltin-module-map can be used to load the clang
4177 // builtin headers modulemap file.
4178 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4179 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4180 llvm::sys::path::append(BuiltinModuleMap, "include");
4181 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4182 if (llvm::sys::fs::exists(BuiltinModuleMap))
4183 CmdArgs.push_back(
4184 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4185 }
4186
4187 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4188 // names to precompiled module files (the module is loaded only if used).
4189 // The -fmodule-file=<file> form can be used to unconditionally load
4190 // precompiled module files (whether used or not).
4191 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4192 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4193
4194 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4195 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4196 CmdArgs.push_back(Args.MakeArgString(
4197 std::string("-fprebuilt-module-path=") + A->getValue()));
4198 A->claim();
4199 }
4200 } else
4201 Args.ClaimAllArgs(options::OPT_fmodule_file);
4202
4203 // When building modules and generating crashdumps, we need to dump a module
4204 // dependency VFS alongside the output.
4205 if (HaveClangModules && C.isForDiagnostics()) {
4206 SmallString<128> VFSDir(Output.getFilename());
4207 llvm::sys::path::replace_extension(VFSDir, ".cache");
4208 // Add the cache directory as a temp so the crash diagnostics pick it up.
4209 C.addTempFile(Args.MakeArgString(VFSDir));
4210
4211 llvm::sys::path::append(VFSDir, "vfs");
4212 CmdArgs.push_back("-module-dependency-dir");
4213 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4214 }
4215
4216 if (HaveClangModules)
4217 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4218
4219 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4220 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_search_path);
4221 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4222 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4223
4224 if (HaveClangModules) {
4225 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4226
4227 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4228 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4229 D.Diag(diag::err_drv_argument_not_allowed_with)
4230 << A->getAsString(Args) << "-fbuild-session-timestamp";
4231
4232 llvm::sys::fs::file_status Status;
4233 if (llvm::sys::fs::status(A->getValue(), Status))
4234 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4235 CmdArgs.push_back(Args.MakeArgString(
4236 "-fbuild-session-timestamp=" +
4237 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4238 Status.getLastModificationTime().time_since_epoch())
4239 .count())));
4240 }
4241
4242 if (Args.getLastArg(
4243 options::OPT_fmodules_validate_once_per_build_session)) {
4244 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4245 options::OPT_fbuild_session_file))
4246 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4247
4248 Args.AddLastArg(CmdArgs,
4249 options::OPT_fmodules_validate_once_per_build_session);
4250 }
4251
4252 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4253 options::OPT_fno_modules_validate_system_headers,
4254 ImplicitModules))
4255 CmdArgs.push_back("-fmodules-validate-system-headers");
4256
4257 Args.AddLastArg(CmdArgs,
4258 options::OPT_fmodules_disable_diagnostic_validation);
4259 } else {
4260 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4261 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4262 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4263 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4264 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4265 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4266 }
4267
4268 // FIXME: We provisionally don't check ODR violations for decls in the global
4269 // module fragment.
4270 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4271
4272 if (Input.getType() == driver::types::TY_CXXModule ||
4273 Input.getType() == driver::types::TY_PP_CXXModule) {
4274 if (!Args.hasArg(options::OPT_fno_modules_reduced_bmi))
4275 CmdArgs.push_back("-fmodules-reduced-bmi");
4276
4277 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4278 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4279 else if (!(Args.hasArg(options::OPT__precompile) ||
4280 Args.hasArg(options::OPT__precompile_reduced_bmi)) ||
4281 Args.hasArg(options::OPT_fmodule_output))
4282 // If --precompile is specified, we will always generate a module file if
4283 // we're compiling an importable module unit. This is fine even if the
4284 // compilation process won't reach the point of generating the module file
4285 // (e.g., in the preprocessing mode), since the attached flag
4286 // '-fmodule-output' is useless.
4287 //
4288 // But if '--precompile' is specified, it might be annoying to always
4289 // generate the module file as '--precompile' will generate the module
4290 // file anyway.
4291 CmdArgs.push_back(Args.MakeArgString(
4292 "-fmodule-output=" +
4294 }
4295
4296 if (Args.hasArg(options::OPT_fmodules_reduced_bmi) &&
4297 Args.hasArg(options::OPT__precompile) &&
4298 (!Args.hasArg(options::OPT_o) ||
4299 Args.getLastArg(options::OPT_o)->getValue() ==
4301 D.Diag(diag::err_drv_reduced_module_output_overrided);
4302 }
4303
4304 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4305 // other translation units than module units. This is more user friendly to
4306 // allow end uers to enable this feature without asking for help from build
4307 // systems.
4308 Args.ClaimAllArgs(options::OPT_fmodules_reduced_bmi);
4309 Args.ClaimAllArgs(options::OPT_fno_modules_reduced_bmi);
4310
4311 // We need to include the case the input file is a module file here.
4312 // Since the default compilation model for C++ module interface unit will
4313 // create temporary module file and compile the temporary module file
4314 // to get the object file. Then the `-fmodule-output` flag will be
4315 // brought to the second compilation process. So we have to claim it for
4316 // the case too.
4317 if (Input.getType() == driver::types::TY_CXXModule ||
4318 Input.getType() == driver::types::TY_PP_CXXModule ||
4319 Input.getType() == driver::types::TY_ModuleFile) {
4320 Args.ClaimAllArgs(options::OPT_fmodule_output);
4321 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4322 }
4323
4324 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4325 CmdArgs.push_back("-fmodules-embed-all-files");
4326
4327 return HaveModules;
4328}
4329
4330static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4331 ArgStringList &CmdArgs) {
4332 // -fsigned-char is default.
4333 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4334 options::OPT_fno_signed_char,
4335 options::OPT_funsigned_char,
4336 options::OPT_fno_unsigned_char)) {
4337 if (A->getOption().matches(options::OPT_funsigned_char) ||
4338 A->getOption().matches(options::OPT_fno_signed_char)) {
4339 CmdArgs.push_back("-fno-signed-char");
4340 }
4341 } else if (!isSignedCharDefault(T)) {
4342 CmdArgs.push_back("-fno-signed-char");
4343 }
4344
4345 // The default depends on the language standard.
4346 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4347
4348 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4349 options::OPT_fno_short_wchar)) {
4350 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4351 CmdArgs.push_back("-fwchar-type=short");
4352 CmdArgs.push_back("-fno-signed-wchar");
4353 } else {
4354 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4355 CmdArgs.push_back("-fwchar-type=int");
4356 if (T.isOSzOS() ||
4357 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4358 CmdArgs.push_back("-fno-signed-wchar");
4359 else
4360 CmdArgs.push_back("-fsigned-wchar");
4361 }
4362 } else if (T.isOSzOS())
4363 CmdArgs.push_back("-fno-signed-wchar");
4364}
4365
4366static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4367 const llvm::Triple &T, const ArgList &Args,
4368 ObjCRuntime &Runtime, bool InferCovariantReturns,
4369 const InputInfo &Input, ArgStringList &CmdArgs) {
4370 const llvm::Triple::ArchType Arch = TC.getArch();
4371
4372 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4373 // is the default. Except for deployment target of 10.5, next runtime is
4374 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4375 if (Runtime.isNonFragile()) {
4376 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4377 options::OPT_fno_objc_legacy_dispatch,
4379 if (TC.UseObjCMixedDispatch())
4380 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4381 else
4382 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4383 }
4384 }
4385
4386 // Forward -fobjc-direct-precondition-thunk to cc1
4387 // Defaults to false and needs explict turn on for now
4388 // TODO: switch to default true and needs explict turn off in the future.
4389 // TODO: add support for other runtimes
4390 if (Args.hasFlag(options::OPT_fobjc_direct_precondition_thunk,
4391 options::OPT_fno_objc_direct_precondition_thunk, false)) {
4392 if (Runtime.isNeXTFamily()) {
4393 CmdArgs.push_back("-fobjc-direct-precondition-thunk");
4394 } else {
4395 D.Diag(diag::warn_drv_unsupported_option_for_runtime)
4396 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4397 }
4398 }
4399
4400 if (types::isObjC(Input.getType())) {
4401 // Pass down -fobjc-msgsend-selector-stubs if present.
4402 if (Args.hasFlag(options::OPT_fobjc_msgsend_selector_stubs,
4403 options::OPT_fno_objc_msgsend_selector_stubs, false))
4404 CmdArgs.push_back("-fobjc-msgsend-selector-stubs");
4405
4406 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4407 if (Args.hasFlag(options::OPT_fobjc_msgsend_class_selector_stubs,
4408 options::OPT_fno_objc_msgsend_class_selector_stubs, false))
4409 CmdArgs.push_back("-fobjc-msgsend-class-selector-stubs");
4410 }
4411
4412 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4413 // to do Array/Dictionary subscripting by default.
4414 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4415 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4416 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4417
4418 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4419 // NOTE: This logic is duplicated in ToolChains.cpp.
4420 if (isObjCAutoRefCount(Args)) {
4421 TC.CheckObjCARC();
4422
4423 CmdArgs.push_back("-fobjc-arc");
4424
4425 // FIXME: It seems like this entire block, and several around it should be
4426 // wrapped in isObjC, but for now we just use it here as this is where it
4427 // was being used previously.
4428 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4430 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4431 else
4432 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4433 }
4434
4435 // Allow the user to enable full exceptions code emission.
4436 // We default off for Objective-C, on for Objective-C++.
4437 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4438 options::OPT_fno_objc_arc_exceptions,
4439 /*Default=*/types::isCXX(Input.getType())))
4440 CmdArgs.push_back("-fobjc-arc-exceptions");
4441 }
4442
4443 // Silence warning for full exception code emission options when explicitly
4444 // set to use no ARC.
4445 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4446 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4447 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4448 }
4449
4450 // Allow the user to control whether messages can be converted to runtime
4451 // functions.
4452 if (types::isObjC(Input.getType())) {
4453 auto *Arg = Args.getLastArg(
4454 options::OPT_fobjc_convert_messages_to_runtime_calls,
4455 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4456 if (Arg &&
4457 Arg->getOption().matches(
4458 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4459 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4460 }
4461
4462 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4463 // rewriter.
4464 if (InferCovariantReturns)
4465 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4466
4467 // Pass down -fobjc-weak or -fno-objc-weak if present.
4468 if (types::isObjC(Input.getType())) {
4469 auto WeakArg =
4470 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4471 if (!WeakArg) {
4472 // nothing to do
4473 } else if (!Runtime.allowsWeak()) {
4474 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4475 D.Diag(diag::err_objc_weak_unsupported);
4476 } else {
4477 WeakArg->render(Args, CmdArgs);
4478 }
4479 }
4480
4481 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4482 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4483
4484 // Forward constant literal flags to cc1.
4485 if (types::isObjC(Input.getType())) {
4486 bool EnableConstantLiterals =
4487 Args.hasFlag(options::OPT_fobjc_constant_literals,
4488 options::OPT_fno_objc_constant_literals,
4489 /*default=*/true) &&
4490 Runtime.hasConstantLiteralClasses();
4491 if (EnableConstantLiterals)
4492 CmdArgs.push_back("-fobjc-constant-literals");
4493 if (Args.hasFlag(options::OPT_fconstant_nsnumber_literals,
4494 options::OPT_fno_constant_nsnumber_literals,
4495 /*default=*/true) &&
4496 EnableConstantLiterals)
4497 CmdArgs.push_back("-fconstant-nsnumber-literals");
4498 if (Args.hasFlag(options::OPT_fconstant_nsarray_literals,
4499 options::OPT_fno_constant_nsarray_literals,
4500 /*default=*/true) &&
4501 EnableConstantLiterals)
4502 CmdArgs.push_back("-fconstant-nsarray-literals");
4503 if (Args.hasFlag(options::OPT_fconstant_nsdictionary_literals,
4504 options::OPT_fno_constant_nsdictionary_literals,
4505 /*default=*/true) &&
4506 EnableConstantLiterals)
4507 CmdArgs.push_back("-fconstant-nsdictionary-literals");
4508 }
4509}
4510
4511static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4512 ArgStringList &CmdArgs) {
4513 bool CaretDefault = true;
4514 bool ColumnDefault = true;
4515
4516 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4517 options::OPT__SLASH_diagnostics_column,
4518 options::OPT__SLASH_diagnostics_caret)) {
4519 switch (A->getOption().getID()) {
4520 case options::OPT__SLASH_diagnostics_caret:
4521 CaretDefault = true;
4522 ColumnDefault = true;
4523 break;
4524 case options::OPT__SLASH_diagnostics_column:
4525 CaretDefault = false;
4526 ColumnDefault = true;
4527 break;
4528 case options::OPT__SLASH_diagnostics_classic:
4529 CaretDefault = false;
4530 ColumnDefault = false;
4531 break;
4532 }
4533 }
4534
4535 // -fcaret-diagnostics is default.
4536 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4537 options::OPT_fno_caret_diagnostics, CaretDefault))
4538 CmdArgs.push_back("-fno-caret-diagnostics");
4539
4540 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4541 options::OPT_fno_diagnostics_fixit_info);
4542 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4543 options::OPT_fno_diagnostics_show_option);
4544
4545 if (const Arg *A =
4546 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4547 CmdArgs.push_back("-fdiagnostics-show-category");
4548 CmdArgs.push_back(A->getValue());
4549 }
4550
4551 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4552 options::OPT_fno_diagnostics_show_hotness);
4553
4554 if (const Arg *A =
4555 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4556 std::string Opt =
4557 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4558 CmdArgs.push_back(Args.MakeArgString(Opt));
4559 }
4560
4561 if (const Arg *A =
4562 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4563 std::string Opt =
4564 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4565 CmdArgs.push_back(Args.MakeArgString(Opt));
4566 }
4567
4568 if (const Arg *A =
4569 Args.getLastArg(options::OPT_fdiagnostics_show_inlining_chain,
4570 options::OPT_fno_diagnostics_show_inlining_chain)) {
4571 if (A->getOption().matches(options::OPT_fdiagnostics_show_inlining_chain))
4572 CmdArgs.push_back("-fdiagnostics-show-inlining-chain");
4573 else
4574 CmdArgs.push_back("-fno-diagnostics-show-inlining-chain");
4575 }
4576
4577 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4578 CmdArgs.push_back("-fdiagnostics-format");
4579 CmdArgs.push_back(A->getValue());
4580 if (StringRef(A->getValue()) == "sarif" ||
4581 StringRef(A->getValue()) == "SARIF")
4582 D.Diag(diag::warn_drv_sarif_format_unstable);
4583 }
4584
4585 if (const Arg *A = Args.getLastArg(
4586 options::OPT_fdiagnostics_show_note_include_stack,
4587 options::OPT_fno_diagnostics_show_note_include_stack)) {
4588 const Option &O = A->getOption();
4589 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4590 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4591 else
4592 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4593 }
4594
4595 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4596
4597 if (Args.hasArg(options::OPT_fansi_escape_codes))
4598 CmdArgs.push_back("-fansi-escape-codes");
4599
4600 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4601 options::OPT_fno_show_source_location);
4602
4603 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4604 options::OPT_fno_diagnostics_show_line_numbers);
4605
4606 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4607 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4608
4609 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4610 ColumnDefault))
4611 CmdArgs.push_back("-fno-show-column");
4612
4613 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4614 options::OPT_fno_spell_checking);
4615
4616 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4617}
4618
4619static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4620 const ArgList &Args, ArgStringList &CmdArgs,
4621 unsigned DwarfVersion) {
4622 auto *DwarfFormatArg =
4623 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4624 if (!DwarfFormatArg)
4625 return;
4626
4627 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4628 if (DwarfVersion < 3)
4629 D.Diag(diag::err_drv_argument_only_allowed_with)
4630 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4631 else if (!T.isArch64Bit())
4632 D.Diag(diag::err_drv_argument_only_allowed_with)
4633 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4634 else if (!T.isOSBinFormatELF())
4635 D.Diag(diag::err_drv_argument_only_allowed_with)
4636 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4637 }
4638
4639 DwarfFormatArg->render(Args, CmdArgs);
4640}
4641
4642static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4643 const ArgList &Args) {
4644 bool NeedsSimpleTemplateNames =
4645 Args.hasFlag(options::OPT_gsimple_template_names,
4646 options::OPT_gno_simple_template_names,
4648 if (!NeedsSimpleTemplateNames)
4649 return false;
4650
4651 if (const Arg *A = Args.getLastArg(options::OPT_gsimple_template_names))
4652 if (!checkDebugInfoOption(A, Args, D, TC))
4653 return false;
4654
4655 return true;
4656}
4657
4658static void
4659renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4660 const ArgList &Args, types::ID InputType,
4661 ArgStringList &CmdArgs, const InputInfo &Output,
4662 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4663 DwarfFissionKind &DwarfFission, bool IsUsingLTO) {
4664 bool IRInput = isLLVMIR(InputType);
4665 bool PlainCOrCXX = isDerivedFromC(InputType) && !isCuda(InputType) &&
4666 !isHIP(InputType) && !isObjC(InputType) &&
4667 !isOpenCL(InputType);
4668
4669 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
4670
4671 if (!Args.hasFlag(options::OPT_fdebug_record_sysroot,
4672 options::OPT_fno_debug_record_sysroot, true))
4673 CmdArgs.push_back("-fno-debug-record-sysroot");
4674
4675 // The 'g' groups options involve a somewhat intricate sequence of decisions
4676 // about what to pass from the driver to the frontend, but by the time they
4677 // reach cc1 they've been factored into three well-defined orthogonal choices:
4678 // * what level of debug info to generate
4679 // * what dwarf version to write
4680 // * what debugger tuning to use
4681 // This avoids having to monkey around further in cc1 other than to disable
4682 // codeview if not running in a Windows environment. Perhaps even that
4683 // decision should be made in the driver as well though.
4684 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4685
4686 bool SplitDWARFInlining =
4687 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4688 options::OPT_fno_split_dwarf_inlining, false);
4689
4690 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4691 // object file generation and no IR generation, -gN should not be needed. So
4692 // allow -gsplit-dwarf with either -gN or IR input.
4693 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4694 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4695 if (TC.getTriple().isOSAIX() && Args.hasArg(options::OPT_gsplit_dwarf)) {
4696 D.Diag(diag::err_drv_unsupported_opt_for_target)
4697 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
4698 << TC.getTripleString();
4699 return;
4700 }
4701 Arg *SplitDWARFArg;
4702 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4703 if (DwarfFission != DwarfFissionKind::None &&
4704 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4705 DwarfFission = DwarfFissionKind::None;
4706 SplitDWARFInlining = false;
4707 }
4708 }
4709 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4710 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4711
4712 // If the last option explicitly specified a debug-info level, use it.
4713 if (checkDebugInfoOption(A, Args, D, TC) &&
4714 A->getOption().matches(options::OPT_gN_Group)) {
4715 DebugInfoKind = debugLevelToInfoKind(*A);
4716 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4717 // complicated if you've disabled inline info in the skeleton CUs
4718 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4719 // line-tables-only, so let those compose naturally in that case.
4720 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4721 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4722 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4723 SplitDWARFInlining))
4724 DwarfFission = DwarfFissionKind::None;
4725 }
4726 }
4727
4728 // If a debugger tuning argument appeared, remember it.
4729 bool HasDebuggerTuning = false;
4730 if (const Arg *A =
4731 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4732 HasDebuggerTuning = true;
4733 if (checkDebugInfoOption(A, Args, D, TC)) {
4734 if (A->getOption().matches(options::OPT_glldb))
4735 DebuggerTuning = llvm::DebuggerKind::LLDB;
4736 else if (A->getOption().matches(options::OPT_gsce))
4737 DebuggerTuning = llvm::DebuggerKind::SCE;
4738 else if (A->getOption().matches(options::OPT_gdbx))
4739 DebuggerTuning = llvm::DebuggerKind::DBX;
4740 else
4741 DebuggerTuning = llvm::DebuggerKind::GDB;
4742 }
4743 }
4744
4745 // If a -gdwarf argument appeared, remember it.
4746 bool EmitDwarf = false;
4747 if (const Arg *A = getDwarfNArg(Args))
4748 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4749
4750 bool EmitCodeView = false;
4751 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4752 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4753
4754 // If the user asked for debug info but did not explicitly specify -gcodeview
4755 // or -gdwarf, ask the toolchain for the default format.
4756 if (!EmitCodeView && !EmitDwarf &&
4757 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4758 switch (TC.getDefaultDebugFormat()) {
4759 case llvm::codegenoptions::DIF_CodeView:
4760 EmitCodeView = true;
4761 break;
4762 case llvm::codegenoptions::DIF_DWARF:
4763 EmitDwarf = true;
4764 break;
4765 }
4766 }
4767
4768 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4769 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4770 // be lower than what the user wanted.
4771 if (EmitDwarf) {
4772 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4773 // Clamp effective DWARF version to the max supported by the toolchain.
4774 EffectiveDWARFVersion =
4775 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4776 } else {
4777 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4778 }
4779
4780 // -gline-directives-only supported only for the DWARF debug info.
4781 if (RequestedDWARFVersion == 0 &&
4782 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4783 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4784
4785 // strict DWARF is set to false by default. But for DBX, we need it to be set
4786 // as true by default.
4787 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4788 (void)checkDebugInfoOption(A, Args, D, TC);
4789 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4790 DebuggerTuning == llvm::DebuggerKind::DBX))
4791 CmdArgs.push_back("-gstrict-dwarf");
4792
4793 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4794 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4795
4796 // Column info is included by default for everything except SCE and
4797 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4798 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4799 // practice, however, the Microsoft debuggers don't handle missing end columns
4800 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4801 // it's better not to include any column info.
4802 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4803 (void)checkDebugInfoOption(A, Args, D, TC);
4804 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4805 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4806 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4807 DebuggerTuning != llvm::DebuggerKind::DBX)))
4808 CmdArgs.push_back("-gno-column-info");
4809
4810 if (!Args.hasFlag(options::OPT_gcall_site_info,
4811 options::OPT_gno_call_site_info, true))
4812 CmdArgs.push_back("-gno-call-site-info");
4813
4814 // FIXME: Move backend command line options to the module.
4815 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4816 // If -gline-tables-only or -gline-directives-only is the last option it
4817 // wins.
4818 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4819 TC)) {
4820 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4821 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4822 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4823 CmdArgs.push_back("-dwarf-ext-refs");
4824 CmdArgs.push_back("-fmodule-format=obj");
4825 }
4826 }
4827 }
4828
4829 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4830 CmdArgs.push_back("-fsplit-dwarf-inlining");
4831
4832 // After we've dealt with all combinations of things that could
4833 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4834 // figure out if we need to "upgrade" it to standalone debug info.
4835 // We parse these two '-f' options whether or not they will be used,
4836 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4837 bool NeedFullDebug = Args.hasFlag(
4838 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4839 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4841 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4842 (void)checkDebugInfoOption(A, Args, D, TC);
4843
4844 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4845 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4846 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4847 options::OPT_feliminate_unused_debug_types, false))
4848 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4849 else if (NeedFullDebug)
4850 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4851 }
4852
4853 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4854 false)) {
4855 // Source embedding is a vendor extension to DWARF v5. By now we have
4856 // checked if a DWARF version was stated explicitly, and have otherwise
4857 // fallen back to the target default, so if this is still not at least 5
4858 // we emit an error.
4859 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4860 if (RequestedDWARFVersion < 5)
4861 D.Diag(diag::err_drv_argument_only_allowed_with)
4862 << A->getAsString(Args) << "-gdwarf-5";
4863 else if (EffectiveDWARFVersion < 5)
4864 // The toolchain has reduced allowed dwarf version, so we can't enable
4865 // -gembed-source.
4866 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4867 << A->getAsString(Args) << TC.getTripleString() << 5
4868 << EffectiveDWARFVersion;
4869 else if (checkDebugInfoOption(A, Args, D, TC))
4870 CmdArgs.push_back("-gembed-source");
4871 }
4872
4873 // Enable Key Instructions by default if we're emitting DWARF, the language is
4874 // plain C or C++, and optimisations are enabled.
4875 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
4876 bool KeyInstructionsOnByDefault =
4877 EmitDwarf && PlainCOrCXX && OptLevel &&
4878 !OptLevel->getOption().matches(options::OPT_O0);
4879 if (Args.hasFlag(options::OPT_gkey_instructions,
4880 options::OPT_gno_key_instructions,
4881 KeyInstructionsOnByDefault))
4882 CmdArgs.push_back("-gkey-instructions");
4883
4884 if (!Args.hasFlag(options::OPT_gstructor_decl_linkage_names,
4885 options::OPT_gno_structor_decl_linkage_names, true))
4886 CmdArgs.push_back("-gno-structor-decl-linkage-names");
4887
4888 if (Args.hasFlag(options::OPT_fdynamic_debugging,
4889 options::OPT_fno_dynamic_debugging, false)) {
4890 // As this is an experimental feature we can afford to be strict about
4891 // supported configurations.
4892 // NOTE on adding target support, consider adding "tail-pad-to-size"
4893 // support in `llvm::prepareForDynamicDebugging`.
4894 if (!TC.getTriple().isX86())
4895 D.Diag(diag::err_drv_unsupported_opt_for_target)
4896 << Args.getLastArg(options::OPT_fdynamic_debugging)->getAsString(Args)
4897 << T.getTriple();
4898 if (IsUsingLTO)
4899 D.Diag(diag::err_drv_dyndbg_lto);
4900 if (DwarfFission != DwarfFissionKind::None)
4901 D.Diag(diag::err_drv_dyndbg_incompatible)
4902 << Args.getLastArg(options::OPT_gsplit_dwarf)->getAsString(Args);
4903 // There's no fundamental reason why IR input should be incompatible, but
4904 // it would add some complexity, and reducing the test matrix is valuable.
4905 if (IRInput)
4906 D.Diag(diag::err_drv_dyndbg_ir);
4907
4908 // Disable composition with sanitizers for now.
4909 if (auto *San = Args.getLastArg(options::OPT_fsanitize_EQ))
4910 D.Diag(diag::err_drv_dyndbg_incompatible) << San->getAsString(Args);
4911
4912 if (!EmitDwarf)
4913 D.Diag(diag::warn_drv_dyndbg_req_debug);
4914 else
4915 CmdArgs.push_back("-fdynamic-debugging");
4916 }
4917
4918 if (EmitCodeView) {
4919 CmdArgs.push_back("-gcodeview");
4920
4921 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4922 options::OPT_gno_codeview_ghash);
4923
4924 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4925 options::OPT_gno_codeview_command_line);
4926 }
4927
4928 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4929 options::OPT_gno_inline_line_tables);
4930
4931 // When emitting remarks, we need at least debug lines in the output.
4932 if (willEmitRemarks(Args) &&
4933 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4934 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4935
4936 // Adjust the debug info kind for the given toolchain.
4937 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4938
4939 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4940 // set.
4941 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4942 T.isOSAIX() && !HasDebuggerTuning
4943 ? llvm::DebuggerKind::Default
4944 : DebuggerTuning);
4945
4946 // -fdebug-macro turns on macro debug info generation.
4947 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4948 false))
4949 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4950 D, TC))
4951 CmdArgs.push_back("-debug-info-macro");
4952
4953 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4954 const auto *PubnamesArg =
4955 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4956 options::OPT_gpubnames, options::OPT_gno_pubnames);
4957 if (DwarfFission != DwarfFissionKind::None ||
4958 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4959 const bool OptionSet =
4960 (PubnamesArg &&
4961 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4962 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4963 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4964 (!PubnamesArg ||
4965 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4966 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4967 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4968 options::OPT_gpubnames)
4969 ? "-gpubnames"
4970 : "-ggnu-pubnames");
4971 }
4972
4973 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4974 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4975 ForwardTemplateParams = true;
4976 CmdArgs.push_back("-gsimple-template-names=simple");
4977 }
4978
4979 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4980 bool UseDebugTemplateAlias =
4981 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4982 if (const auto *DebugTemplateAlias = Args.getLastArg(
4983 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4984 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4985 // asks for it we should let them have it (if the target supports it).
4986 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4987 const auto &Opt = DebugTemplateAlias->getOption();
4988 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4989 }
4990 }
4991 if (UseDebugTemplateAlias)
4992 CmdArgs.push_back("-gtemplate-alias");
4993
4994 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4995 StringRef v = A->getValue();
4996 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4997 }
4998
4999 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
5000 options::OPT_fno_debug_ranges_base_address);
5001
5002 // -gdwarf-aranges turns on the emission of the aranges section in the
5003 // backend.
5004 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
5005 A && checkDebugInfoOption(A, Args, D, TC)) {
5006 CmdArgs.push_back("-mllvm");
5007 CmdArgs.push_back("-generate-arange-section");
5008 }
5009
5010 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
5011 options::OPT_fno_force_dwarf_frame);
5012
5013 bool EnableTypeUnits = false;
5014 if (Args.hasFlag(options::OPT_fdebug_types_section,
5015 options::OPT_fno_debug_types_section, false)) {
5016 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
5017 D.Diag(diag::err_drv_unsupported_opt_for_target)
5018 << Args.getLastArg(options::OPT_fdebug_types_section)
5019 ->getAsString(Args)
5020 << T.getTriple();
5021 } else if (checkDebugInfoOption(
5022 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
5023 TC)) {
5024 EnableTypeUnits = true;
5025 CmdArgs.push_back("-mllvm");
5026 CmdArgs.push_back("-generate-type-units");
5027 }
5028 }
5029
5030 if (const Arg *A =
5031 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
5032 options::OPT_gno_omit_unreferenced_methods))
5033 (void)checkDebugInfoOption(A, Args, D, TC);
5034 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
5035 options::OPT_gno_omit_unreferenced_methods, false) &&
5036 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
5037 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
5038 !EnableTypeUnits) {
5039 CmdArgs.push_back("-gomit-unreferenced-methods");
5040 }
5041
5042 // To avoid join/split of directory+filename, the integrated assembler prefers
5043 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
5044 // form before DWARF v5.
5045 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
5046 options::OPT_fno_dwarf_directory_asm,
5047 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
5048 CmdArgs.push_back("-fno-dwarf-directory-asm");
5049
5050 // Decide how to render forward declarations of template instantiations.
5051 // SCE wants full descriptions, others just get them in the name.
5052 if (ForwardTemplateParams)
5053 CmdArgs.push_back("-debug-forward-template-params");
5054
5055 // Do we need to explicitly import anonymous namespaces into the parent
5056 // scope?
5057 if (DebuggerTuning == llvm::DebuggerKind::SCE)
5058 CmdArgs.push_back("-dwarf-explicit-import");
5059
5060 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
5061 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
5062
5063 // This controls whether or not we perform JustMyCode instrumentation.
5064 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
5065 if (TC.getTriple().isOSBinFormatELF() ||
5066 TC.getTriple().isWindowsMSVCEnvironment()) {
5067 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
5068 CmdArgs.push_back("-fjmc");
5069 else if (D.IsCLMode())
5070 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
5071 << "'/Zi', '/Z7'";
5072 else
5073 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
5074 << "-g";
5075 } else {
5076 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
5077 }
5078 }
5079
5080 // Add in -fdebug-compilation-dir if necessary.
5081 const char *DebugCompilationDir =
5082 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5083
5084 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
5085
5086 // Add the output path to the object file for CodeView debug infos.
5087 if (EmitCodeView && Output.isFilename())
5088 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
5089 Output.getFilename());
5090}
5091
5092static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
5093 ArgStringList &CmdArgs) {
5094 unsigned RTOptionID = options::OPT__SLASH_MT;
5095
5096 if (Args.hasArg(options::OPT__SLASH_LDd))
5097 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5098 // but defining _DEBUG is sticky.
5099 RTOptionID = options::OPT__SLASH_MTd;
5100
5101 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5102 RTOptionID = A->getOption().getID();
5103
5104 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5105 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
5106 .Case("static", options::OPT__SLASH_MT)
5107 .Case("static_dbg", options::OPT__SLASH_MTd)
5108 .Case("dll", options::OPT__SLASH_MD)
5109 .Case("dll_dbg", options::OPT__SLASH_MDd)
5110 .Default(options::OPT__SLASH_MT);
5111 }
5112
5113 StringRef FlagForCRT;
5114 switch (RTOptionID) {
5115 case options::OPT__SLASH_MD:
5116 if (Args.hasArg(options::OPT__SLASH_LDd))
5117 CmdArgs.push_back("-D_DEBUG");
5118 CmdArgs.push_back("-D_MT");
5119 CmdArgs.push_back("-D_DLL");
5120 FlagForCRT = "--dependent-lib=msvcrt";
5121 break;
5122 case options::OPT__SLASH_MDd:
5123 CmdArgs.push_back("-D_DEBUG");
5124 CmdArgs.push_back("-D_MT");
5125 CmdArgs.push_back("-D_DLL");
5126 FlagForCRT = "--dependent-lib=msvcrtd";
5127 break;
5128 case options::OPT__SLASH_MT:
5129 if (Args.hasArg(options::OPT__SLASH_LDd))
5130 CmdArgs.push_back("-D_DEBUG");
5131 CmdArgs.push_back("-D_MT");
5132 CmdArgs.push_back("-flto-visibility-public-std");
5133 FlagForCRT = "--dependent-lib=libcmt";
5134 break;
5135 case options::OPT__SLASH_MTd:
5136 CmdArgs.push_back("-D_DEBUG");
5137 CmdArgs.push_back("-D_MT");
5138 CmdArgs.push_back("-flto-visibility-public-std");
5139 FlagForCRT = "--dependent-lib=libcmtd";
5140 break;
5141 default:
5142 llvm_unreachable("Unexpected option ID.");
5143 }
5144
5145 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5146 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5147 } else {
5148 CmdArgs.push_back(FlagForCRT.data());
5149
5150 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5151 // users want. The /Za flag to cl.exe turns this off, but it's not
5152 // implemented in clang.
5153 CmdArgs.push_back("--dependent-lib=oldnames");
5154 }
5155
5156 // SYCL: Add SYCL runtime library dependency
5157 // SYCL runtime is a required dependency similar to CRT, so we use
5158 // --dependent-lib to embed it in the object file metadata
5159 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false) &&
5160 !Args.hasArg(options::OPT_nolibsycl) &&
5161 !Args.hasArg(options::OPT_fms_omit_default_lib)) {
5162
5163 // Determine debug vs release based on CRT flags
5164 bool IsDebugBuild = false;
5165
5166 // Check -fms-runtime-lib=dll_dbg
5167 if (const Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
5168 StringRef RuntimeVal = A->getValue();
5169 if (RuntimeVal == "dll_dbg")
5170 IsDebugBuild = true;
5171 }
5172
5173 // Check for /MDd flag (dynamic debug CRT), use getLastArg to handle
5174 // overriding options (e.g., /MDd /MD -> /MD wins)
5175 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) {
5176 if (A->getOption().matches(options::OPT__SLASH_MDd))
5177 IsDebugBuild = true;
5178 }
5179
5180 // Add appropriate SYCL runtime library dependency
5181 CmdArgs.push_back(IsDebugBuild ? "--dependent-lib=LLVMSYCLd"
5182 : "--dependent-lib=LLVMSYCL");
5183 }
5184
5185 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5186 // even if the file doesn't actually refer to any of the routines because
5187 // the CRT itself has incomplete dependency markings.
5188 if (TC.getTriple().isWindowsArm64EC())
5189 CmdArgs.push_back("--dependent-lib=softintrin");
5190}
5191
5193 const InputInfo &Output, const InputInfoList &Inputs,
5194 const ArgList &Args, const char *LinkingOutput) const {
5195 const auto &TC = getToolChain();
5196 const llvm::Triple &RawTriple = TC.getTriple();
5197 const llvm::Triple &Triple = TC.getEffectiveTriple();
5198 const std::string &TripleStr = Triple.getTriple();
5199
5200 bool KernelOrKext =
5201 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5202 const Driver &D = TC.getDriver();
5203 ArgStringList CmdArgs;
5204
5205 assert(Inputs.size() >= 1 && "Must have at least one input.");
5206 // CUDA/HIP compilation may have multiple inputs (source file + results of
5207 // device-side compilations). OpenMP device jobs also take the host IR as a
5208 // second input. Module precompilation accepts a list of header files to
5209 // include as part of the module. API extraction accepts a list of header
5210 // files whose API information is emitted in the output. All other jobs are
5211 // expected to have exactly one input. SYCL compilation only expects a
5212 // single input.
5213 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5214 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5215 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5216 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5217 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5218 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5219 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5220 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5221 bool UsesLLVMOffloading = Args.hasFlag(
5222 options::OPT_foffload_via_llvm, options::OPT_fno_offload_via_llvm, false);
5223 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5225 bool IsHostOffloadingAction =
5228 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5229 Args.hasFlag(options::OPT_offload_new_driver,
5230 options::OPT_no_offload_new_driver,
5231 C.getActiveOffloadKinds() != Action::OFK_None));
5232
5233 // SYCL defaults to RDC; CUDA/HIP default to non-RDC.
5234 bool IsRDCMode = Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
5235 /*Default=*/IsSYCL);
5236
5237 auto LTOMode = TC.getLTOMode(Args, JA.getOffloadingDeviceKind());
5238 bool IsUsingLTO = LTOMode != LTOK_None;
5239
5240 // Extract API doesn't have a main input file, so invent a fake one as a
5241 // placeholder.
5242 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5243 "extract-api");
5244
5245 const InputInfo &Input =
5246 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5247
5248 InputInfoList ExtractAPIInputs;
5249 InputInfoList HostOffloadingInputs;
5250 const InputInfo *CudaDeviceInput = nullptr;
5251 const InputInfo *OpenMPDeviceInput = nullptr;
5252 for (const InputInfo &I : Inputs) {
5253 if (&I == &Input || I.getType() == types::TY_Nothing) {
5254 // This is the primary input or contains nothing.
5255 } else if (IsExtractAPI) {
5256 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5257 if (I.getType() != ExpectedInputType) {
5258 D.Diag(diag::err_drv_extract_api_wrong_kind)
5259 << I.getFilename() << types::getTypeName(I.getType())
5260 << types::getTypeName(ExpectedInputType);
5261 }
5262 ExtractAPIInputs.push_back(I);
5263 } else if (IsHostOffloadingAction) {
5264 HostOffloadingInputs.push_back(I);
5265 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5266 CudaDeviceInput = &I;
5267 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5268 OpenMPDeviceInput = &I;
5269 } else {
5270 llvm_unreachable("unexpectedly given multiple inputs");
5271 }
5272 }
5273
5274 bool IsUEFI = RawTriple.isUEFI();
5275 bool IsIAMCU = RawTriple.isOSIAMCU();
5276
5277 // C++ is not supported for IAMCU.
5278 if (IsIAMCU && types::isCXX(Input.getType()))
5279 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5280
5281 // Invoke ourselves in -cc1 mode.
5282 //
5283 // FIXME: Implement custom jobs for internal actions.
5284 CmdArgs.push_back("-cc1");
5285
5286 // Add the "effective" target triple.
5287 CmdArgs.push_back("-triple");
5288 CmdArgs.push_back(Args.MakeArgStringRef(TripleStr));
5289
5290 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5291
5292 const llvm::Triple *AuxTriple = TC.getAuxTriple();
5293 if (AuxTriple) {
5294 CmdArgs.push_back("-aux-triple");
5295 CmdArgs.push_back(Args.MakeArgStringRef(AuxTriple->str()));
5296
5297 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling
5298 // in device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5299 // Windows), we need to pass Windows-specific flags to cc1.
5300 IsWindowsMSVC |= AuxTriple->isWindowsMSVCEnvironment();
5302 // Figure out the device side triple for the host-side compilation.
5303 for (unsigned I = Action::OFK_DeviceFirst; I <= Action::OFK_DeviceLast;
5304 ++I) {
5306 C.getOffloadToolChains(static_cast<Action::OffloadKind>(I));
5307 if (OffloadToolChains.first == OffloadToolChains.second)
5308 continue;
5309
5310 const llvm::Triple &DeviceAuxTriple =
5311 OffloadToolChains.first->second->getTriple();
5312 CmdArgs.push_back("-aux-triple");
5313 CmdArgs.push_back(Args.MakeArgStringRef(DeviceAuxTriple.str()));
5314 break;
5315 }
5316 }
5317
5318 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5319 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5320 Args.ClaimAllArgs(options::OPT_MJ);
5321 } else if (const Arg *GenCDBFragment =
5322 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5323 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5324 TripleStr, Output, Input, Args);
5325 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5326 }
5327
5328 if ((getToolChain().getTriple().isAMDGPU() ||
5329 (getToolChain().getTriple().isSPIRV() &&
5330 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5331 // Device side compilation printf
5332 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5333 CmdArgs.push_back(Args.MakeArgString(
5334 "-mprintf-kind=" +
5335 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5336 // Force compiler error on invalid conversion specifiers
5337 CmdArgs.push_back(
5338 Args.MakeArgStringRef("-Werror=format-invalid-specifier"));
5339 }
5340 }
5341
5342 if (IsCuda && !IsCudaDevice && !UsesLLVMOffloading) {
5343 // We need to figure out which CUDA version we're compiling for, as that
5344 // determines how we load and launch GPU kernels.
5345 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5346 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5347 assert(CTC && "Expected valid CUDA Toolchain.");
5348 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5349 CmdArgs.push_back(Args.MakeArgString(
5350 Twine("-target-sdk-version=") +
5351 CudaVersionToString(CTC->CudaInstallation.version())));
5352 }
5353
5354 // Optimization level for CodeGen.
5355 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5356 if (A->getOption().matches(options::OPT_O4)) {
5357 CmdArgs.push_back("-O3");
5358 D.Diag(diag::warn_O4_is_O3);
5359 } else {
5360 A->render(Args, CmdArgs);
5361 }
5362 }
5363
5364 // Unconditionally claim the printf option now to avoid unused diagnostic.
5365 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5366 PF->claim();
5367
5368 if (IsSYCL) {
5369 if (IsSYCLDevice) {
5370 // We want to compile sycl kernels.
5371 CmdArgs.push_back("-fsycl-is-device");
5372
5373 // Set O2 optimization level by default
5374 if (!Args.getLastArg(options::OPT_O_Group))
5375 CmdArgs.push_back("-O2");
5376 } else {
5377 // Add any options that are needed specific to SYCL offload while
5378 // performing the host side compilation.
5379
5380 // Let the front-end host compilation flow know about SYCL offload
5381 // compilation.
5382 CmdArgs.push_back("-fsycl-is-host");
5383 }
5384
5385 // Set options for both host and device.
5386 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5387 if (SYCLStdArg) {
5388 SYCLStdArg->render(Args, CmdArgs);
5389 } else {
5390 // Ensure the default version in SYCL mode is 2020.
5391 CmdArgs.push_back("-sycl-std=2020");
5392 }
5393 }
5394
5395 if (Args.hasFlag(options::OPT_fclangir, options::OPT_fno_clangir, false))
5396 CmdArgs.push_back("-fclangir");
5397
5398 if (IsOpenMPDevice) {
5399 // We have to pass the triple of the host if compiling for an OpenMP device.
5400 const llvm::Triple &HostTriple =
5401 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
5402 CmdArgs.push_back("-aux-triple");
5403 CmdArgs.push_back(HostTriple.str().c_str());
5404 }
5405
5406 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5407 Triple.getArch() == llvm::Triple::thumb)) {
5408 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5409 unsigned Version = 0;
5410 bool Failure =
5411 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5412 if (Failure || Version < 7)
5413 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5414 << TripleStr;
5415 }
5416
5417 // Push all default warning arguments that are specific to
5418 // the given target. These come before user provided warning options
5419 // are provided.
5420 TC.addClangWarningOptions(CmdArgs);
5421
5422 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5423 if (Triple.isSPIR() || Triple.isSPIRV())
5424 CmdArgs.push_back("-Wspir-compat");
5425
5426 // Select the appropriate action.
5427 RewriteKind rewriteKind = RK_None;
5428
5429 bool UnifiedLTO = false;
5430 if (IsUsingLTO) {
5431 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5432 options::OPT_fno_unified_lto, Triple.isPS());
5433 if (UnifiedLTO)
5434 CmdArgs.push_back("-funified-lto");
5435 }
5436
5437 if (Args.hasArg(options::OPT_fdefined_pointer_subtraction))
5438 CmdArgs.push_back("-fdefined-pointer-subtraction");
5439
5440 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5441 // it claims when not running an assembler. Otherwise, clang would emit
5442 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5443 // flags while debugging something. That'd be somewhat inconvenient, and it's
5444 // also inconsistent with most other flags -- we don't warn on
5445 // -ffunction-sections not being used in -E mode either for example, even
5446 // though it's not really used either.
5447 if (!isa<AssembleJobAction>(JA)) {
5448 // The args claimed here should match the args used in
5449 // CollectArgsForIntegratedAssembler().
5450 if (TC.useIntegratedAs()) {
5451 Args.ClaimAllArgs(options::OPT_mrelax_all);
5452 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5453 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5454 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5455 switch (C.getDefaultToolChain().getArch()) {
5456 case llvm::Triple::arm:
5457 case llvm::Triple::armeb:
5458 case llvm::Triple::thumb:
5459 case llvm::Triple::thumbeb:
5460 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5461 break;
5462 default:
5463 break;
5464 }
5465 }
5466 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5467 Args.ClaimAllArgs(options::OPT_Xassembler);
5468 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5469 }
5470
5471 bool IsAMDSPIRVForHIPDevice =
5472 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5473 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5474
5475 if (isa<AnalyzeJobAction>(JA)) {
5476 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5477 CmdArgs.push_back("-analyze");
5478 } else if (isa<PreprocessJobAction>(JA)) {
5479 if (Output.getType() == types::TY_Dependencies)
5480 CmdArgs.push_back("-Eonly");
5481 else {
5482 CmdArgs.push_back("-E");
5483 if (Args.hasArg(options::OPT_rewrite_objc) &&
5484 !Args.hasArg(options::OPT_g_Group))
5485 CmdArgs.push_back("-P");
5486 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5487 CmdArgs.push_back("-fdirectives-only");
5488 }
5489 } else if (isa<AssembleJobAction>(JA)) {
5490 CmdArgs.push_back("-emit-obj");
5491
5492 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5493
5494 // Also ignore explicit -force_cpusubtype_ALL option.
5495 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5496 } else if (isa<PrecompileJobAction>(JA)) {
5497 if (JA.getType() == types::TY_Nothing)
5498 CmdArgs.push_back("-fsyntax-only");
5499 else if (JA.getType() == types::TY_ModuleFile) {
5500 if (Args.hasArg(options::OPT__precompile_reduced_bmi) ||
5501 ((Input.getType() == types::TY_CXXStdModule ||
5502 Input.getType() == types::TY_PP_CXXStdModule) &&
5503 !Args.hasArg(options::OPT_fno_modules_reduced_bmi)))
5504 CmdArgs.push_back("-emit-reduced-module-interface");
5505 else
5506 CmdArgs.push_back("-emit-module-interface");
5507 } else if (JA.getType() == types::TY_HeaderUnit)
5508 CmdArgs.push_back("-emit-header-unit");
5509 else if (!Args.hasArg(options::OPT_ignore_pch))
5510 CmdArgs.push_back("-emit-pch");
5511 } else if (isa<VerifyPCHJobAction>(JA)) {
5512 CmdArgs.push_back("-verify-pch");
5513 } else if (isa<ExtractAPIJobAction>(JA)) {
5514 assert(JA.getType() == types::TY_API_INFO &&
5515 "Extract API actions must generate a API information.");
5516 CmdArgs.push_back("-extract-api");
5517
5518 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5519 PrettySGFArg->render(Args, CmdArgs);
5520
5521 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5522
5523 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5524 ProductNameArg->render(Args, CmdArgs);
5525 if (Arg *ExtractAPIIgnoresFileArg =
5526 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5527 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5528 if (Arg *EmitExtensionSymbolGraphs =
5529 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5530 if (!SymbolGraphDirArg)
5531 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5532
5533 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5534 }
5535 if (SymbolGraphDirArg)
5536 SymbolGraphDirArg->render(Args, CmdArgs);
5537 } else {
5538 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5539 "Invalid action for clang tool.");
5540 if (JA.getType() == types::TY_Nothing) {
5541 CmdArgs.push_back("-fsyntax-only");
5542 } else if (JA.getType() == types::TY_LLVM_IR ||
5543 JA.getType() == types::TY_LTO_IR) {
5544 CmdArgs.push_back("-emit-llvm");
5545 } else if (JA.getType() == types::TY_LLVM_BC ||
5546 JA.getType() == types::TY_LTO_BC) {
5547 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5548 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5549 Args.hasArg(options::OPT_emit_llvm)) {
5550 CmdArgs.push_back("-emit-llvm");
5551 } else {
5552 CmdArgs.push_back("-emit-llvm-bc");
5553 }
5554 } else if (JA.getType() == types::TY_IFS ||
5555 JA.getType() == types::TY_IFS_CPP) {
5556 StringRef ArgStr =
5557 Args.hasArg(options::OPT_interface_stub_version_EQ)
5558 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5559 : "ifs-v1";
5560 CmdArgs.push_back("-emit-interface-stubs");
5561 CmdArgs.push_back(
5562 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr));
5563 } else if (JA.getType() == types::TY_PP_Asm) {
5564 CmdArgs.push_back("-S");
5565 } else if (JA.getType() == types::TY_AST) {
5566 if (!Args.hasArg(options::OPT_ignore_pch))
5567 CmdArgs.push_back("-emit-pch");
5568 } else if (JA.getType() == types::TY_ModuleFile) {
5569 CmdArgs.push_back("-module-file-info");
5570 } else if (JA.getType() == types::TY_RewrittenObjC) {
5571 CmdArgs.push_back("-rewrite-objc");
5572 rewriteKind = RK_NonFragile;
5573 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5574 CmdArgs.push_back("-rewrite-objc");
5575 rewriteKind = RK_Fragile;
5576 } else if (JA.getType() == types::TY_CIR) {
5577 CmdArgs.push_back("-emit-cir");
5578 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5579 CmdArgs.push_back("-emit-obj");
5580 } else {
5581 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5582 }
5583
5584 // Preserve use-list order by default when emitting bitcode, so that
5585 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5586 // same result as running passes here. For LTO, we don't need to preserve
5587 // the use-list order, since serialization to bitcode is part of the flow.
5588 if (JA.getType() == types::TY_LLVM_BC)
5589 CmdArgs.push_back("-emit-llvm-uselists");
5590
5591 if (IsUsingLTO) {
5592 const Arg *LTOArg = Args.getLastArg(options::OPT_foffload_lto,
5593 options::OPT_foffload_lto_EQ);
5594 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5595 !Args.hasFlag(options::OPT_offload_new_driver,
5596 options::OPT_no_offload_new_driver,
5597 C.getActiveOffloadKinds() != Action::OFK_None) &&
5598 !Triple.isAMDGPU() && !Triple.isSPIRV()) {
5599 D.Diag(diag::err_drv_unsupported_opt_for_target)
5600 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5601 << Triple.getTriple();
5602 } else if (Triple.isNVPTX() && !IsRDCMode &&
5604 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5605 << (LTOArg ? LTOArg->getAsString(Args) : "-foffload-lto")
5606 << "-fno-gpu-rdc";
5607 } else {
5608 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5609 CmdArgs.push_back(Args.MakeArgString(
5610 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5611 // PS4 uses the legacy LTO API, which does not support some of the
5612 // features enabled by -flto-unit.
5613 if (!RawTriple.isPS4() || (LTOMode == LTOK_Full) || !UnifiedLTO)
5614 CmdArgs.push_back("-flto-unit");
5615 }
5616 }
5617 }
5618
5619 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5620
5621 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5622 if (!types::isLLVMIR(Input.getType()))
5623 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5624 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5625 }
5626
5627 if (Triple.isPPC())
5628 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5629 options::OPT_mno_regnames);
5630
5631 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5632 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5633
5634 if (Args.getLastArg(options::OPT_save_temps_EQ))
5635 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5636
5637 if (Args.getLastArg(options::OPT_save_dynamic_debugging_temps))
5638 Args.AddLastArg(CmdArgs, options::OPT_save_dynamic_debugging_temps);
5639
5640 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5641 options::OPT_fmemory_profile_EQ,
5642 options::OPT_fno_memory_profile);
5643 if (MemProfArg &&
5644 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5645 MemProfArg->render(Args, CmdArgs);
5646
5647 if (auto *MemProfUseArg =
5648 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5649 if (MemProfArg)
5650 D.Diag(diag::err_drv_argument_not_allowed_with)
5651 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5652 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5653 options::OPT_fprofile_generate_EQ))
5654 D.Diag(diag::err_drv_argument_not_allowed_with)
5655 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5656 MemProfUseArg->render(Args, CmdArgs);
5657 }
5658
5659 // Embed-bitcode option.
5660 // Only white-listed flags below are allowed to be embedded.
5661 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5663 // Add flags implied by -fembed-bitcode.
5664 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5665 // Disable all llvm IR level optimizations.
5666 CmdArgs.push_back("-disable-llvm-passes");
5667
5668 // Render target options.
5669 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
5671
5672 // reject options that shouldn't be supported in bitcode
5673 // also reject kernel/kext
5674 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5675 options::OPT_mkernel,
5676 options::OPT_fapple_kext,
5677 options::OPT_ffunction_sections,
5678 options::OPT_fno_function_sections,
5679 options::OPT_fdata_sections,
5680 options::OPT_fno_data_sections,
5681 options::OPT_fbasic_block_sections_EQ,
5682 options::OPT_funique_internal_linkage_names,
5683 options::OPT_fno_unique_internal_linkage_names,
5684 options::OPT_funique_section_names,
5685 options::OPT_fno_unique_section_names,
5686 options::OPT_funique_basic_block_section_names,
5687 options::OPT_fno_unique_basic_block_section_names,
5688 options::OPT_mrestrict_it,
5689 options::OPT_mno_restrict_it,
5690 options::OPT_mstackrealign,
5691 options::OPT_mno_stackrealign,
5692 options::OPT_mstack_alignment,
5693 options::OPT_mcmodel_EQ,
5694 options::OPT_mlong_calls,
5695 options::OPT_mno_long_calls,
5696 options::OPT_ggnu_pubnames,
5697 options::OPT_gdwarf_aranges,
5698 options::OPT_fdebug_types_section,
5699 options::OPT_fno_debug_types_section,
5700 options::OPT_fdwarf_directory_asm,
5701 options::OPT_fno_dwarf_directory_asm,
5702 options::OPT_mrelax_all,
5703 options::OPT_mno_relax_all,
5704 options::OPT_ftrap_function_EQ,
5705 options::OPT_ffixed_r9,
5706 options::OPT_mfix_cortex_a53_835769,
5707 options::OPT_mno_fix_cortex_a53_835769,
5708 options::OPT_ffixed_x18,
5709 options::OPT_mglobal_merge,
5710 options::OPT_mno_global_merge,
5711 options::OPT_mred_zone,
5712 options::OPT_mno_red_zone,
5713 options::OPT_Wa_COMMA,
5714 options::OPT_Xassembler,
5715 options::OPT_mllvm,
5716 options::OPT_mmlir,
5717 };
5718 for (const auto &A : Args)
5719 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5720 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5721
5722 // Render the CodeGen options that need to be passed.
5723 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5724 options::OPT_fno_optimize_sibling_calls);
5725
5727 CmdArgs, JA);
5728
5729 // Render ABI arguments
5730 switch (TC.getArch()) {
5731 default: break;
5732 case llvm::Triple::arm:
5733 case llvm::Triple::armeb:
5734 case llvm::Triple::thumbeb:
5735 RenderARMABI(D, Triple, Args, CmdArgs);
5736 break;
5737 case llvm::Triple::aarch64:
5738 case llvm::Triple::aarch64_32:
5739 case llvm::Triple::aarch64_be:
5740 RenderAArch64ABI(Triple, Args, CmdArgs);
5741 break;
5742 }
5743
5744 // Input/Output file.
5745 if (Output.getType() == types::TY_Dependencies) {
5746 // Handled with other dependency code.
5747 } else if (Output.isFilename()) {
5748 CmdArgs.push_back("-o");
5749 CmdArgs.push_back(Output.getFilename());
5750 } else {
5751 assert(Output.isNothing() && "Input output.");
5752 }
5753
5754 for (const auto &II : Inputs) {
5755 addDashXForInput(Args, II, CmdArgs);
5756 if (II.isFilename())
5757 CmdArgs.push_back(II.getFilename());
5758 else
5759 II.getInputArg().renderAsInput(Args, CmdArgs);
5760 }
5761
5762 C.addCommand(std::make_unique<Command>(
5764 CmdArgs, Inputs, Output, D.getPrependArg()));
5765 return;
5766 }
5767
5768 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5769 CmdArgs.push_back("-fembed-bitcode=marker");
5770
5771 // We normally speed up the clang process a bit by skipping destructors at
5772 // exit, but when we're generating diagnostics we can rely on some of the
5773 // cleanup.
5774 if (!C.isForDiagnostics())
5775 CmdArgs.push_back("-disable-free");
5776 CmdArgs.push_back("-clear-ast-before-backend");
5777
5778#ifdef NDEBUG
5779 const bool IsAssertBuild = false;
5780#else
5781 const bool IsAssertBuild = true;
5782#endif
5783
5784 // Disable the verification pass in no-asserts builds unless otherwise
5785 // specified.
5786 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5787 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5788 CmdArgs.push_back("-disable-llvm-verifier");
5789 }
5790
5791 // Discard value names in no-asserts builds unless otherwise specified.
5792 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5793 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5794 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5795 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5796 return types::isLLVMIR(II.getType());
5797 })) {
5798 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5799 }
5800 CmdArgs.push_back("-discard-value-names");
5801 }
5802
5803 // Set the main file name, so that debug info works even with
5804 // -save-temps.
5805 CmdArgs.push_back("-main-file-name");
5806 CmdArgs.push_back(getBaseInputName(Args, Input));
5807
5808 // Some flags which affect the language (via preprocessor
5809 // defines).
5810 if (Args.hasArg(options::OPT_static))
5811 CmdArgs.push_back("-static-define");
5812
5813 Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
5814
5815 if (Args.hasArg(options::OPT_municode))
5816 CmdArgs.push_back("-DUNICODE");
5817
5818 if (isa<AnalyzeJobAction>(JA))
5819 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5820
5821 if (isa<AnalyzeJobAction>(JA) ||
5822 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5823 CmdArgs.push_back("-setup-static-analyzer");
5824
5825 // Enable compatilibily mode to avoid analyzer-config related errors.
5826 // Since we can't access frontend flags through hasArg, let's manually iterate
5827 // through them.
5828 bool FoundAnalyzerConfig = false;
5829 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5830 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5831 FoundAnalyzerConfig = true;
5832 break;
5833 }
5834 if (!FoundAnalyzerConfig)
5835 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5836 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5837 FoundAnalyzerConfig = true;
5838 break;
5839 }
5840 if (FoundAnalyzerConfig)
5841 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5842
5844
5845 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5846 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5847 if (FunctionAlignment) {
5848 CmdArgs.push_back("-function-alignment");
5849 CmdArgs.push_back(Args.MakeArgString(Twine(FunctionAlignment)));
5850 }
5851
5852 if (const Arg *A =
5853 Args.getLastArg(options::OPT_fpreferred_function_alignment_EQ)) {
5854 unsigned Value = 0;
5855 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5856 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5857 << A->getAsString(Args) << A->getValue();
5858 else if (!llvm::isPowerOf2_32(Value))
5859 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5860 << A->getAsString(Args) << A->getValue();
5861
5862 CmdArgs.push_back(Args.MakeArgString("-fpreferred-function-alignment=" +
5863 Twine(std::min(Value, 65536u))));
5864 }
5865
5866 // We support -falign-loops=N where N is a power of 2. GCC supports more
5867 // forms.
5868 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5869 unsigned Value = 0;
5870 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5871 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5872 << A->getAsString(Args) << A->getValue();
5873 else if (Value & (Value - 1))
5874 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5875 << A->getAsString(Args) << A->getValue();
5876 // Treat =0 as unspecified (use the target preference).
5877 if (Value)
5878 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5879 Twine(std::min(Value, 65536u))));
5880 }
5881
5882 if (Triple.isOSzOS()) {
5883 // On z/OS some of the system header feature macros need to
5884 // be defined to enable most cross platform projects to build
5885 // successfully. Ths include the libc++ library. A
5886 // complicating factor is that users can define these
5887 // macros to the same or different values. We need to add
5888 // the definition for these macros to the compilation command
5889 // if the user hasn't already defined them.
5890
5891 auto findMacroDefinition = [&](const std::string &Macro) {
5892 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5893 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5894 return M == Macro || M.find(Macro + '=') != std::string::npos;
5895 });
5896 };
5897
5898 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5899 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5900 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5901 // _OPEN_DEFAULT is required for XL compat
5902 if (!findMacroDefinition("_OPEN_DEFAULT"))
5903 CmdArgs.push_back("-D_OPEN_DEFAULT");
5904 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5905 // _XOPEN_SOURCE=600 is required for libcxx.
5906 if (!findMacroDefinition("_XOPEN_SOURCE"))
5907 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5908 }
5909 }
5910
5911 llvm::Reloc::Model RelocationModel;
5912 unsigned PICLevel;
5913 bool IsPIE;
5914 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5915 Arg *LastPICDataRelArg =
5916 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5917 options::OPT_mpic_data_is_text_relative);
5918 bool NoPICDataIsTextRelative = false;
5919 if (LastPICDataRelArg) {
5920 if (LastPICDataRelArg->getOption().matches(
5921 options::OPT_mno_pic_data_is_text_relative)) {
5922 NoPICDataIsTextRelative = true;
5923 if (!PICLevel)
5924 D.Diag(diag::err_drv_argument_only_allowed_with)
5925 << "-mno-pic-data-is-text-relative"
5926 << "-fpic/-fpie";
5927 }
5928 if (!Triple.isSystemZ())
5929 D.Diag(diag::err_drv_unsupported_opt_for_target)
5930 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5931 : "-mpic-data-is-text-relative")
5932 << RawTriple.str();
5933 }
5934
5935 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5936 RelocationModel == llvm::Reloc::ROPI_RWPI;
5937 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5938 RelocationModel == llvm::Reloc::ROPI_RWPI;
5939
5940 if (Args.hasArg(options::OPT_mcmse) &&
5941 !Args.hasArg(options::OPT_fallow_unsupported)) {
5942 if (IsROPI)
5943 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5944 if (IsRWPI)
5945 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5946 }
5947
5948 if (IsROPI && types::isCXX(Input.getType()) &&
5949 !Args.hasArg(options::OPT_fallow_unsupported))
5950 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5951
5952 const char *RMName = RelocationModelName(RelocationModel);
5953 if (RMName) {
5954 CmdArgs.push_back("-mrelocation-model");
5955 CmdArgs.push_back(RMName);
5956 }
5957 if (PICLevel > 0) {
5958 CmdArgs.push_back("-pic-level");
5959 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5960 if (IsPIE)
5961 CmdArgs.push_back("-pic-is-pie");
5962 if (NoPICDataIsTextRelative)
5963 CmdArgs.push_back("-mcmodel=medium");
5964 }
5965
5966 if (RelocationModel == llvm::Reloc::ROPI ||
5967 RelocationModel == llvm::Reloc::ROPI_RWPI)
5968 CmdArgs.push_back("-fropi");
5969 if (RelocationModel == llvm::Reloc::RWPI ||
5970 RelocationModel == llvm::Reloc::ROPI_RWPI)
5971 CmdArgs.push_back("-frwpi");
5972
5973 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5974 CmdArgs.push_back("-meabi");
5975 CmdArgs.push_back(A->getValue());
5976 }
5977
5978 // -fsemantic-interposition is forwarded to CC1: set the
5979 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5980 // make default visibility external linkage definitions dso_preemptable.
5981 //
5982 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5983 // aliases (make default visibility external linkage definitions dso_local).
5984 // This is the CC1 default for ELF to match COFF/Mach-O.
5985 //
5986 // Otherwise use Clang's traditional behavior: like
5987 // -fno-semantic-interposition but local aliases are not used. So references
5988 // can be interposed if not optimized out.
5989 if (Triple.isOSBinFormatELF()) {
5990 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5991 options::OPT_fno_semantic_interposition);
5992 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5993 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5994 bool SupportsLocalAlias =
5995 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5996 if (!A)
5997 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5998 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5999 A->render(Args, CmdArgs);
6000 else if (!SupportsLocalAlias)
6001 CmdArgs.push_back("-fhalf-no-semantic-interposition");
6002 }
6003 }
6004
6005 {
6006 std::string Model;
6007 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
6008 if (!TC.isThreadModelSupported(A->getValue()))
6009 D.Diag(diag::err_drv_invalid_thread_model_for_target)
6010 << A->getValue() << A->getAsString(Args);
6011 Model = A->getValue();
6012 } else
6013 Model = TC.getThreadModel();
6014 if (Model != "posix") {
6015 CmdArgs.push_back("-mthread-model");
6016 CmdArgs.push_back(Args.MakeArgString(Model));
6017 }
6018 }
6019
6020 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
6021 StringRef Name = A->getValue();
6022 if (Name == "SVML") {
6023 if (Triple.getArch() != llvm::Triple::x86 &&
6024 Triple.getArch() != llvm::Triple::x86_64)
6025 D.Diag(diag::err_drv_unsupported_opt_for_target)
6026 << Name << Triple.getArchName();
6027 } else if (Name == "AMDLIBM") {
6028 if (Triple.getArch() != llvm::Triple::x86 &&
6029 Triple.getArch() != llvm::Triple::x86_64)
6030 D.Diag(diag::err_drv_unsupported_opt_for_target)
6031 << Name << Triple.getArchName();
6032 } else if (Name == "libmvec") {
6033 if (Triple.getArch() != llvm::Triple::x86 &&
6034 Triple.getArch() != llvm::Triple::x86_64 &&
6035 Triple.getArch() != llvm::Triple::aarch64 &&
6036 Triple.getArch() != llvm::Triple::aarch64_be)
6037 D.Diag(diag::err_drv_unsupported_opt_for_target)
6038 << Name << Triple.getArchName();
6039 } else if (Name == "SLEEF" || Name == "ArmPL") {
6040 if (Triple.getArch() != llvm::Triple::aarch64 &&
6041 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
6042 D.Diag(diag::err_drv_unsupported_opt_for_target)
6043 << Name << Triple.getArchName();
6044 }
6045 A->render(Args, CmdArgs);
6046 }
6047
6048 if (Args.hasFlag(options::OPT_fmerge_all_constants,
6049 options::OPT_fno_merge_all_constants, false))
6050 CmdArgs.push_back("-fmerge-all-constants");
6051
6052 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
6053 options::OPT_fno_delete_null_pointer_checks);
6054
6055 Args.addOptOutFlag(CmdArgs, options::OPT_flifetime_dse,
6056 options::OPT_fno_lifetime_dse);
6057
6058 // LLVM Code Generator Options.
6059
6060 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
6061 if (!Triple.isOSAIX() || Triple.isPPC32())
6062 D.Diag(diag::err_drv_unsupported_opt_for_target)
6063 << A->getSpelling() << RawTriple.str();
6064 CmdArgs.push_back("-mabi=quadword-atomics");
6065 }
6066
6067 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
6068 // Emit the unsupported option error until the Clang's library integration
6069 // support for 128-bit long double is available for AIX.
6070 if (Triple.isOSAIX())
6071 D.Diag(diag::err_drv_unsupported_opt_for_target)
6072 << A->getSpelling() << RawTriple.str();
6073 }
6074
6075 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
6076 StringRef V = A->getValue(), V1 = V;
6077 unsigned Size;
6078 if (V1.consumeInteger(10, Size) || !V1.empty())
6079 D.Diag(diag::err_drv_invalid_argument_to_option)
6080 << V << A->getOption().getName();
6081 else
6082 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
6083 }
6084
6085 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
6086 options::OPT_fno_jump_tables);
6087 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
6088 options::OPT_fno_profile_sample_accurate);
6089 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
6090 options::OPT_fno_preserve_as_comments);
6091
6092 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
6093 CmdArgs.push_back("-mregparm");
6094 CmdArgs.push_back(A->getValue());
6095 }
6096
6097 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
6098 options::OPT_msvr4_struct_return)) {
6099 if (!TC.getTriple().isPPC32()) {
6100 D.Diag(diag::err_drv_unsupported_opt_for_target)
6101 << A->getSpelling() << RawTriple.str();
6102 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
6103 CmdArgs.push_back("-maix-struct-return");
6104 } else {
6105 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
6106 CmdArgs.push_back("-msvr4-struct-return");
6107 }
6108 }
6109
6110 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
6111 options::OPT_freg_struct_return)) {
6112 if (TC.getArch() != llvm::Triple::x86) {
6113 D.Diag(diag::err_drv_unsupported_opt_for_target)
6114 << A->getSpelling() << RawTriple.str();
6115 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
6116 CmdArgs.push_back("-fpcc-struct-return");
6117 } else {
6118 assert(A->getOption().matches(options::OPT_freg_struct_return));
6119 CmdArgs.push_back("-freg-struct-return");
6120 }
6121 }
6122
6123 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
6124 if (Triple.getArch() == llvm::Triple::m68k)
6125 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
6126 else
6127 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6128 }
6129
6130 if (Args.hasArg(options::OPT_fenable_matrix)) {
6131 // enable-matrix is needed by both the LangOpts and by LLVM.
6132 CmdArgs.push_back("-fenable-matrix");
6133 CmdArgs.push_back("-mllvm");
6134 CmdArgs.push_back("-enable-matrix");
6135 // Only handle default layout if matrix is enabled
6136 if (const Arg *A = Args.getLastArg(options::OPT_fmatrix_memory_layout_EQ)) {
6137 StringRef Val = A->getValue();
6138 if (Val == "row-major" || Val == "column-major") {
6139 CmdArgs.push_back(Args.MakeArgString("-fmatrix-memory-layout=" + Val));
6140 CmdArgs.push_back("-mllvm");
6141 CmdArgs.push_back(Args.MakeArgString("-matrix-default-layout=" + Val));
6142
6143 } else {
6144 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
6145 }
6146 }
6147 }
6148
6150 getFramePointerKind(Args, RawTriple);
6151 const char *FPKeepKindStr = nullptr;
6152 switch (FPKeepKind) {
6154 FPKeepKindStr = "-mframe-pointer=none";
6155 break;
6157 FPKeepKindStr = "-mframe-pointer=reserved";
6158 break;
6160 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
6161 break;
6163 FPKeepKindStr = "-mframe-pointer=non-leaf";
6164 break;
6166 FPKeepKindStr = "-mframe-pointer=all";
6167 break;
6168 }
6169 assert(FPKeepKindStr && "unknown FramePointerKind");
6170 CmdArgs.push_back(FPKeepKindStr);
6171
6172 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
6173 options::OPT_fno_zero_initialized_in_bss);
6174
6175 bool OFastEnabled = isOptimizationLevelFast(Args);
6176 if (Args.hasArg(options::OPT_Ofast))
6177 D.Diag(diag::warn_drv_deprecated_arg_ofast);
6178 // If -Ofast is the optimization level, then -fstrict-aliasing should be
6179 // enabled. This alias option is being used to simplify the hasFlag logic.
6180 OptSpecifier StrictAliasingAliasOption =
6181 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
6182 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
6183 // doesn't do any TBAA.
6184 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
6185 options::OPT_fno_strict_aliasing,
6186 !IsWindowsMSVC && !IsUEFI))
6187 CmdArgs.push_back("-relaxed-aliasing");
6188 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
6189 false))
6190 CmdArgs.push_back("-no-pointer-tbaa");
6191 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
6192 options::OPT_fno_struct_path_tbaa, true))
6193 CmdArgs.push_back("-no-struct-path-tbaa");
6194
6195 if (Arg *A = Args.getLastArg(options::OPT_fstrict_bool,
6196 options::OPT_fno_strict_bool,
6197 options::OPT_fno_strict_bool_EQ)) {
6198 StringRef BFM = "";
6199 if (A->getOption().matches(options::OPT_fstrict_bool))
6200 BFM = "strict";
6201 else if (A->getOption().matches(options::OPT_fno_strict_bool))
6202 BFM = "nonstrict";
6203 else if (A->getValue() == StringRef("truncate"))
6204 BFM = "truncate";
6205 else if (A->getValue() == StringRef("nonzero"))
6206 BFM = "nonzero";
6207 else
6208 D.Diag(diag::err_drv_invalid_value)
6209 << A->getAsString(Args) << A->getValue();
6210 CmdArgs.push_back(Args.MakeArgString("-load-bool-from-mem=" + BFM));
6211 } else if (KernelOrKext) {
6212 // If unspecified, assume -fno-strict-bool=truncate in the Darwin kernel.
6213 CmdArgs.push_back("-load-bool-from-mem=truncate");
6214 }
6215
6216 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
6217 options::OPT_fno_strict_enums);
6218 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
6219 options::OPT_fno_strict_return);
6220 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
6221 options::OPT_fno_allow_editor_placeholders);
6222 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
6223 options::OPT_fno_strict_vtable_pointers);
6224 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
6225 options::OPT_fno_force_emit_vtables);
6226 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
6227 options::OPT_fno_optimize_sibling_calls);
6228 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
6229 options::OPT_fno_escaping_block_tail_calls);
6230
6231 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6232 options::OPT_fno_fine_grained_bitfield_accesses);
6233
6234 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6235 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6236
6237 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6238 options::OPT_fno_experimental_omit_vtable_rtti);
6239
6240 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6241 options::OPT_fno_disable_block_signature_string);
6242
6243 // Handle segmented stacks.
6244 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6245 options::OPT_fno_split_stack);
6246
6247 // -fprotect-parens=0 is default.
6248 if (Args.hasFlag(options::OPT_fprotect_parens,
6249 options::OPT_fno_protect_parens, false))
6250 CmdArgs.push_back("-fprotect-parens");
6251
6252 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6253
6254 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_remote_memory,
6255 options::OPT_fno_atomic_remote_memory);
6256 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_fine_grained_memory,
6257 options::OPT_fno_atomic_fine_grained_memory);
6258 Args.addOptInFlag(CmdArgs, options::OPT_fatomic_ignore_denormal_mode,
6259 options::OPT_fno_atomic_ignore_denormal_mode);
6260
6261 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6262 const llvm::Triple::ArchType Arch = TC.getArch();
6263 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6264 StringRef V = A->getValue();
6265 if (V == "64")
6266 CmdArgs.push_back("-fextend-arguments=64");
6267 else if (V != "32")
6268 D.Diag(diag::err_drv_invalid_argument_to_option)
6269 << A->getValue() << A->getOption().getName();
6270 } else
6271 D.Diag(diag::err_drv_unsupported_opt_for_target)
6272 << A->getOption().getName() << TripleStr;
6273 }
6274
6275 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6276 if (TC.getArch() == llvm::Triple::avr)
6277 A->render(Args, CmdArgs);
6278 else
6279 D.Diag(diag::err_drv_unsupported_opt_for_target)
6280 << A->getAsString(Args) << TripleStr;
6281 }
6282
6283 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6284 if (TC.getTriple().isX86())
6285 A->render(Args, CmdArgs);
6286 else if (TC.getTriple().isPPC() &&
6287 (A->getOption().getID() != options::OPT_mlong_double_80))
6288 A->render(Args, CmdArgs);
6289 else
6290 D.Diag(diag::err_drv_unsupported_opt_for_target)
6291 << A->getAsString(Args) << TripleStr;
6292 }
6293
6294 // Decide whether to use verbose asm. Verbose assembly is the default on
6295 // toolchains which have the integrated assembler on by default.
6296 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6297 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6298 IsIntegratedAssemblerDefault))
6299 CmdArgs.push_back("-fno-verbose-asm");
6300
6301 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6302 // use that to indicate the MC default in the backend.
6303 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6304 StringRef V = A->getValue();
6305 unsigned Num;
6306 if (V == "none")
6307 A->render(Args, CmdArgs);
6308 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6309 (V.empty() || (V.consume_front(".") &&
6310 !V.consumeInteger(10, Num) && V.empty())))
6311 A->render(Args, CmdArgs);
6312 else
6313 D.Diag(diag::err_drv_invalid_argument_to_option)
6314 << A->getValue() << A->getOption().getName();
6315 }
6316
6317 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6318 // option to disable integrated-as explicitly.
6320 CmdArgs.push_back("-no-integrated-as");
6321
6322 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6323 CmdArgs.push_back("-mdebug-pass");
6324 CmdArgs.push_back("Structure");
6325 }
6326 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6327 CmdArgs.push_back("-mdebug-pass");
6328 CmdArgs.push_back("Arguments");
6329 }
6330
6331 // Enable -mconstructor-aliases except on darwin, where we have to work around
6332 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6333 // code, where aliases aren't supported.
6334 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6335 CmdArgs.push_back("-mconstructor-aliases");
6336
6337 // Darwin's kernel doesn't support guard variables; just die if we
6338 // try to use them.
6339 if (KernelOrKext && RawTriple.isOSDarwin())
6340 CmdArgs.push_back("-fforbid-guard-variables");
6341
6342 if (Arg *A = Args.getLastArg(options::OPT_mms_bitfields,
6343 options::OPT_mno_ms_bitfields)) {
6344 if (A->getOption().matches(options::OPT_mms_bitfields))
6345 CmdArgs.push_back("-fms-layout-compatibility=microsoft");
6346 else
6347 CmdArgs.push_back("-fms-layout-compatibility=itanium");
6348 }
6349
6350 if (Triple.isOSCygMing()) {
6351 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6352 options::OPT_fno_auto_import);
6353 }
6354
6355 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6356 Triple.isX86() && IsWindowsMSVC))
6357 CmdArgs.push_back("-fms-volatile");
6358
6359 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6360 // defaults to -fno-direct-access-external-data. Pass the option if different
6361 // from the default.
6362 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6363 options::OPT_fno_direct_access_external_data)) {
6364 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6365 (PICLevel == 0))
6366 A->render(Args, CmdArgs);
6367 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6368 // Some targets default to -fno-direct-access-external-data even for
6369 // -fno-pic.
6370 CmdArgs.push_back("-fno-direct-access-external-data");
6371 }
6372
6373 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6374 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
6375
6376 // -fhosted is default.
6377 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6378 // use Freestanding.
6379 bool Freestanding =
6380 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6381 KernelOrKext;
6382 if (Freestanding)
6383 CmdArgs.push_back("-ffreestanding");
6384
6385 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6386
6388 auto SanitizeArgs =
6390 Args.AddLastArg(CmdArgs,
6391 options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6392
6393 // This is a coarse approximation of what llvm-gcc actually does, both
6394 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6395 // complicated ways.
6396 bool IsAsyncUnwindTablesDefault =
6398 bool IsSyncUnwindTablesDefault =
6400
6401 bool AsyncUnwindTables = Args.hasFlag(
6402 options::OPT_fasynchronous_unwind_tables,
6403 options::OPT_fno_asynchronous_unwind_tables,
6404 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6405 !Freestanding);
6406 bool UnwindTables =
6407 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6408 IsSyncUnwindTablesDefault && !Freestanding);
6409 if (AsyncUnwindTables)
6410 CmdArgs.push_back("-funwind-tables=2");
6411 else if (UnwindTables)
6412 CmdArgs.push_back("-funwind-tables=1");
6413
6414 // Sframe unwind tables are independent of the other types. Although also
6415 // defined for aarch64, only x86_64 support is implemented at the moment.
6416 if (Arg *A = Args.getLastArg(options::OPT_gsframe)) {
6417 if (Triple.isOSBinFormatELF() && Triple.isX86())
6418 CmdArgs.push_back("--gsframe");
6419 else
6420 D.Diag(diag::err_drv_unsupported_opt_for_target)
6421 << A->getOption().getName() << TripleStr;
6422 }
6423
6424 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6425 // `--gpu-use-aux-triple-only` is specified.
6426 if (AuxTriple && !Args.getLastArg(options::OPT_gpu_use_aux_triple_only)) {
6427 const ArgList &HostArgs =
6428 C.getArgsForToolChain(nullptr, BoundArch(), Action::OFK_None);
6429 std::string HostCPU = getCPUName(D, HostArgs, *AuxTriple, /*FromAs*/ false);
6430 if (!HostCPU.empty()) {
6431 CmdArgs.push_back("-aux-target-cpu");
6432 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6433 }
6434 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6435 /*ForAS*/ false, /*IsAux*/ true);
6436 }
6437
6438 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
6440
6441 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6442
6443 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6444 StringRef Value = A->getValue();
6445 unsigned TLSSize = 0;
6446 Value.getAsInteger(10, TLSSize);
6447 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6448 D.Diag(diag::err_drv_unsupported_opt_for_target)
6449 << A->getOption().getName() << TripleStr;
6450 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6451 D.Diag(diag::err_drv_invalid_int_value)
6452 << A->getOption().getName() << Value;
6453 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6454 }
6455
6456 if (isTLSDESCEnabled(TC, Args))
6457 CmdArgs.push_back("-enable-tlsdesc");
6458
6459 // Add the target cpu
6460 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6461 if (!CPU.empty()) {
6462 CmdArgs.push_back("-target-cpu");
6463 CmdArgs.push_back(Args.MakeArgString(CPU));
6464 }
6465
6466 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6467
6468 // Add clang-cl arguments.
6469 types::ID InputType = Input.getType();
6470 if (D.IsCLMode())
6471 AddClangCLArgs(Args, InputType, CmdArgs);
6472
6473 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6474 llvm::codegenoptions::NoDebugInfo;
6476 renderDebugOptions(TC, D, RawTriple, Args, InputType, CmdArgs, Output,
6477 DebugInfoKind, DwarfFission, IsUsingLTO);
6478
6479 // Add the split debug info name to the command lines here so we
6480 // can propagate it to the backend.
6481 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6482 (TC.getTriple().isOSBinFormatELF() ||
6483 TC.getTriple().isOSBinFormatWasm() ||
6484 TC.getTriple().isOSBinFormatCOFF()) &&
6487 if (SplitDWARF) {
6488 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6489 CmdArgs.push_back("-split-dwarf-file");
6490 CmdArgs.push_back(SplitDWARFOut);
6491 if (DwarfFission == DwarfFissionKind::Split) {
6492 CmdArgs.push_back("-split-dwarf-output");
6493 CmdArgs.push_back(SplitDWARFOut);
6494 }
6495 }
6496
6497 // Pass the linker version in use.
6498 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6499 CmdArgs.push_back("-target-linker-version");
6500 CmdArgs.push_back(A->getValue());
6501 }
6502
6503 // Explicitly error on some things we know we don't support and can't just
6504 // ignore.
6505 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6506 Arg *Unsupported;
6507 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6508 TC.getArch() == llvm::Triple::x86) {
6509 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6510 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6511 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6512 << Unsupported->getOption().getName();
6513 }
6514 // The faltivec option has been superseded by the maltivec option.
6515 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6516 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6517 << Unsupported->getOption().getName()
6518 << "please use -maltivec and include altivec.h explicitly";
6519 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6520 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6521 << Unsupported->getOption().getName() << "please use -mno-altivec";
6522 }
6523
6524 Args.AddAllArgs(CmdArgs, options::OPT_v);
6525
6526 if (Args.getLastArg(options::OPT_H)) {
6527 CmdArgs.push_back("-H");
6528 CmdArgs.push_back("-sys-header-deps");
6529 }
6530 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6531
6533 CmdArgs.push_back("-header-include-file");
6534 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6535 ? D.CCPrintHeadersFilename.c_str()
6536 : "-");
6537 CmdArgs.push_back("-sys-header-deps");
6538 CmdArgs.push_back(Args.MakeArgString(
6539 "-header-include-format=" +
6541 CmdArgs.push_back(Args.MakeArgString(
6542 "-header-include-filtering=" +
6544 }
6545 Args.AddLastArg(CmdArgs, options::OPT_P);
6546 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6547
6548 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6549 CmdArgs.push_back("-diagnostic-log-file");
6550 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6551 ? D.CCLogDiagnosticsFilename.c_str()
6552 : "-");
6553 }
6554
6555 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6556 // crashes.
6557 if (D.CCGenDiagnostics)
6558 CmdArgs.push_back("-disable-pragma-debug-crash");
6559
6560 // Allow backend to put its diagnostic files in the same place as frontend
6561 // crash diagnostics files.
6562 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6563 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6564 CmdArgs.push_back("-mllvm");
6565 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6566 }
6567
6568 addSeparateSectionFlags(Triple, Args, CmdArgs);
6569
6570 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6571 options::OPT_fno_basic_block_address_map)) {
6572 if (((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) ||
6573 (Triple.isX86() && Triple.isOSBinFormatCOFF())) {
6574 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6575 A->render(Args, CmdArgs);
6576 } else {
6577 D.Diag(diag::err_drv_unsupported_opt_for_target)
6578 << A->getAsString(Args) << TripleStr;
6579 }
6580 }
6581
6582 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6583 StringRef Val = A->getValue();
6584 if (Val == "labels") {
6585 D.Diag(diag::warn_drv_deprecated_arg)
6586 << A->getAsString(Args) << /*hasReplacement=*/true
6587 << "-fbasic-block-address-map";
6588 CmdArgs.push_back("-fbasic-block-address-map");
6589 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6590 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6591 D.Diag(diag::err_drv_invalid_value)
6592 << A->getAsString(Args) << A->getValue();
6593 else
6594 A->render(Args, CmdArgs);
6595 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6596 // "all" is not supported on AArch64 since branch relaxation creates new
6597 // basic blocks for some cross-section branches.
6598 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6599 D.Diag(diag::err_drv_invalid_value)
6600 << A->getAsString(Args) << A->getValue();
6601 else
6602 A->render(Args, CmdArgs);
6603 } else if (Triple.isNVPTX()) {
6604 // Do not pass the option to the GPU compilation. We still want it enabled
6605 // for the host-side compilation, so seeing it here is not an error.
6606 } else if (Val != "none") {
6607 // =none is allowed everywhere. It's useful for overriding the option
6608 // and is the same as not specifying the option.
6609 D.Diag(diag::err_drv_unsupported_opt_for_target)
6610 << A->getAsString(Args) << TripleStr;
6611 }
6612 }
6613
6614 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6615 options::OPT_fno_unique_section_names);
6616 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6617 options::OPT_fno_separate_named_sections);
6618 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6619 options::OPT_fno_unique_internal_linkage_names);
6620 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6621 options::OPT_fno_unique_basic_block_section_names);
6622
6623 addSplitMachineFunctionsArgs(D, Args, CmdArgs, Triple);
6624
6625 if (Arg *A =
6626 Args.getLastArg(options::OPT_fpartition_static_data_sections,
6627 options::OPT_fno_partition_static_data_sections)) {
6628 if (!A->getOption().matches(
6629 options::OPT_fno_partition_static_data_sections)) {
6630 // This codegen pass is only available on x86 and AArch64 ELF targets.
6631 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6632 A->render(Args, CmdArgs);
6633 CmdArgs.push_back("-mllvm");
6634 CmdArgs.push_back("-memprof-annotate-static-data-prefix");
6635 } else
6636 D.Diag(diag::err_drv_unsupported_opt_for_target)
6637 << A->getAsString(Args) << TripleStr;
6638 }
6639 }
6640
6641 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6642 options::OPT_finstrument_functions_after_inlining,
6643 options::OPT_finstrument_function_entry_bare);
6644 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6645 options::OPT_fno_convergent_functions);
6646
6647 // NVPTX doesn't support PGO or coverage
6648 if (!Triple.isNVPTX())
6649 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6650
6651 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6652
6653 if (getLastProfileSampleUseArg(Args) &&
6654 Args.hasFlag(options::OPT_fsample_profile_use_profi,
6655 options::OPT_fno_sample_profile_use_profi, true)) {
6656 CmdArgs.push_back("-mllvm");
6657 CmdArgs.push_back("-sample-profile-use-profi");
6658 }
6659
6660 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6661 if (RawTriple.isPS() &&
6662 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6663 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6664 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6665 }
6666
6667 // Pass options for controlling the default header search paths.
6668 if (Args.hasArg(options::OPT_nostdinc)) {
6669 CmdArgs.push_back("-nostdsysteminc");
6670 CmdArgs.push_back("-nobuiltininc");
6671 } else {
6672 if (Args.hasArg(options::OPT_nostdlibinc))
6673 CmdArgs.push_back("-nostdsysteminc");
6674 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6675 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6676 }
6677
6678 // Pass the path to compiler resource files.
6679 CmdArgs.push_back("-resource-dir");
6680 CmdArgs.push_back(D.ResourceDir.c_str());
6681
6682 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6683
6684 // Add preprocessing options like -I, -D, etc. if we are using the
6685 // preprocessor.
6686 //
6687 // FIXME: Support -fpreprocessed
6689 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6690
6691 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6692 // that "The compiler can only warn and ignore the option if not recognized".
6693 // When building with ccache, it will pass -D options to clang even on
6694 // preprocessed inputs and configure concludes that -fPIC is not supported.
6695 Args.ClaimAllArgs(options::OPT_D);
6696
6697 // Warn about ignored options to clang.
6698 for (const Arg *A :
6699 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6700 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6701 A->claim();
6702 }
6703
6704 for (const Arg *A :
6705 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6706 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6707 A->claim();
6708 }
6709
6710 claimNoWarnArgs(Args);
6711
6712 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6713
6714 for (const Arg *A :
6715 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6716 A->claim();
6717 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6718 unsigned WarningNumber;
6719 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6720 D.Diag(diag::err_drv_invalid_int_value)
6721 << A->getAsString(Args) << A->getValue();
6722 continue;
6723 }
6724
6725 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6726 CmdArgs.push_back(Args.MakeArgString(
6727 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6728 }
6729 continue;
6730 }
6731 A->render(Args, CmdArgs);
6732 }
6733
6734 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6735
6736 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6737 CmdArgs.push_back("-pedantic");
6738 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6739 Args.AddLastArg(CmdArgs, options::OPT_w);
6740
6741 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6742 options::OPT_fno_fixed_point);
6743
6744 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_overflow_behavior_types,
6745 options::OPT_fno_experimental_overflow_behavior_types);
6746
6747 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6748 A->render(Args, CmdArgs);
6749
6750 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6751 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6752
6753 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6754 options::OPT_fno_experimental_omit_vtable_rtti);
6755
6756 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6757 A->render(Args, CmdArgs);
6758
6759 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6760 // (-ansi is equivalent to -std=c89 or -std=c++98).
6761 //
6762 // If a std is supplied, only add -trigraphs if it follows the
6763 // option.
6764 bool ImplyVCPPCVer = false;
6765 bool ImplyVCPPCXXVer = false;
6766 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6767 if (Std) {
6768 if (Std->getOption().matches(options::OPT_ansi))
6769 if (types::isCXX(InputType))
6770 CmdArgs.push_back("-std=c++98");
6771 else
6772 CmdArgs.push_back("-std=c89");
6773 else {
6774 if (IsSYCL) {
6775 const LangStandard *LangStd =
6776 LangStandard::getLangStandardForName(Std->getValue());
6777 if (LangStd) {
6778 // Use of -std= with 'C' is not supported for SYCL.
6779 if (LangStd->getLanguage() == Language::C)
6780 D.Diag(diag::err_drv_argument_not_allowed_with)
6781 << Std->getAsString(Args) << "-fsycl";
6782 // SYCL requires C++17 or later.
6783 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
6784 D.Diag(diag::err_drv_sycl_requires_cxx17) << Std->getAsString(Args);
6785 }
6786 }
6787 Std->render(Args, CmdArgs);
6788 }
6789
6790 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6791 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6792 options::OPT_ftrigraphs,
6793 options::OPT_fno_trigraphs))
6794 if (A != Std)
6795 A->render(Args, CmdArgs);
6796 } else {
6797 // Honor -std-default.
6798 //
6799 // FIXME: Clang doesn't correctly handle -std= when the input language
6800 // doesn't match. For the time being just ignore this for C++ inputs;
6801 // eventually we want to do all the standard defaulting here instead of
6802 // splitting it between the driver and clang -cc1.
6803 if (!types::isCXX(InputType)) {
6804 if (!Args.hasArg(options::OPT__SLASH_std)) {
6805 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6806 /*Joined=*/true);
6807 } else
6808 ImplyVCPPCVer = true;
6809 }
6810 else if (IsWindowsMSVC)
6811 ImplyVCPPCXXVer = true;
6812
6813 if (IsSYCL && types::isCXX(InputType) &&
6814 !Args.hasArg(options::OPT__SLASH_std) && !IsWindowsMSVC)
6815 // For SYCL, we default to -std=c++17 for all compilations. Use of -std
6816 // on the command line will override. On Windows MSVC, this is handled
6817 // by the ImplyVCPPCXXVer path below.
6818 CmdArgs.push_back("-std=c++17");
6819
6820 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6821 options::OPT_fno_trigraphs);
6822 }
6823
6824 // GCC's behavior for -Wwrite-strings is a bit strange:
6825 // * In C, this "warning flag" changes the types of string literals from
6826 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6827 // for the discarded qualifier.
6828 // * In C++, this is just a normal warning flag.
6829 //
6830 // Implementing this warning correctly in C is hard, so we follow GCC's
6831 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6832 // a non-const char* in C, rather than using this crude hack.
6833 if (!types::isCXX(InputType)) {
6834 // FIXME: This should behave just like a warning flag, and thus should also
6835 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6836 Arg *WriteStrings =
6837 Args.getLastArg(options::OPT_Wwrite_strings,
6838 options::OPT_Wno_write_strings, options::OPT_w);
6839 if (WriteStrings &&
6840 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6841 CmdArgs.push_back("-fconst-strings");
6842 }
6843
6844 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6845 // during C++ compilation, which it is by default. GCC keeps this define even
6846 // in the presence of '-w', match this behavior bug-for-bug.
6847 if (types::isCXX(InputType) &&
6848 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6849 true)) {
6850 CmdArgs.push_back("-fdeprecated-macro");
6851 }
6852
6853 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6854 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6855 if (Asm->getOption().matches(options::OPT_fasm))
6856 CmdArgs.push_back("-fgnu-keywords");
6857 else
6858 CmdArgs.push_back("-fno-gnu-keywords");
6859 }
6860
6861 if (!ShouldEnableAutolink(Args, TC, JA))
6862 CmdArgs.push_back("-fno-autolink");
6863
6864 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6865 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6866 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6867 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6868
6869 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6870
6871 if (CLANG_USE_EXPERIMENTAL_CONST_INTERP) {
6872 Args.ClaimAllArgs(options::OPT_fexperimental_new_constant_interpreter);
6873 Args.AddLastArg(CmdArgs,
6874 options::OPT_fno_experimental_new_constant_interpreter);
6875 } else {
6876 Args.ClaimAllArgs(options::OPT_fno_experimental_new_constant_interpreter);
6877 Args.AddLastArg(CmdArgs,
6878 options::OPT_fexperimental_new_constant_interpreter);
6879 }
6880
6881 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6882 CmdArgs.push_back("-fbracket-depth");
6883 CmdArgs.push_back(A->getValue());
6884 }
6885
6886 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6887 options::OPT_Wlarge_by_value_copy_def)) {
6888 if (A->getNumValues()) {
6889 StringRef bytes = A->getValue();
6890 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6891 } else
6892 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6893 }
6894
6895 if (Args.hasArg(options::OPT_relocatable_pch))
6896 CmdArgs.push_back("-relocatable-pch");
6897
6898 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6899 static const char *kCFABIs[] = {
6900 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6901 };
6902
6903 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6904 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6905 else
6906 A->render(Args, CmdArgs);
6907 }
6908
6909 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6910 CmdArgs.push_back("-fconstant-string-class");
6911 CmdArgs.push_back(A->getValue());
6912 }
6913
6914 if (Arg *A = Args.getLastArg(options::OPT_fconstant_array_class_EQ)) {
6915 CmdArgs.push_back("-fconstant-array-class");
6916 CmdArgs.push_back(A->getValue());
6917 }
6918 if (Arg *A = Args.getLastArg(options::OPT_fconstant_dictionary_class_EQ)) {
6919 CmdArgs.push_back("-fconstant-dictionary-class");
6920 CmdArgs.push_back(A->getValue());
6921 }
6922 if (Arg *A =
6923 Args.getLastArg(options::OPT_fconstant_integer_number_class_EQ)) {
6924 CmdArgs.push_back("-fconstant-integer-number-class");
6925 CmdArgs.push_back(A->getValue());
6926 }
6927 if (Arg *A = Args.getLastArg(options::OPT_fconstant_float_number_class_EQ)) {
6928 CmdArgs.push_back("-fconstant-float-number-class");
6929 CmdArgs.push_back(A->getValue());
6930 }
6931 if (Arg *A = Args.getLastArg(options::OPT_fconstant_double_number_class_EQ)) {
6932 CmdArgs.push_back("-fconstant-double-number-class");
6933 CmdArgs.push_back(A->getValue());
6934 }
6935
6936 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6937 CmdArgs.push_back("-ftabstop");
6938 CmdArgs.push_back(A->getValue());
6939 }
6940
6941 if (Args.hasFlag(options::OPT_fexperimental_call_graph_section,
6942 options::OPT_fno_experimental_call_graph_section, false))
6943 CmdArgs.push_back("-fexperimental-call-graph-section");
6944
6945 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6946 options::OPT_fno_stack_size_section);
6947
6948 if (Args.hasArg(options::OPT_fstack_usage)) {
6949 CmdArgs.push_back("-stack-usage-file");
6950
6951 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6952 SmallString<128> OutputFilename(OutputOpt->getValue());
6953 llvm::sys::path::replace_extension(OutputFilename, "su");
6954 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6955 } else
6956 CmdArgs.push_back(
6957 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6958 }
6959
6960 CmdArgs.push_back("-ferror-limit");
6961 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6962 CmdArgs.push_back(A->getValue());
6963 else
6964 CmdArgs.push_back("19");
6965
6966 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6967 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6968 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6969 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6970 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6971
6972 // Pass -fmessage-length=.
6973 unsigned MessageLength = 0;
6974 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6975 StringRef V(A->getValue());
6976 if (V.getAsInteger(0, MessageLength))
6977 D.Diag(diag::err_drv_invalid_argument_to_option)
6978 << V << A->getOption().getName();
6979 } else {
6980 // If -fmessage-length=N was not specified, determine whether this is a
6981 // terminal and, if so, implicitly define -fmessage-length appropriately.
6982 MessageLength = llvm::sys::Process::StandardErrColumns();
6983 }
6984 if (MessageLength != 0)
6985 CmdArgs.push_back(
6986 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6987
6988 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6989 CmdArgs.push_back(
6990 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6991
6992 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6993 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6994 Twine(A->getValue(0))));
6995
6996 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6997 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6998 options::OPT_fvisibility_ms_compat)) {
6999 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
7000 A->render(Args, CmdArgs);
7001 } else {
7002 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
7003 CmdArgs.push_back("-fvisibility=hidden");
7004 CmdArgs.push_back("-ftype-visibility=default");
7005 }
7006 } else if (IsOpenMPDevice) {
7007 // When compiling for the OpenMP device we want protected visibility by
7008 // default. This prevents the device from accidentally preempting code on
7009 // the host, makes the system more robust, and improves performance.
7010 CmdArgs.push_back("-fvisibility=protected");
7011 }
7012
7013 // PS4/PS5 process these options in addClangTargetOptions.
7014 if (!RawTriple.isPS()) {
7015 if (const Arg *A =
7016 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
7017 options::OPT_fno_visibility_from_dllstorageclass)) {
7018 if (A->getOption().matches(
7019 options::OPT_fvisibility_from_dllstorageclass)) {
7020 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
7021 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
7022 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
7023 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
7024 Args.AddLastArg(CmdArgs,
7025 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
7026 }
7027 }
7028 }
7029
7030 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
7031 options::OPT_fno_visibility_inlines_hidden, false))
7032 CmdArgs.push_back("-fvisibility-inlines-hidden");
7033
7034 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
7035 options::OPT_fno_visibility_inlines_hidden_static_local_var);
7036
7037 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
7038 // -fvisibility-global-new-delete=force-hidden.
7039 if (const Arg *A =
7040 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
7041 D.Diag(diag::warn_drv_deprecated_arg)
7042 << A->getAsString(Args) << /*hasReplacement=*/true
7043 << "-fvisibility-global-new-delete=force-hidden";
7044 }
7045
7046 if (const Arg *A =
7047 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
7048 options::OPT_fvisibility_global_new_delete_hidden)) {
7049 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
7050 A->render(Args, CmdArgs);
7051 } else {
7052 assert(A->getOption().matches(
7053 options::OPT_fvisibility_global_new_delete_hidden));
7054 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
7055 }
7056 }
7057
7058 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
7059
7060 if (Args.hasFlag(options::OPT_fnew_infallible,
7061 options::OPT_fno_new_infallible, false))
7062 CmdArgs.push_back("-fnew-infallible");
7063
7064 if (Args.hasFlag(options::OPT_fno_operator_names,
7065 options::OPT_foperator_names, false))
7066 CmdArgs.push_back("-fno-operator-names");
7067
7068 // Forward -f (flag) options which we can pass directly.
7069 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
7070 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
7071 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
7072 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
7073 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
7074 options::OPT_fno_raw_string_literals);
7075
7076 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
7077 Triple.hasDefaultEmulatedTLS()))
7078 CmdArgs.push_back("-femulated-tls");
7079
7080 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
7081 options::OPT_fno_check_new);
7082
7083 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
7084 // FIXME: There's no reason for this to be restricted to some backend.
7085 // The backend code needs to be changed to include the appropriate function
7086 // calls automatically.
7087 if (!Triple.isX86() && !Triple.isAArch64() && !Triple.isRISCV())
7088 D.Diag(diag::err_drv_unsupported_opt_for_target)
7089 << A->getAsString(Args) << TripleStr;
7090 }
7091
7092 // AltiVec-like language extensions aren't relevant for assembling.
7093 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
7094 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
7095
7096 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
7097 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
7098
7099 // Forward flags for OpenMP. We don't do this if the current action is an
7100 // device offloading action other than OpenMP.
7101 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
7102 options::OPT_fno_openmp, false) &&
7103 !Args.hasFlag(options::OPT_foffload_via_llvm,
7104 options::OPT_fno_offload_via_llvm, false) &&
7107
7108 // Determine if target-fast optimizations should be enabled
7109 bool TargetFastUsed =
7110 Args.hasFlag(options::OPT_fopenmp_target_fast,
7111 options::OPT_fno_openmp_target_fast, OFastEnabled);
7112 switch (D.getOpenMPRuntime(Args)) {
7113 case Driver::OMPRT_OMP:
7115 // Clang can generate useful OpenMP code for these two runtime libraries.
7116 CmdArgs.push_back("-fopenmp");
7117
7118 // If no option regarding the use of TLS in OpenMP codegeneration is
7119 // given, decide a default based on the target. Otherwise rely on the
7120 // options and pass the right information to the frontend.
7121 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
7122 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
7123 CmdArgs.push_back("-fnoopenmp-use-tls");
7124 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7125 options::OPT_fno_openmp_simd);
7126 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
7127 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7128 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
7129 options::OPT_fno_openmp_extensions, /*Default=*/true))
7130 CmdArgs.push_back("-fno-openmp-extensions");
7131 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
7132 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
7133 // '-fopenmp-cuda-teams-reduction-recs-num=' is deprecated and has no
7134 // effect: the teams reduction buffer is sized at kernel launch by the
7135 // offload plugin to match the actual number of teams. Honoring a
7136 // smaller user-supplied value would silently truncate the buffer for
7137 // larger launches.
7138 if (Arg *A = Args.getLastArg(
7139 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ))
7140 D.Diag(diag::warn_drv_deprecated_custom)
7141 << A->getAsString(Args)
7142 << "the value is ignored; the teams reduction buffer is sized "
7143 "automatically at kernel launch";
7144 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
7145 options::OPT_fno_openmp_optimistic_collapse,
7146 /*Default=*/false))
7147 CmdArgs.push_back("-fopenmp-optimistic-collapse");
7148
7149 // When in OpenMP offloading mode with NVPTX target, forward
7150 // cuda-mode flag
7151 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
7152 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
7153 CmdArgs.push_back("-fopenmp-cuda-mode");
7154
7155 // When in OpenMP offloading mode, enable debugging on the device.
7156 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
7157 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
7158 options::OPT_fno_openmp_target_debug, /*Default=*/false))
7159 CmdArgs.push_back("-fopenmp-target-debug");
7160
7161 // When in OpenMP offloading mode, forward assumptions information about
7162 // thread and team counts in the device.
7163 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
7164 options::OPT_fno_openmp_assume_teams_oversubscription,
7165 /*Default=*/TargetFastUsed))
7166 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
7167 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
7168 options::OPT_fno_openmp_assume_threads_oversubscription,
7169 /*Default=*/TargetFastUsed))
7170 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
7171
7172 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
7173 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
7174 options::OPT_fno_openmp_assume_no_thread_state,
7175 /*Default=*/TargetFastUsed))
7176 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
7177
7178 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
7179 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
7180 options::OPT_fno_openmp_assume_no_nested_parallelism,
7181 /*Default=*/TargetFastUsed))
7182 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
7183
7184 // Handle -fopenmp-target-atomic-reduction.
7185 if (Args.hasFlag(options::OPT_fopenmp_target_atomic_reduction,
7186 options::OPT_fno_openmp_target_atomic_reduction,
7187 /*Default=*/false))
7188 CmdArgs.push_back("-fopenmp-target-atomic-reduction");
7189
7190 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
7191 CmdArgs.push_back("-fopenmp-offload-mandatory");
7192 if (Args.hasArg(options::OPT_fopenmp_force_usm))
7193 CmdArgs.push_back("-fopenmp-force-usm");
7194 break;
7195 default:
7196 // By default, if Clang doesn't know how to generate useful OpenMP code
7197 // for a specific runtime library, we just don't pass the '-fopenmp' flag
7198 // down to the actual compilation.
7199 // FIXME: It would be better to have a mode which *only* omits IR
7200 // generation based on the OpenMP support so that we get consistent
7201 // semantic analysis, etc.
7202 break;
7203 }
7204 } else {
7205 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
7206 options::OPT_fno_openmp_simd);
7207 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
7208 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
7209 options::OPT_fno_openmp_extensions);
7210 }
7211 // Forward the offload runtime change to code generation, liboffload implies
7212 // new driver. Otherwise, check if we should forward the new driver to change
7213 // offloading code generation.
7214 if (Args.hasFlag(options::OPT_foffload_via_llvm,
7215 options::OPT_fno_offload_via_llvm, false)) {
7216 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
7217 } else if (Args.hasFlag(options::OPT_offload_new_driver,
7218 options::OPT_no_offload_new_driver,
7219 C.getActiveOffloadKinds() != Action::OFK_None)) {
7220 CmdArgs.push_back("--offload-new-driver");
7221 }
7222
7223 const XRayArgs &XRay = TC.getXRayArgs(Args);
7224 XRay.addArgs(TC, Args, CmdArgs, InputType);
7225
7226 for (const auto &Filename :
7227 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
7228 if (D.getVFS().exists(Filename))
7229 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
7230 else
7231 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
7232 }
7233
7234 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
7235 StringRef S0 = A->getValue(), S = S0;
7236 unsigned Size, Offset = 0;
7237 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
7238 !Triple.isX86() && !Triple.isSystemZ() &&
7239 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
7240 Triple.getArch() == llvm::Triple::ppc64 ||
7241 Triple.getArch() == llvm::Triple::ppc64le)))
7242 D.Diag(diag::err_drv_unsupported_opt_for_target)
7243 << A->getAsString(Args) << TripleStr;
7244 else if (S.consumeInteger(10, Size) ||
7245 (!S.empty() &&
7246 (!S.consume_front(",") || S.consumeInteger(10, Offset))) ||
7247 (!S.empty() && (!S.consume_front(",") || S.empty())))
7248 D.Diag(diag::err_drv_invalid_argument_to_option)
7249 << S0 << A->getOption().getName();
7250 else if (Size < Offset)
7251 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
7252 else {
7253 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
7254 CmdArgs.push_back(Args.MakeArgString(
7255 "-fpatchable-function-entry-offset=" + Twine(Offset)));
7256 if (!S.empty())
7257 CmdArgs.push_back(
7258 Args.MakeArgString("-fpatchable-function-entry-section=" + S));
7259 }
7260 }
7261
7262 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
7263
7264 if (Args.hasArg(options::OPT_fms_secure_hotpatch_functions_file))
7265 Args.AddLastArg(CmdArgs, options::OPT_fms_secure_hotpatch_functions_file);
7266
7267 for (const auto &A :
7268 Args.getAllArgValues(options::OPT_fms_secure_hotpatch_functions_list))
7269 CmdArgs.push_back(
7270 Args.MakeArgString("-fms-secure-hotpatch-functions-list=" + Twine(A)));
7271
7272 if (TC.SupportsProfiling()) {
7273 Args.AddLastArg(CmdArgs, options::OPT_pg);
7274
7275 llvm::Triple::ArchType Arch = TC.getArch();
7276 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
7277 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
7278 A->render(Args, CmdArgs);
7279 else
7280 D.Diag(diag::err_drv_unsupported_opt_for_target)
7281 << A->getAsString(Args) << TripleStr;
7282 }
7283 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
7284 if (Arch == llvm::Triple::systemz)
7285 A->render(Args, CmdArgs);
7286 else
7287 D.Diag(diag::err_drv_unsupported_opt_for_target)
7288 << A->getAsString(Args) << TripleStr;
7289 }
7290 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
7291 if (Arch == llvm::Triple::systemz)
7292 A->render(Args, CmdArgs);
7293 else
7294 D.Diag(diag::err_drv_unsupported_opt_for_target)
7295 << A->getAsString(Args) << TripleStr;
7296 }
7297 }
7298
7299 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
7300 if (TC.getTriple().isOSzOS()) {
7301 D.Diag(diag::err_drv_unsupported_opt_for_target)
7302 << A->getAsString(Args) << TripleStr;
7303 }
7304 }
7305 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
7306 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
7307 D.Diag(diag::err_drv_unsupported_opt_for_target)
7308 << A->getAsString(Args) << TripleStr;
7309 }
7310 }
7311 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
7312 if (A->getOption().matches(options::OPT_p)) {
7313 A->claim();
7314 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
7315 CmdArgs.push_back("-pg");
7316 }
7317 }
7318
7319 // Reject AIX-specific link options on other targets.
7320 if (!TC.getTriple().isOSAIX()) {
7321 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
7322 options::OPT_mxcoff_build_id_EQ)) {
7323 D.Diag(diag::err_drv_unsupported_opt_for_target)
7324 << A->getSpelling() << TripleStr;
7325 }
7326 }
7327
7328 if (Args.getLastArg(options::OPT_fapple_kext) ||
7329 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
7330 CmdArgs.push_back("-fapple-kext");
7331
7332 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
7333 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7334 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7335 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7336 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7337 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7338 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7339 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_json);
7340 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7341 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7342 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7343
7344 if (const char *Name = C.getTimeTraceFile(&JA)) {
7345 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7346 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7347 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7348 }
7349
7350 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7351 CmdArgs.push_back("-ftrapv-handler");
7352 CmdArgs.push_back(A->getValue());
7353 }
7354
7355 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7356
7357 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7358 options::OPT_fno_finite_loops);
7359
7360 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7361 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7362 options::OPT_fno_unroll_loops);
7363 Args.AddLastArg(CmdArgs, options::OPT_floop_interchange,
7364 options::OPT_fno_loop_interchange);
7365 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
7366 options::OPT_fno_experimental_loop_fusion);
7367
7368 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7369
7370 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7371
7372 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7373 options::OPT_mno_speculative_load_hardening);
7374
7375 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7376 RenderSCPOptions(TC, Args, CmdArgs);
7377 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7378
7379 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7380
7381 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7382 options::OPT_mno_stackrealign);
7383
7384 if (const Arg *A = Args.getLastArg(options::OPT_mstack_alignment)) {
7385 StringRef Value = A->getValue();
7386 int64_t Alignment = 0;
7387 if (Value.getAsInteger(10, Alignment) || Alignment < 0)
7388 D.Diag(diag::err_drv_invalid_argument_to_option)
7389 << Value << A->getOption().getName();
7390 else if (Alignment & (Alignment - 1))
7391 D.Diag(diag::err_drv_alignment_not_power_of_two)
7392 << A->getAsString(Args) << Value;
7393 else
7394 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
7395 }
7396
7397 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7398 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7399
7400 if (!Size.empty())
7401 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7402 else
7403 CmdArgs.push_back("-mstack-probe-size=0");
7404 }
7405
7406 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7407 options::OPT_mno_stack_arg_probe);
7408
7409 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7410 options::OPT_mno_restrict_it)) {
7411 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7412 CmdArgs.push_back("-mllvm");
7413 CmdArgs.push_back("-arm-restrict-it");
7414 } else {
7415 CmdArgs.push_back("-mllvm");
7416 CmdArgs.push_back("-arm-default-it");
7417 }
7418 }
7419
7420 // Forward -cl options to -cc1
7421 RenderOpenCLOptions(Args, CmdArgs, InputType);
7422
7423 // Forward hlsl options to -cc1
7424 RenderHLSLOptions(D, Args, CmdArgs, InputType);
7425
7426 // Forward OpenACC options to -cc1
7427 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7428
7429 if (IsHIP) {
7430 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7431 options::OPT_fno_hip_new_launch_api, true))
7432 CmdArgs.push_back("-fhip-new-launch-api");
7433 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7434 options::OPT_fno_gpu_allow_device_init);
7435 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7436 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7437 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7438 options::OPT_fno_hip_kernel_arg_name);
7439 }
7440
7441 if ((IsCuda || IsHIP || IsSYCL) && IsRDCMode)
7442 CmdArgs.push_back("-fgpu-rdc");
7443
7444 if (IsCuda || IsHIP) {
7445 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7446 options::OPT_fno_gpu_defer_diag);
7447 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7448 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7449 false)) {
7450 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7451 CmdArgs.push_back("-fgpu-defer-diag");
7452 }
7453 }
7454
7455 // Forward --no-offloadlib to -cc1.
7456 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
7457 CmdArgs.push_back("--no-offloadlib");
7458
7459 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7460 CmdArgs.push_back(
7461 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7462
7463 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7464 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7465 SA->getValue()));
7466 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7467 // Emit IBT endbr64 instructions by default
7468 CmdArgs.push_back("-fcf-protection=branch");
7469 // jump-table can generate indirect jumps, which are not permitted
7470 CmdArgs.push_back("-fno-jump-tables");
7471 }
7472
7473 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7474 CmdArgs.push_back(
7475 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7476
7477 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7478
7479 // Forward -f options with positive and negative forms; we translate these by
7480 // hand. Do not propagate PGO options to the GPU-side compilations as the
7481 // profile info is for the host-side compilation only.
7482 if (!(IsCudaDevice || IsHIPDevice)) {
7483 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7484 auto *PGOArg = Args.getLastArg(
7485 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7486 options::OPT_fcs_profile_generate,
7487 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7488 options::OPT_fprofile_use_EQ);
7489 if (PGOArg)
7490 D.Diag(diag::err_drv_argument_not_allowed_with)
7491 << "SampleUse with PGO options";
7492
7493 StringRef fname = A->getValue();
7494 if (!llvm::sys::fs::exists(fname))
7495 D.Diag(diag::err_drv_no_such_file) << fname;
7496 else
7497 A->render(Args, CmdArgs);
7498 }
7499 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7500
7501 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7502 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7503 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7504 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7505 // off.
7506 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7507 options::OPT_fno_unique_internal_linkage_names, true))
7508 CmdArgs.push_back("-funique-internal-linkage-names");
7509 }
7510 }
7511 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7512
7513 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7514 options::OPT_fno_assume_sane_operator_new);
7515
7516 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7517 CmdArgs.push_back("-fapinotes");
7518 if (Args.hasFlag(options::OPT_fapinotes_modules,
7519 options::OPT_fno_apinotes_modules, false))
7520 CmdArgs.push_back("-fapinotes-modules");
7521 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7522
7523 if (Args.hasFlag(options::OPT_fswift_version_independent_apinotes,
7524 options::OPT_fno_swift_version_independent_apinotes, false))
7525 CmdArgs.push_back("-fswift-version-independent-apinotes");
7526
7527 // -fblocks=0 is default.
7528 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7529 TC.IsBlocksDefault()) ||
7530 (Args.hasArg(options::OPT_fgnu_runtime) &&
7531 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7532 !Args.hasArg(options::OPT_fno_blocks))) {
7533 CmdArgs.push_back("-fblocks");
7534
7535 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7536 CmdArgs.push_back("-fblocks-runtime-optional");
7537 }
7538
7539 // -fencode-extended-block-signature=1 is default.
7541 CmdArgs.push_back("-fencode-extended-block-signature");
7542
7543 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7544 options::OPT_fno_coro_aligned_allocation, false) &&
7545 types::isCXX(InputType))
7546 CmdArgs.push_back("-fcoro-aligned-allocation");
7547
7548 if (Args.hasFlag(options::OPT_fdefer_ts, options::OPT_fno_defer_ts,
7549 /*Default=*/false))
7550 CmdArgs.push_back("-fdefer-ts");
7551
7552 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7553 options::OPT_fno_double_square_bracket_attributes);
7554
7555 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7556 options::OPT_fno_access_control);
7557 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7558 options::OPT_fno_elide_constructors);
7559
7560 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7561
7562 if (KernelOrKext || (types::isCXX(InputType) &&
7563 (RTTIMode == ToolChain::RM_Disabled)))
7564 CmdArgs.push_back("-fno-rtti");
7565
7566 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7567 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7568 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7569 CmdArgs.push_back("-fshort-enums");
7570
7571 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7572
7573 // -fuse-cxa-atexit is default.
7574 if (!Args.hasFlag(
7575 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7576 !RawTriple.isOSAIX() &&
7577 (!RawTriple.isOSWindows() ||
7578 RawTriple.isWindowsCygwinEnvironment()) &&
7579 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7580 RawTriple.hasEnvironment())) ||
7581 KernelOrKext)
7582 CmdArgs.push_back("-fno-use-cxa-atexit");
7583
7584 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7585 options::OPT_fno_register_global_dtors_with_atexit,
7586 RawTriple.isOSDarwin() && !KernelOrKext))
7587 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7588
7589 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7590 options::OPT_fno_use_line_directives);
7591
7592 // -fno-minimize-whitespace is default.
7593 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7594 options::OPT_fno_minimize_whitespace, false)) {
7595 types::ID InputType = Inputs[0].getType();
7596 if (!isDerivedFromC(InputType))
7597 D.Diag(diag::err_drv_opt_unsupported_input_type)
7598 << "-fminimize-whitespace" << types::getTypeName(InputType);
7599 CmdArgs.push_back("-fminimize-whitespace");
7600 }
7601
7602 // -fno-keep-system-includes is default.
7603 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7604 options::OPT_fno_keep_system_includes, false)) {
7605 types::ID InputType = Inputs[0].getType();
7606 if (!isDerivedFromC(InputType))
7607 D.Diag(diag::err_drv_opt_unsupported_input_type)
7608 << "-fkeep-system-includes" << types::getTypeName(InputType);
7609 CmdArgs.push_back("-fkeep-system-includes");
7610 }
7611
7612 // -fms-extensions=0 is default.
7613 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7614 IsWindowsMSVC || IsUEFI))
7615 CmdArgs.push_back("-fms-extensions");
7616
7617 // -fms-compatibility=0 is default.
7618 bool IsMSVCCompat = Args.hasFlag(
7619 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7620 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7621 options::OPT_fno_ms_extensions, true)));
7622 if (IsMSVCCompat) {
7623 CmdArgs.push_back("-fms-compatibility");
7624 if (!types::isCXX(Input.getType()) &&
7625 Args.hasArg(options::OPT_fms_define_stdc))
7626 CmdArgs.push_back("-fms-define-stdc");
7627 }
7628
7629 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7630 // clang and flang.
7631 renderCommonIntegerOverflowOptions(Args, CmdArgs, IsMSVCCompat);
7632
7633 // -fms-anonymous-structs is disabled by default.
7634 // Determine whether to enable Microsoft named anonymous struct/union support.
7635 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7636 // where the feature can be:
7637 // - Explicitly enabled via -fms-anonymous-structs.
7638 // - Explicitly disabled via fno-ms-anonymous-structs
7639 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7640 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7641 //
7642 // When multiple relevent options are present, the last option on the command
7643 // line takes precedence. This allows users to selectively override implicit
7644 // enablement. Examples:
7645 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7646 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7647 auto MSAnonymousStructsOptionToUseOrNull =
7648 [](const ArgList &Args) -> const char * {
7649 const char *Option = nullptr;
7650 constexpr const char *Enable = "-fms-anonymous-structs";
7651 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7652
7653 // Iterate through all arguments in order to implement "last flag wins".
7654 for (const Arg *A : Args) {
7655 switch (A->getOption().getID()) {
7656 case options::OPT_fms_anonymous_structs:
7657 A->claim();
7658 Option = Enable;
7659 break;
7660 case options::OPT_fno_ms_anonymous_structs:
7661 A->claim();
7662 Option = Disable;
7663 break;
7664 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7665 // feature.
7666 case options::OPT_fms_extensions:
7667 case options::OPT_fms_compatibility:
7668 Option = Enable;
7669 break;
7670 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7671 // disables the feature.
7672 case options::OPT_fno_ms_extensions:
7673 case options::OPT_fno_ms_compatibility:
7674 Option = Disable;
7675 break;
7676 default:
7677 break;
7678 }
7679 }
7680 return Option;
7681 };
7682
7683 // Only pass a flag to CC1 if a relevant option was seen
7684 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7685 CmdArgs.push_back(MSAnonOpt);
7686
7687 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7688 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7689 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7690
7691 // Handle -fgcc-version, if present.
7692 VersionTuple GNUCVer;
7693 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7694 // Check that the version has 1 to 3 components and the minor and patch
7695 // versions fit in two decimal digits.
7696 StringRef Val = A->getValue();
7697 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7698 bool Invalid = GNUCVer.tryParse(Val);
7699 unsigned Minor = GNUCVer.getMinor().value_or(0);
7700 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7701 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7702 D.Diag(diag::err_drv_invalid_value)
7703 << A->getAsString(Args) << A->getValue();
7704 }
7705 } else if (!IsMSVCCompat) {
7706 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7707 GNUCVer = VersionTuple(4, 2, 1);
7708 }
7709 if (!GNUCVer.empty()) {
7710 CmdArgs.push_back(
7711 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7712 }
7713
7714 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7715 if (!MSVT.empty())
7716 CmdArgs.push_back(
7717 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7718
7719 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7720 if (ImplyVCPPCVer) {
7721 StringRef LanguageStandard;
7722 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7723 Std = StdArg;
7724 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7725 .Case("c11", "-std=c11")
7726 .Case("c17", "-std=c17")
7727 // If you add cases below for spellings that are
7728 // not in LangStandards.def, update
7729 // TransferableCommand::tryParseStdArg() in
7730 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7731 // to match.
7732 // TODO: add c23 when MSVC supports it.
7733 .Case("clatest", "-std=c23")
7734 .Default("");
7735 if (LanguageStandard.empty())
7736 D.Diag(clang::diag::warn_drv_unused_argument)
7737 << StdArg->getAsString(Args);
7738 }
7739 CmdArgs.push_back(LanguageStandard.data());
7740 }
7741 if (ImplyVCPPCXXVer) {
7742 StringRef LanguageStandard;
7743 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7744 Std = StdArg;
7745 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7746 .Case("c++14", "-std=c++14")
7747 .Case("c++17", "-std=c++17")
7748 .Case("c++20", "-std=c++20")
7749 // If you add cases below for spellings that are
7750 // not in LangStandards.def, update
7751 // TransferableCommand::tryParseStdArg() in
7752 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7753 // to match.
7754 // TODO add c++23, c++26, c++29 when MSVC supports
7755 // it.
7756 .Case("c++23preview", "-std=c++23")
7757 .Case("c++26preview", "-std=c++26")
7758 .Case("c++latest", "-std=c++2d")
7759 .Default("");
7760 if (IsSYCL) {
7761 const LangStandard *LangStd =
7762 LangStandard::getLangStandardForName(StdArg->getValue());
7763 if (LangStd) {
7764 // Use of /std: with 'C' is not supported for SYCL.
7765 if (LangStd->getLanguage() == Language::C)
7766 D.Diag(diag::err_drv_argument_not_allowed_with)
7767 << StdArg->getAsString(Args) << "-fsycl";
7768 // SYCL requires C++17 or later.
7769 else if (LangStd->isCPlusPlus() && !LangStd->isCPlusPlus17())
7770 D.Diag(diag::err_drv_sycl_requires_cxx17)
7771 << StdArg->getAsString(Args);
7772 }
7773 }
7774 if (LanguageStandard.empty())
7775 D.Diag(clang::diag::warn_drv_unused_argument)
7776 << StdArg->getAsString(Args);
7777 }
7778
7779 if (LanguageStandard.empty()) {
7780 if (IsSYCL)
7781 // For SYCL, C++17 is the default.
7782 LanguageStandard = "-std=c++17";
7783 else if (IsMSVC2015Compatible)
7784 LanguageStandard = "-std=c++14";
7785 else
7786 LanguageStandard = "-std=c++11";
7787 }
7788
7789 CmdArgs.push_back(LanguageStandard.data());
7790 }
7791
7792 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7793 options::OPT_fno_borland_extensions);
7794
7795 // -fno-declspec is default, except for PS4/PS5.
7796 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7797 RawTriple.isPS()))
7798 CmdArgs.push_back("-fdeclspec");
7799 else if (Args.hasArg(options::OPT_fno_declspec))
7800 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7801
7802 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7803 // than 19.
7804 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7805 options::OPT_fno_threadsafe_statics,
7806 !types::isOpenCL(InputType) &&
7807 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7808 CmdArgs.push_back("-fno-threadsafe-statics");
7809
7810 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7811 true))
7812 CmdArgs.push_back("-fno-ms-tls-guards");
7813
7814 // Add -fno-assumptions, if it was specified.
7815 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7816 true))
7817 CmdArgs.push_back("-fno-assumptions");
7818
7819 // -fgnu-keywords default varies depending on language; only pass if
7820 // specified.
7821 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7822 options::OPT_fno_gnu_keywords);
7823
7824 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7825 options::OPT_fno_gnu89_inline);
7826
7827 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7828 options::OPT_finline_hint_functions,
7829 options::OPT_fno_inline_functions);
7830 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7831 if (A->getOption().matches(options::OPT_fno_inline))
7832 A->render(Args, CmdArgs);
7833 } else if (InlineArg) {
7834 InlineArg->render(Args, CmdArgs);
7835 }
7836
7837 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7838
7839 // FIXME: Find a better way to determine whether we are in C++20.
7840 bool HaveCxx20 =
7841 Std &&
7842 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7843 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7844 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7845 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7846 Std->containsValue("c++23preview") || Std->containsValue("c++2c") ||
7847 Std->containsValue("gnu++2c") || Std->containsValue("c++26") ||
7848 Std->containsValue("gnu++26") || Std->containsValue("c++26preview") ||
7849 Std->containsValue("c++2d") || Std->containsValue("gnu++2d") ||
7850 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7851 bool HaveModules =
7852 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7853
7854 // -fdelayed-template-parsing is default when targeting MSVC.
7855 // Many old Windows SDK versions require this to parse.
7856 //
7857 // According to
7858 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7859 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7860 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7861 // not enable -fdelayed-template-parsing by default after C++20.
7862 //
7863 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7864 // able to disable this by default at some point.
7865 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7866 options::OPT_fno_delayed_template_parsing,
7867 IsWindowsMSVC && !HaveCxx20)) {
7868 if (HaveCxx20)
7869 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7870
7871 CmdArgs.push_back("-fdelayed-template-parsing");
7872 }
7873
7874 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7875 options::OPT_fno_pch_validate_input_files_content, false))
7876 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7877 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7878 options::OPT_fno_pch_instantiate_templates, false))
7879 CmdArgs.push_back("-fpch-instantiate-templates");
7880 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7881 false))
7882 CmdArgs.push_back("-fmodules-codegen");
7883 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7884 false))
7885 CmdArgs.push_back("-fmodules-debuginfo");
7886
7887 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7888 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7889 Input, CmdArgs);
7890
7891 if (types::isObjC(Input.getType()) &&
7892 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7893 options::OPT_fno_objc_encode_cxx_class_template_spec,
7894 !Runtime.isNeXTFamily()))
7895 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7896
7897 if (Args.hasFlag(options::OPT_fapplication_extension,
7898 options::OPT_fno_application_extension, false))
7899 CmdArgs.push_back("-fapplication-extension");
7900
7901 // Handle GCC-style exception args.
7902 bool EH = false;
7903 if (!C.getDriver().IsCLMode())
7904 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext,
7905 IsDeviceOffloadAction, Runtime, CmdArgs);
7906
7907 // Handle exception personalities
7908 Arg *A = Args.getLastArg(
7909 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7910 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7911 if (A) {
7912 const Option &Opt = A->getOption();
7913 if (Opt.matches(options::OPT_fsjlj_exceptions))
7914 CmdArgs.push_back("-exception-model=sjlj");
7915 if (Opt.matches(options::OPT_fseh_exceptions))
7916 CmdArgs.push_back("-exception-model=seh");
7917 if (Opt.matches(options::OPT_fdwarf_exceptions))
7918 CmdArgs.push_back("-exception-model=dwarf");
7919 if (Opt.matches(options::OPT_fwasm_exceptions))
7920 CmdArgs.push_back("-exception-model=wasm");
7921 } else {
7922 switch (TC.GetExceptionModel(Args)) {
7923 default:
7924 break;
7925 case llvm::ExceptionHandling::DwarfCFI:
7926 CmdArgs.push_back("-exception-model=dwarf");
7927 break;
7928 case llvm::ExceptionHandling::SjLj:
7929 CmdArgs.push_back("-exception-model=sjlj");
7930 break;
7931 case llvm::ExceptionHandling::WinEH:
7932 CmdArgs.push_back("-exception-model=seh");
7933 break;
7934 }
7935 }
7936
7937 // Unwind information version for x64 Windows.
7938 // Forward the new unified flag if present, otherwise translate legacy flags.
7939 if (const Arg *A = Args.getLastArg(options::OPT_winx64_eh_unwind_EQ)) {
7940 A->claim();
7941 CmdArgs.push_back(
7942 Args.MakeArgString(Twine("-fwinx64-eh-unwind=") + A->getValue()));
7943 } else if (const Arg *A =
7944 Args.getLastArg(options::OPT_winx64_eh_unwindv2_EQ)) {
7945 A->claim();
7946 StringRef Val = A->getValue();
7947 if (Val == "best-effort")
7948 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
7949 else if (Val == "required")
7950 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
7951 // "disabled" maps to v1 default, nothing to forward.
7952 else if (Val != "disabled")
7953 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
7954 }
7955
7956 // Control Flow Guard mechanism for Windows.
7957 Args.AddLastArg(CmdArgs, options::OPT_win_cfg_mechanism);
7958
7959 // C++ "sane" operator new.
7960 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7961 options::OPT_fno_assume_sane_operator_new);
7962
7963 // -fassume-unique-vtables is on by default.
7964 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7965 options::OPT_fno_assume_unique_vtables);
7966
7967 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7968 // by default.
7969 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7970 options::OPT_fno_sized_deallocation);
7971
7972 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7973 // by default.
7974 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7975 options::OPT_fno_aligned_allocation,
7976 options::OPT_faligned_new_EQ)) {
7977 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7978 CmdArgs.push_back("-fno-aligned-allocation");
7979 else
7980 CmdArgs.push_back("-faligned-allocation");
7981 }
7982
7983 // The default new alignment can be specified using a dedicated option or via
7984 // a GCC-compatible option that also turns on aligned allocation.
7985 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7986 options::OPT_faligned_new_EQ))
7987 CmdArgs.push_back(
7988 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7989
7990 // -fconstant-cfstrings is default, and may be subject to argument translation
7991 // on Darwin.
7992 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7993 options::OPT_fno_constant_cfstrings, true) ||
7994 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7995 options::OPT_mno_constant_cfstrings, true))
7996 CmdArgs.push_back("-fno-constant-cfstrings");
7997
7998 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7999 options::OPT_fno_pascal_strings);
8000
8001 // Honor -fpack-struct= and -fpack-struct, if given. Note that
8002 // -fno-pack-struct doesn't apply to -fpack-struct=.
8003 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
8004 CmdArgs.push_back(
8005 Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
8006 } else if (Args.hasFlag(options::OPT_fpack_struct,
8007 options::OPT_fno_pack_struct, false)) {
8008 CmdArgs.push_back("-fpack-struct=1");
8009 }
8010
8011 // Handle -fmax-type-align=N and -fno-type-align
8012 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
8013 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
8014 if (!SkipMaxTypeAlign) {
8015 std::string MaxTypeAlignStr = "-fmax-type-align=";
8016 MaxTypeAlignStr += A->getValue();
8017 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8018 }
8019 } else if (RawTriple.isOSDarwin()) {
8020 if (!SkipMaxTypeAlign) {
8021 std::string MaxTypeAlignStr = "-fmax-type-align=16";
8022 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
8023 }
8024 }
8025
8026 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
8027 CmdArgs.push_back("-Qn");
8028
8029 // -fno-common is the default, set -fcommon only when that flag is set.
8030 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
8031
8032 // -fsigned-bitfields is default, and clang doesn't yet support
8033 // -funsigned-bitfields.
8034 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
8035 options::OPT_funsigned_bitfields, true))
8036 D.Diag(diag::warn_drv_clang_unsupported)
8037 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
8038
8039 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
8040 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
8041 D.Diag(diag::err_drv_clang_unsupported)
8042 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
8043
8044 // -finput_charset=UTF-8 is default. Reject others
8045 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
8046 StringRef value = inputCharset->getValue();
8047 if (!value.equals_insensitive("utf-8"))
8048 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
8049 << value;
8050 }
8051
8052 // -fexec_charset=UTF-8 is default. Reject others
8053 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
8054 StringRef value = execCharset->getValue();
8055 if (!value.equals_insensitive("utf-8"))
8056 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
8057 << value;
8058 }
8059
8060 RenderDiagnosticsOptions(D, Args, CmdArgs);
8061
8062 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
8063 options::OPT_fno_asm_blocks);
8064
8065 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
8066 options::OPT_fno_gnu_inline_asm);
8067
8068 handleVectorizeLoopsArgs(Args, CmdArgs);
8069 handleVectorizeSLPArgs(Args, CmdArgs);
8070
8071 StringRef VecWidth = parseMPreferVectorWidthOption(D.getDiags(), Args);
8072 if (!VecWidth.empty())
8073 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + VecWidth));
8074
8075 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
8076 Args.AddLastArg(CmdArgs,
8077 options::OPT_fsanitize_undefined_strip_path_components_EQ);
8078
8079 // -fdollars-in-identifiers default varies depending on platform and
8080 // language; only pass if specified.
8081 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
8082 options::OPT_fno_dollars_in_identifiers)) {
8083 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
8084 CmdArgs.push_back("-fdollars-in-identifiers");
8085 else
8086 CmdArgs.push_back("-fno-dollars-in-identifiers");
8087 }
8088
8089 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
8090 options::OPT_fno_apple_pragma_pack);
8091
8092 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
8093 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
8094 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
8095
8096 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
8097 options::OPT_fno_rewrite_imports, false);
8098 if (RewriteImports)
8099 CmdArgs.push_back("-frewrite-imports");
8100
8101 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
8102 options::OPT_fno_directives_only);
8103
8104 // Enable rewrite includes if the user's asked for it or if we're generating
8105 // diagnostics.
8106 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
8107 // nice to enable this when doing a crashdump for modules as well.
8108 if (Args.hasFlag(options::OPT_frewrite_includes,
8109 options::OPT_fno_rewrite_includes, false) ||
8110 (C.isForDiagnostics() && !HaveModules))
8111 CmdArgs.push_back("-frewrite-includes");
8112
8113 if (Args.hasFlag(options::OPT_fzos_extensions,
8114 options::OPT_fno_zos_extensions, false))
8115 CmdArgs.push_back("-fzos-extensions");
8116 else if (Args.hasArg(options::OPT_fno_zos_extensions))
8117 CmdArgs.push_back("-fno-zos-extensions");
8118
8119 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
8120 if (Arg *A = Args.getLastArg(options::OPT_traditional,
8121 options::OPT_traditional_cpp)) {
8123 CmdArgs.push_back("-traditional-cpp");
8124 else
8125 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
8126 }
8127
8128 Args.AddLastArg(CmdArgs, options::OPT_dM);
8129 Args.AddLastArg(CmdArgs, options::OPT_dD);
8130 Args.AddLastArg(CmdArgs, options::OPT_dI);
8131
8132 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
8133
8134 Args.AddLastArg(CmdArgs, options::OPT__ssaf_extract_summaries);
8135 Args.AddLastArg(CmdArgs, options::OPT__ssaf_tu_summary_file);
8136 Args.AddLastArg(CmdArgs, options::OPT__ssaf_compilation_unit_id);
8137 Args.AddLastArg(CmdArgs, options::OPT__ssaf_include_local_entities);
8138 Args.AddLastArg(CmdArgs, options::OPT__ssaf_no_extract_from_system_headers);
8139 Args.AddLastArg(CmdArgs, options::OPT__ssaf_source_transformation);
8140 Args.AddLastArg(CmdArgs, options::OPT__ssaf_global_scope_analysis_result);
8141 Args.AddLastArg(CmdArgs, options::OPT__ssaf_link_unit_id);
8142 Args.AddLastArg(CmdArgs, options::OPT__ssaf_src_edit_file);
8143 Args.AddLastArg(CmdArgs, options::OPT__ssaf_transformation_report_file);
8144
8145 // Handle serialized diagnostics.
8146 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
8147 CmdArgs.push_back("-serialize-diagnostic-file");
8148 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
8149 }
8150
8151 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
8152 CmdArgs.push_back("-fretain-comments-from-system-headers");
8153
8154 if (Arg *A = Args.getLastArg(options::OPT_fextend_variable_liveness_EQ)) {
8155 A->render(Args, CmdArgs);
8156 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group);
8157 A && A->containsValue("g")) {
8158 // Set -fextend-variable-liveness=all by default at -Og.
8159 CmdArgs.push_back("-fextend-variable-liveness=all");
8160 }
8161
8162 // Forward -fcomment-block-commands to -cc1.
8163 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
8164 // Forward -fparse-all-comments to -cc1.
8165 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
8166
8167 // Turn -fplugin=name.so into -load name.so
8168 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
8169 CmdArgs.push_back("-load");
8170 CmdArgs.push_back(A->getValue());
8171 A->claim();
8172 }
8173
8174 // Turn -fplugin-arg-pluginname-key=value into
8175 // -plugin-arg-pluginname key=value
8176 // GCC has an actual plugin_argument struct with key/value pairs that it
8177 // passes to its plugins, but we don't, so just pass it on as-is.
8178 //
8179 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
8180 // argument key are allowed to contain dashes. GCC therefore only
8181 // allows dashes in the key. We do the same.
8182 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
8183 auto ArgValue = StringRef(A->getValue());
8184 auto FirstDashIndex = ArgValue.find('-');
8185 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
8186 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
8187
8188 A->claim();
8189 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
8190 if (PluginName.empty()) {
8191 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
8192 } else {
8193 D.Diag(diag::warn_drv_missing_plugin_arg)
8194 << PluginName << A->getAsString(Args);
8195 }
8196 continue;
8197 }
8198
8199 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
8200 CmdArgs.push_back(Args.MakeArgString(Arg));
8201 }
8202
8203 // Forward -fpass-plugin=name.so to -cc1.
8204 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
8205 CmdArgs.push_back(
8206 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
8207 A->claim();
8208 }
8209
8210 // Forward --vfsoverlay to -cc1.
8211 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
8212 CmdArgs.push_back("--vfsoverlay");
8213 CmdArgs.push_back(A->getValue());
8214 A->claim();
8215 }
8216
8217 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
8218 options::OPT_fno_safe_buffer_usage_suggestions);
8219
8220 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
8221 options::OPT_fno_experimental_late_parse_attributes);
8222
8223 if (Args.hasFlag(options::OPT_funique_source_file_names,
8224 options::OPT_fno_unique_source_file_names, false)) {
8225 if (Arg *A = Args.getLastArg(options::OPT_unique_source_file_identifier_EQ))
8226 A->render(Args, CmdArgs);
8227 else
8228 CmdArgs.push_back(Args.MakeArgString(
8229 Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
8230 }
8231
8232 if (Args.hasFlag(
8233 options::OPT_fexperimental_allow_pointer_field_protection_attr,
8234 options::OPT_fno_experimental_allow_pointer_field_protection_attr,
8235 false) ||
8236 Args.hasFlag(options::OPT_fexperimental_pointer_field_protection_abi,
8237 options::OPT_fno_experimental_pointer_field_protection_abi,
8238 false))
8239 CmdArgs.push_back("-fexperimental-allow-pointer-field-protection-attr");
8240
8241 if (!IsCudaDevice) {
8242 Args.addOptInFlag(
8243 CmdArgs, options::OPT_fexperimental_pointer_field_protection_abi,
8244 options::OPT_fno_experimental_pointer_field_protection_abi);
8245 Args.addOptInFlag(
8246 CmdArgs, options::OPT_fexperimental_pointer_field_protection_tagged,
8247 options::OPT_fno_experimental_pointer_field_protection_tagged);
8248 }
8249
8250 // Setup statistics file output.
8251 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
8252 if (!StatsFile.empty()) {
8253 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
8255 CmdArgs.push_back("-stats-file-append");
8256 }
8257
8258 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
8259 // parser.
8260 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
8261 Arg->claim();
8262 // -finclude-default-header flag is for preprocessor,
8263 // do not pass it to other cc1 commands when save-temps is enabled
8264 if (C.getDriver().isSaveTempsEnabled() &&
8266 if (StringRef(Arg->getValue()) == "-finclude-default-header")
8267 continue;
8268 }
8269 CmdArgs.push_back(Arg->getValue());
8270 }
8271 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
8272 A->claim();
8273
8274 // We translate this by hand to the -cc1 argument, since nightly test uses
8275 // it and developers have been trained to spell it with -mllvm. Both
8276 // spellings are now deprecated and should be removed.
8277 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
8278 CmdArgs.push_back("-disable-llvm-optzns");
8279 } else {
8280 A->render(Args, CmdArgs);
8281 }
8282 }
8283
8284 // This needs to run after -Xclang argument forwarding to pick up the target
8285 // features enabled through -Xclang -target-feature flags.
8286 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
8287
8288 Args.AddLastArg(CmdArgs, options::OPT_falloc_token_max_EQ);
8289
8290#if CLANG_ENABLE_CIR
8291 // Forward -mmlir arguments to to the MLIR option parser.
8292 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
8293 A->claim();
8294 A->render(Args, CmdArgs);
8295 }
8296#endif // CLANG_ENABLE_CIR
8297
8298 // With -save-temps, we want to save the unoptimized bitcode output from the
8299 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
8300 // by the frontend.
8301 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
8302 // has slightly different breakdown between stages.
8303 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
8304 // pristine IR generated by the frontend. Ideally, a new compile action should
8305 // be added so both IR can be captured.
8306 if ((C.getDriver().isSaveTempsEnabled() ||
8308 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
8310 CmdArgs.push_back("-disable-llvm-passes");
8311
8312 Args.AddAllArgs(CmdArgs, options::OPT_undef);
8313
8314 const char *Exec = D.getDriverProgramPath();
8315
8316 // Optionally embed the -cc1 level arguments into the debug info or a
8317 // section, for build analysis.
8318 // Also record command line arguments into the debug info if
8319 // -grecord-gcc-switches options is set on.
8320 // By default, -gno-record-gcc-switches is set on and no recording.
8321 auto GRecordSwitches = false;
8322 auto FRecordSwitches = false;
8323 bool DXRecordSwitches = false;
8324 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches,
8325 DXRecordSwitches)) {
8326 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
8327 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
8328 CmdArgs.push_back("-dwarf-debug-flags");
8329 CmdArgs.push_back(FlagsArgString);
8330 }
8331 if (FRecordSwitches) {
8332 CmdArgs.push_back("-record-command-line");
8333 CmdArgs.push_back(FlagsArgString);
8334 }
8335 if (DXRecordSwitches) {
8336 CmdArgs.push_back("-fdx-record-command-line");
8337 CmdArgs.push_back(FlagsArgString);
8338 }
8339 }
8340
8341 // Host-side offloading compilation receives all device-side outputs. Include
8342 // them in the host compilation depending on the target. If the host inputs
8343 // are not empty we use the new-driver scheme, otherwise use the old scheme.
8344 if ((IsCuda || IsHIP) && !UsesLLVMOffloading && CudaDeviceInput) {
8345 CmdArgs.push_back("-foffload-include-binary");
8346 CmdArgs.push_back(CudaDeviceInput->getFilename());
8347 } else if (!HostOffloadingInputs.empty()) {
8348 if ((IsCuda || IsHIP) &&
8349 (!IsRDCMode || Args.hasArg(options::OPT_cuda_emit_nvcc_abi)) &&
8350 !UsesLLVMOffloading) {
8351 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
8352 CmdArgs.push_back("-foffload-include-binary");
8353 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
8354 } else {
8355 for (const InputInfo Input : HostOffloadingInputs)
8356 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
8357 TC.getInputFilename(Input)));
8358 }
8359 }
8360
8361 if (IsCuda) {
8362 if (Args.hasArg(options::OPT_cuda_emit_nvcc_abi))
8363 CmdArgs.push_back("--cuda-emit-nvcc-abi");
8364 }
8365
8366 if (IsCuda || IsHIP) {
8367 // Determine the original source input.
8368 const Action *SourceAction = &JA;
8369 while (SourceAction->getKind() != Action::InputClass) {
8370 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
8371 SourceAction = SourceAction->getInputs()[0];
8372 }
8373 auto CUID = cast<InputAction>(SourceAction)->getId();
8374 if (!CUID.empty())
8375 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
8376
8377 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
8378 // be overriden by -fno-gpu-approx-transcendentals.
8379 bool UseApproxTranscendentals = Args.hasFlag(
8380 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
8381 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
8382 options::OPT_fno_gpu_approx_transcendentals,
8383 UseApproxTranscendentals))
8384 CmdArgs.push_back("-fgpu-approx-transcendentals");
8385 } else {
8386 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
8387 options::OPT_fno_gpu_approx_transcendentals);
8388 }
8389
8390 if (IsHIP) {
8391 CmdArgs.push_back("-fcuda-allow-variadic-functions");
8392 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
8393 }
8394
8395 Args.AddAllArgs(CmdArgs,
8396 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
8397
8398 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
8399 options::OPT_fno_offload_uniform_block);
8400
8401 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
8402 options::OPT_fno_offload_implicit_host_device_templates);
8403
8404 if (IsCudaDevice || IsHIPDevice) {
8405 StringRef InlineThresh =
8406 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
8407 if (!InlineThresh.empty()) {
8408 std::string ArgStr =
8409 std::string("-inline-threshold=") + InlineThresh.str();
8410 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
8411 }
8412 }
8413
8414 if (IsHIPDevice)
8415 Args.addOptOutFlag(CmdArgs,
8416 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
8417 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
8418
8419 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
8420 // to specify the result of the compile phase on the host, so the meaningful
8421 // device declarations can be identified. Also, -fopenmp-is-target-device is
8422 // passed along to tell the frontend that it is generating code for a device,
8423 // so that only the relevant declarations are emitted.
8424 if (IsOpenMPDevice) {
8425 CmdArgs.push_back("-fopenmp-is-target-device");
8426 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
8427 if (Args.hasArg(options::OPT_foffload_via_llvm))
8428 CmdArgs.push_back("-fcuda-is-device");
8429
8430 if (OpenMPDeviceInput) {
8431 CmdArgs.push_back("-fopenmp-host-ir-file-path");
8432 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
8433 }
8434 }
8435
8436 if (Triple.isAMDGPU() ||
8437 (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD)) {
8438 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
8439
8440 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
8441 options::OPT_mno_unsafe_fp_atomics);
8442 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
8443 options::OPT_mno_amdgpu_ieee);
8444 }
8445
8446 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8447
8448 if (Args.hasFlag(options::OPT_fdevirtualize_speculatively,
8449 options::OPT_fno_devirtualize_speculatively,
8450 /*Default value*/ false))
8451 CmdArgs.push_back("-fdevirtualize-speculatively");
8452
8453 bool VirtualFunctionElimination =
8454 Args.hasFlag(options::OPT_fvirtual_function_elimination,
8455 options::OPT_fno_virtual_function_elimination, false);
8456 if (VirtualFunctionElimination) {
8457 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8458 // in the future).
8459 if (LTOMode != LTOK_Full)
8460 D.Diag(diag::err_drv_argument_only_allowed_with)
8461 << "-fvirtual-function-elimination"
8462 << "-flto=full";
8463
8464 CmdArgs.push_back("-fvirtual-function-elimination");
8465 }
8466
8467 // VFE requires whole-program-vtables, and enables it by default.
8468 bool WholeProgramVTables = Args.hasFlag(
8469 options::OPT_fwhole_program_vtables,
8470 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
8471 if (VirtualFunctionElimination && !WholeProgramVTables) {
8472 D.Diag(diag::err_drv_argument_not_allowed_with)
8473 << "-fno-whole-program-vtables"
8474 << "-fvirtual-function-elimination";
8475 }
8476
8477 if (WholeProgramVTables) {
8478 // PS4 uses the legacy LTO API, which does not support this feature in
8479 // ThinLTO mode.
8480 bool IsPS4 = getToolChain().getTriple().isPS4();
8481
8482 // Check if we passed LTO options but they were suppressed because this is a
8483 // device offloading action, or we passed device offload LTO options which
8484 // were suppressed because this is not the device offload action.
8485 // Check if we are using PS4 in regular LTO mode.
8486 // Otherwise, issue an error.
8487
8488 auto OtherLTOMode = TC.getLTOMode(
8489 Args, IsDeviceOffloadAction ? Action::OFK_None
8490 : static_cast<Action::OffloadKind>(
8491 C.getActiveOffloadKinds()));
8492 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8493
8494 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8495 (IsPS4 && !UnifiedLTO && (TC.getLTOMode(Args) != LTOK_Full)))
8496 D.Diag(diag::err_drv_argument_only_allowed_with)
8497 << "-fwhole-program-vtables"
8498 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8499
8500 // Propagate -fwhole-program-vtables if this is an LTO compile.
8501 if (IsUsingLTO)
8502 CmdArgs.push_back("-fwhole-program-vtables");
8503 }
8504
8505 bool DefaultsSplitLTOUnit =
8506 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8507 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8508 (!Triple.isPS4() && UnifiedLTO);
8509 bool SplitLTOUnit =
8510 Args.hasFlag(options::OPT_fsplit_lto_unit,
8511 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
8512 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8513 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8514 << "-fsanitize=cfi";
8515 if (SplitLTOUnit)
8516 CmdArgs.push_back("-fsplit-lto-unit");
8517
8518 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8519 options::OPT_fno_fat_lto_objects)) {
8520 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8521 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8522 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8523 D.Diag(diag::err_drv_unsupported_opt_for_target)
8524 << A->getAsString(Args) << TC.getTripleString();
8525 }
8526 CmdArgs.push_back(Args.MakeArgString(
8527 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8528 CmdArgs.push_back("-flto-unit");
8529 CmdArgs.push_back("-ffat-lto-objects");
8530 A->render(Args, CmdArgs);
8531 }
8532 }
8533
8534 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8535
8536 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8537 options::OPT_fno_force_enable_int128)) {
8538 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8539 CmdArgs.push_back("-fforce-enable-int128");
8540 }
8541
8542 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8543 options::OPT_fno_keep_static_consts);
8544 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8545 options::OPT_fno_keep_persistent_storage_variables);
8546 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8547 options::OPT_fno_complete_member_pointers);
8548 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8549 A->render(Args, CmdArgs);
8550
8551 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8552
8553 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8554
8555 if (Triple.isAArch64() &&
8556 (Args.hasArg(options::OPT_mno_fmv) ||
8557 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8558 // Disable Function Multiversioning on AArch64 target.
8559 CmdArgs.push_back("-target-feature");
8560 CmdArgs.push_back("-fmv");
8561 }
8562
8563 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8564 (TC.getTriple().isOSBinFormatELF() ||
8565 TC.getTriple().isOSBinFormatCOFF()) &&
8566 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8567 !TC.getTriple().isOSNetBSD() &&
8568 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8569 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8570 CmdArgs.push_back("-faddrsig");
8571
8572 const bool HasDefaultDwarf2CFIASM =
8573 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8574 (EH || UnwindTables || AsyncUnwindTables ||
8575 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8576 if (Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
8577 options::OPT_fno_dwarf2_cfi_asm, HasDefaultDwarf2CFIASM))
8578 CmdArgs.push_back("-fdwarf2-cfi-asm");
8579
8580 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8581 std::string Str = A->getAsString(Args);
8582 if (!TC.getTriple().isOSBinFormatELF())
8583 D.Diag(diag::err_drv_unsupported_opt_for_target)
8584 << Str << TC.getTripleString();
8585 CmdArgs.push_back(Args.MakeArgString(Str));
8586 }
8587
8588 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8589 // the -cc1 command easier to edit when reproducing compiler crashes.
8590 if (Output.getType() == types::TY_Dependencies) {
8591 // Handled with other dependency code.
8592 } else if (Output.isFilename()) {
8593 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8594 Output.getType() == clang::driver::types::TY_IFS) {
8595 SmallString<128> OutputFilename(Output.getFilename());
8596 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8597 CmdArgs.push_back("-o");
8598 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8599 } else {
8600 CmdArgs.push_back("-o");
8601 CmdArgs.push_back(Output.getFilename());
8602 }
8603 } else {
8604 assert(Output.isNothing() && "Invalid output.");
8605 }
8606
8607 addDashXForInput(Args, Input, CmdArgs);
8608
8609 ArrayRef<InputInfo> FrontendInputs = Input;
8610 if (IsExtractAPI)
8611 FrontendInputs = ExtractAPIInputs;
8612 else if (Input.isNothing())
8613 FrontendInputs = {};
8614
8615 for (const InputInfo &Input : FrontendInputs) {
8616 if (Input.isFilename())
8617 CmdArgs.push_back(Input.getFilename());
8618 else
8619 Input.getInputArg().renderAsInput(Args, CmdArgs);
8620 }
8621
8622 if (D.CC1Main && !D.CCGenDiagnostics) {
8623 // Invoke the CC1 directly in this process
8624 C.addCommand(std::make_unique<CC1Command>(
8625 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8626 Output, D.getPrependArg()));
8627 } else {
8628 C.addCommand(std::make_unique<Command>(
8629 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8630 Output, D.getPrependArg()));
8631 }
8632
8633 // Make the compile command echo its inputs for /showFilenames.
8634 if (Output.getType() == types::TY_Object &&
8635 Args.hasFlag(options::OPT__SLASH_showFilenames,
8636 options::OPT__SLASH_showFilenames_, false)) {
8637 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8638 }
8639
8640 if (Arg *A = Args.getLastArg(options::OPT_pg))
8641 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8642 !Args.hasArg(options::OPT_mfentry))
8643 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8644 << A->getAsString(Args);
8645
8646 // Claim some arguments which clang supports automatically.
8647
8648 // -fpch-preprocess is used with gcc to add a special marker in the output to
8649 // include the PCH file.
8650 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8651
8652 // Claim some arguments which clang doesn't support, but we don't
8653 // care to warn the user about.
8654 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8655 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8656
8657 // Disable warnings for clang -E -emit-llvm foo.c
8658 Args.ClaimAllArgs(options::OPT_emit_llvm);
8659}
8660
8661Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8662 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8663 // as it is for other tools. Some operations on a Tool actually test
8664 // whether that tool is Clang based on the Tool's Name as a string.
8665 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8666
8668
8669/// Add options related to the Objective-C runtime/ABI.
8670///
8671/// Returns true if the runtime is non-fragile.
8672ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8673 const InputInfoList &inputs,
8674 ArgStringList &cmdArgs,
8675 RewriteKind rewriteKind) const {
8676 // Look for the controlling runtime option.
8677 Arg *runtimeArg =
8678 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8679 options::OPT_fobjc_runtime_EQ);
8680
8681 // Just forward -fobjc-runtime= to the frontend. This supercedes
8682 // options about fragility.
8683 if (runtimeArg &&
8684 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8685 ObjCRuntime runtime;
8686 StringRef value = runtimeArg->getValue();
8687 if (runtime.tryParse(value)) {
8688 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8689 << value;
8690 }
8691 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8692 (runtime.getVersion() >= VersionTuple(2, 0)))
8693 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8694 !getToolChain().getTriple().isOSBinFormatCOFF() &&
8695 !getToolChain().getTriple().isOSBinFormatWasm()) {
8697 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8698 << runtime.getVersion().getMajor();
8699 }
8700
8701 runtimeArg->render(args, cmdArgs);
8702 return runtime;
8703 }
8704
8705 // Otherwise, we'll need the ABI "version". Version numbers are
8706 // slightly confusing for historical reasons:
8707 // 1 - Traditional "fragile" ABI
8708 // 2 - Non-fragile ABI, version 1
8709 // 3 - Non-fragile ABI, version 2
8710 unsigned objcABIVersion = 1;
8711 // If -fobjc-abi-version= is present, use that to set the version.
8712 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8713 StringRef value = abiArg->getValue();
8714 if (value == "1")
8715 objcABIVersion = 1;
8716 else if (value == "2")
8717 objcABIVersion = 2;
8718 else if (value == "3")
8719 objcABIVersion = 3;
8720 else
8721 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8722 } else {
8723 // Otherwise, determine if we are using the non-fragile ABI.
8724 bool nonFragileABIIsDefault =
8725 (rewriteKind == RK_NonFragile ||
8726 (rewriteKind == RK_None &&
8728 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8729 options::OPT_fno_objc_nonfragile_abi,
8730 nonFragileABIIsDefault)) {
8731// Determine the non-fragile ABI version to use.
8732#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8733 unsigned nonFragileABIVersion = 1;
8734#else
8735 unsigned nonFragileABIVersion = 2;
8736#endif
8737
8738 if (Arg *abiArg =
8739 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8740 StringRef value = abiArg->getValue();
8741 if (value == "1")
8742 nonFragileABIVersion = 1;
8743 else if (value == "2")
8744 nonFragileABIVersion = 2;
8745 else
8746 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8747 << value;
8748 }
8749
8750 objcABIVersion = 1 + nonFragileABIVersion;
8751 } else {
8752 objcABIVersion = 1;
8753 }
8754 }
8755
8756 // We don't actually care about the ABI version other than whether
8757 // it's non-fragile.
8758 bool isNonFragile = objcABIVersion != 1;
8759
8760 // If we have no runtime argument, ask the toolchain for its default runtime.
8761 // However, the rewriter only really supports the Mac runtime, so assume that.
8762 ObjCRuntime runtime;
8763 if (!runtimeArg) {
8764 switch (rewriteKind) {
8765 case RK_None:
8766 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8767 break;
8768 case RK_Fragile:
8769 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8770 break;
8771 case RK_NonFragile:
8772 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8773 break;
8774 }
8775
8776 // -fnext-runtime
8777 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8778 // On Darwin, make this use the default behavior for the toolchain.
8779 if (getToolChain().getTriple().isOSDarwin()) {
8780 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8781
8782 // Otherwise, build for a generic macosx port.
8783 } else {
8784 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8785 }
8786
8787 // -fgnu-runtime
8788 } else {
8789 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8790 // Legacy behaviour is to target the gnustep runtime if we are in
8791 // non-fragile mode or the GCC runtime in fragile mode.
8792 if (isNonFragile)
8793 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8794 else
8795 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8796 }
8797
8798 if (llvm::any_of(inputs, [](const InputInfo &input) {
8799 return types::isObjC(input.getType());
8800 }))
8801 cmdArgs.push_back(
8802 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8803 return runtime;
8804}
8805
8806static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8807 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8808 I += HaveDash;
8809 return !HaveDash;
8810}
8811
8812namespace {
8813struct EHFlags {
8814 bool Synch = false;
8815 bool Asynch = false;
8816 bool NoUnwindC = false;
8817};
8818} // end anonymous namespace
8819
8820/// /EH controls whether to run destructor cleanups when exceptions are
8821/// thrown. There are three modifiers:
8822/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8823/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8824/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8825/// - c: Assume that extern "C" functions are implicitly nounwind.
8826/// The default is /EHs-c-, meaning cleanups are disabled.
8827static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8828 bool isWindowsMSVC) {
8829 EHFlags EH;
8830
8831 std::vector<std::string> EHArgs =
8832 Args.getAllArgValues(options::OPT__SLASH_EH);
8833 for (const auto &EHVal : EHArgs) {
8834 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8835 switch (EHVal[I]) {
8836 case 'a':
8837 EH.Asynch = maybeConsumeDash(EHVal, I);
8838 if (EH.Asynch) {
8839 // Async exceptions are Windows MSVC only.
8840 if (!isWindowsMSVC) {
8841 EH.Asynch = false;
8842 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8843 continue;
8844 }
8845 EH.Synch = false;
8846 }
8847 continue;
8848 case 'c':
8849 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8850 continue;
8851 case 's':
8852 EH.Synch = maybeConsumeDash(EHVal, I);
8853 if (EH.Synch)
8854 EH.Asynch = false;
8855 continue;
8856 default:
8857 break;
8858 }
8859 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8860 break;
8861 }
8862 }
8863 // The /GX, /GX- flags are only processed if there are not /EH flags.
8864 // The default is that /GX is not specified.
8865 if (EHArgs.empty() &&
8866 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8867 /*Default=*/false)) {
8868 EH.Synch = true;
8869 EH.NoUnwindC = true;
8870 }
8871
8872 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8873 EH.Synch = false;
8874 EH.NoUnwindC = false;
8875 EH.Asynch = false;
8876 }
8877
8878 return EH;
8879}
8880
8881void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8882 ArgStringList &CmdArgs) const {
8883 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8884
8885 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8886
8887 if (Arg *ShowIncludes =
8888 Args.getLastArg(options::OPT__SLASH_showIncludes,
8889 options::OPT__SLASH_showIncludes_user)) {
8890 CmdArgs.push_back("--show-includes");
8891 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8892 CmdArgs.push_back("-sys-header-deps");
8893 }
8894
8895 // This controls whether or not we emit RTTI data for polymorphic types.
8896 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8897 /*Default=*/false))
8898 CmdArgs.push_back("-fno-rtti-data");
8899
8900 // This controls whether or not we emit stack-protector instrumentation.
8901 // In MSVC, Buffer Security Check (/GS) is on by default.
8902 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8903 /*Default=*/true)) {
8904 CmdArgs.push_back("-stack-protector");
8905 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8906 }
8907
8908 const Driver &D = getToolChain().getDriver();
8909
8910 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8911 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8912 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8913 if (types::isCXX(InputType))
8914 CmdArgs.push_back("-fcxx-exceptions");
8915 CmdArgs.push_back("-fexceptions");
8916 if (EH.Asynch)
8917 CmdArgs.push_back("-fasync-exceptions");
8918 }
8919 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8920 CmdArgs.push_back("-fexternc-nounwind");
8921
8922 // /EP should expand to -E -P.
8923 if (Args.hasArg(options::OPT__SLASH_EP)) {
8924 CmdArgs.push_back("-E");
8925 CmdArgs.push_back("-P");
8926 }
8927
8928 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8929 options::OPT__SLASH_Zc_dllexportInlines,
8930 false)) {
8931 CmdArgs.push_back("-fno-dllexport-inlines");
8932 }
8933
8934 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8935 options::OPT__SLASH_Zc_wchar_t, false)) {
8936 CmdArgs.push_back("-fno-wchar");
8937 }
8938
8939 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8940 llvm::Triple::ArchType Arch = getToolChain().getArch();
8941 std::vector<std::string> Values =
8942 Args.getAllArgValues(options::OPT__SLASH_arch);
8943 if (!Values.empty()) {
8944 llvm::SmallSet<std::string, 4> SupportedArches;
8945 if (Arch == llvm::Triple::x86)
8946 SupportedArches.insert("IA32");
8947
8948 for (auto &V : Values)
8949 if (!SupportedArches.contains(V))
8950 D.Diag(diag::err_drv_argument_not_allowed_with)
8951 << std::string("/arch:").append(V) << "/kernel";
8952 }
8953
8954 CmdArgs.push_back("-fno-rtti");
8955 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8956 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8957 << "/kernel";
8958 }
8959
8960 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_vlen,
8961 options::OPT__SLASH_vlen_EQ_256,
8962 options::OPT__SLASH_vlen_EQ_512)) {
8963 llvm::Triple::ArchType AT = getToolChain().getArch();
8964 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8965 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch, Default);
8966 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8967 "AVX10.2"};
8968
8969 if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_512)) {
8970 if (Arch512.contains(Arch))
8971 CmdArgs.push_back("-mprefer-vector-width=512");
8972 else
8973 D.Diag(diag::warn_drv_argument_not_allowed_with)
8974 << "/vlen=512" << std::string("/arch:").append(Arch);
8975 } else if (A->getOption().matches(options::OPT__SLASH_vlen_EQ_256)) {
8976 if (Arch512.contains(Arch))
8977 CmdArgs.push_back("-mprefer-vector-width=256");
8978 else if (Arch != "AVX" && Arch != "AVX2")
8979 D.Diag(diag::warn_drv_argument_not_allowed_with)
8980 << "/vlen=256" << std::string("/arch:").append(Arch);
8981 } else {
8982 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8983 CmdArgs.push_back("-mprefer-vector-width=256");
8984 }
8985 } else {
8986 StringRef Arch = Args.getLastArgValue(options::OPT__SLASH_arch);
8987 if (Arch == "AVX10.1" || Arch == "AVX10.2") {
8988 CmdArgs.push_back("-mprefer-vector-width=256");
8989 CmdArgs.push_back("-target-feature");
8990 CmdArgs.push_back("-amx-tile");
8991 }
8992 if (Arch == "AVX10.2") {
8993 CmdArgs.push_back("-target-feature");
8994 CmdArgs.push_back("+avx10.2");
8995 }
8996 }
8997
8998 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8999 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
9000 if (MostGeneralArg && BestCaseArg)
9001 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9002 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
9003
9004 if (MostGeneralArg) {
9005 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
9006 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
9007 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
9008
9009 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
9010 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
9011 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
9012 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
9013 << FirstConflict->getAsString(Args)
9014 << SecondConflict->getAsString(Args);
9015
9016 if (SingleArg)
9017 CmdArgs.push_back("-fms-memptr-rep=single");
9018 else if (MultipleArg)
9019 CmdArgs.push_back("-fms-memptr-rep=multiple");
9020 else
9021 CmdArgs.push_back("-fms-memptr-rep=virtual");
9022 }
9023
9024 if (Args.hasArg(options::OPT_regcall4))
9025 CmdArgs.push_back("-regcall4");
9026
9027 // Parse the default calling convention options.
9028 if (Arg *CCArg =
9029 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
9030 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
9031 options::OPT__SLASH_Gregcall)) {
9032 unsigned DCCOptId = CCArg->getOption().getID();
9033 const char *DCCFlag = nullptr;
9034 bool ArchSupported = !isNVPTX;
9035 llvm::Triple::ArchType Arch = getToolChain().getArch();
9036 switch (DCCOptId) {
9037 case options::OPT__SLASH_Gd:
9038 DCCFlag = "-fdefault-calling-conv=cdecl";
9039 break;
9040 case options::OPT__SLASH_Gr:
9041 ArchSupported = Arch == llvm::Triple::x86;
9042 DCCFlag = "-fdefault-calling-conv=fastcall";
9043 break;
9044 case options::OPT__SLASH_Gz:
9045 ArchSupported = Arch == llvm::Triple::x86;
9046 DCCFlag = "-fdefault-calling-conv=stdcall";
9047 break;
9048 case options::OPT__SLASH_Gv:
9049 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9050 DCCFlag = "-fdefault-calling-conv=vectorcall";
9051 break;
9052 case options::OPT__SLASH_Gregcall:
9053 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
9054 DCCFlag = "-fdefault-calling-conv=regcall";
9055 break;
9056 }
9057
9058 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
9059 if (ArchSupported && DCCFlag)
9060 CmdArgs.push_back(DCCFlag);
9061 }
9062
9063 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
9064 CmdArgs.push_back("-regcall4");
9065
9066 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
9067
9068 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
9069 CmdArgs.push_back("-fdiagnostics-format");
9070 CmdArgs.push_back("msvc");
9071 }
9072
9073 if (Args.hasArg(options::OPT__SLASH_kernel))
9074 CmdArgs.push_back("-fms-kernel");
9075
9076 // Unwind v2 (epilog) information for x64 Windows. MSVC's behavior is not
9077 // order-dependent: /d2epilogunwindrequirev2 always wins over /d2epilogunwind.
9078 if (Args.hasArg(options::OPT__SLASH_d2epilogunwindrequirev2))
9079 CmdArgs.push_back("-fwinx64-eh-unwind=v2-required");
9080 else if (Args.hasArg(options::OPT__SLASH_d2epilogunwind))
9081 CmdArgs.push_back("-fwinx64-eh-unwind=v2-best-effort");
9082
9083 // Handle the various /guard options. We don't immediately push back clang
9084 // args since there are /d2 args that can modify the behavior of /guard:cf.
9085 bool HasCFGuard = false;
9086 bool HasCFGuardNoChecks = false;
9087 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
9088 StringRef GuardArgs = A->getValue();
9089 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
9090 // "ehcont-".
9091 if (GuardArgs.equals_insensitive("cf")) {
9092 // Emit CFG instrumentation and the table of address-taken functions.
9093 HasCFGuard = true;
9094 HasCFGuardNoChecks = false;
9095 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
9096 // Emit only the table of address-taken functions.
9097 HasCFGuard = false;
9098 HasCFGuardNoChecks = true;
9099 } else if (GuardArgs.equals_insensitive("ehcont")) {
9100 // Emit EH continuation table.
9101 CmdArgs.push_back("-ehcontguard");
9102 } else if (GuardArgs.equals_insensitive("cf-") ||
9103 GuardArgs.equals_insensitive("ehcont-")) {
9104 // Do nothing, but we might want to emit a security warning in future.
9105 } else {
9106 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
9107 }
9108 A->claim();
9109 }
9110
9111 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
9112 // If CFG is not enabled, it is a no-op.
9113 if (Args.hasArg(options::OPT__SLASH_d2guardnochecks)) {
9114 if (HasCFGuard) {
9115 HasCFGuard = false;
9116 HasCFGuardNoChecks = true;
9117 }
9118 }
9119
9120 if (HasCFGuard)
9121 CmdArgs.push_back("-cfguard");
9122 else if (HasCFGuardNoChecks)
9123 CmdArgs.push_back("-cfguard-no-checks");
9124
9125 // Control Flow Guard mechanism for Windows.
9126 if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch_))
9127 CmdArgs.push_back("-fwin-cfg-mechanism=check");
9128 else if (Args.hasArg(options::OPT__SLASH_d2guardcfgdispatch))
9129 CmdArgs.push_back("-fwin-cfg-mechanism=dispatch");
9130
9131 for (const auto &FuncOverride :
9132 Args.getAllArgValues(options::OPT__SLASH_funcoverride)) {
9133 CmdArgs.push_back(Args.MakeArgString(
9134 Twine("-loader-replaceable-function=") + FuncOverride));
9135 }
9136
9137 if (Args.hasArg(options::OPT__SLASH_experimental_deterministic)) {
9138 CmdArgs.push_back("-Wdate-time");
9139
9140 if (Args.hasArg(options::OPT_mincremental_linker_compatible)) {
9141 D.Diag(diag::err_drv_argument_not_allowed_with)
9142 << "/experimental:deterministic"
9143 << "/Brepro-";
9144 }
9145 // CL's sets COFF's OBJ timestamp to a hash of the source file path to get
9146 // deterministic result, but we force this timestamp to 0, which also
9147 // produces deterministic result.
9148 CmdArgs.push_back("-mno-incremental-linker-compatible");
9149 }
9150
9151 bool HasNoDateTime = Args.hasFlag(options::OPT__SLASH_d1nodatetime,
9152 options::OPT__SLASH_d1nodatetime_, false);
9153
9154 if (HasNoDateTime)
9155 CmdArgs.push_back("-init-datetime-macros=undefined");
9156
9157 // /Brepro is an alias for -mincremental-linker-compatible option.
9158 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
9159 options::OPT_mno_incremental_linker_compatible,
9160 getToolChain()
9161 .getTriple()
9162 .isDefaultIncrementalLinkerCompatibleByDefault())) {
9163 // Redefine the date/time macros only if /d1nodatetime wasn't specified.
9164 // This option does not allow the user redefinitions for these macros.
9165 if (!HasNoDateTime)
9166 CmdArgs.push_back("-init-datetime-macros=literalone");
9167 }
9168}
9169
9170const char *Clang::getBaseInputName(const ArgList &Args,
9171 const InputInfo &Input) {
9172 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
9173}
9174
9175const char *Clang::getBaseInputStem(const ArgList &Args,
9176 const InputInfoList &Inputs) {
9177 const char *Str = getBaseInputName(Args, Inputs[0]);
9178
9179 if (const char *End = strrchr(Str, '.'))
9180 return Args.MakeArgString(std::string(Str, End));
9181
9182 return Str;
9183}
9184
9185const char *Clang::getDependencyFileName(const ArgList &Args,
9186 const InputInfoList &Inputs) {
9187 // FIXME: Think about this more.
9188
9189 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
9190 SmallString<128> OutputFilename(OutputOpt->getValue());
9191 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
9192 return Args.MakeArgString(OutputFilename);
9193 }
9194
9195 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
9196}
9197
9198// Begin ClangAs
9199
9200void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
9201 ArgStringList &CmdArgs) const {
9202 StringRef CPUName;
9203 StringRef ABIName;
9204 const llvm::Triple &Triple = getToolChain().getTriple();
9205 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
9206
9207 CmdArgs.push_back("-target-abi");
9208 CmdArgs.push_back(ABIName.data());
9209}
9210
9211void ClangAs::AddX86TargetArgs(const ArgList &Args,
9212 ArgStringList &CmdArgs) const {
9213 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
9214 /*IsLTO=*/false);
9215
9216 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
9217 StringRef Value = A->getValue();
9218 if (Value == "intel" || Value == "att") {
9219 CmdArgs.push_back("-mllvm");
9220 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
9221 } else {
9222 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
9223 << A->getSpelling() << Value;
9224 }
9225 }
9226}
9227
9228void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
9229 ArgStringList &CmdArgs) const {
9230 CmdArgs.push_back("-target-abi");
9231 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
9233 .data());
9234}
9235
9236void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
9237 ArgStringList &CmdArgs) const {
9238 const llvm::Triple &Triple = getToolChain().getTriple();
9239 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
9240
9241 CmdArgs.push_back("-target-abi");
9242 CmdArgs.push_back(ABIName.data());
9243
9244 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9245 options::OPT_mno_default_build_attributes, true)) {
9246 CmdArgs.push_back("-mllvm");
9247 CmdArgs.push_back("-riscv-add-build-attributes");
9248 }
9249}
9250
9252 const InputInfo &Output, const InputInfoList &Inputs,
9253 const ArgList &Args,
9254 const char *LinkingOutput) const {
9255 ArgStringList CmdArgs;
9256
9257 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
9258 const InputInfo &Input = Inputs[0];
9259
9260 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
9261 const std::string &TripleStr = Triple.getTriple();
9262 const auto &D = getToolChain().getDriver();
9263
9264 // Don't warn about "clang -w -c foo.s"
9265 Args.ClaimAllArgs(options::OPT_w);
9266 // and "clang -emit-llvm -c foo.s"
9267 Args.ClaimAllArgs(options::OPT_emit_llvm);
9268
9269 claimNoWarnArgs(Args);
9270
9271 // Invoke ourselves in -cc1as mode.
9272 //
9273 // FIXME: Implement custom jobs for internal actions.
9274 CmdArgs.push_back("-cc1as");
9275
9276 // Add the "effective" target triple.
9277 CmdArgs.push_back("-triple");
9278 CmdArgs.push_back(Args.MakeArgString(TripleStr));
9279
9281
9282 // Set the output mode, we currently only expect to be used as a real
9283 // assembler.
9284 CmdArgs.push_back("-filetype");
9285 CmdArgs.push_back("obj");
9286
9287 // Set the main file name, so that debug info works even with
9288 // -save-temps or preprocessed assembly.
9289 CmdArgs.push_back("-main-file-name");
9290 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
9291
9292 // Add the target cpu
9293 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
9294 if (!CPU.empty()) {
9295 CmdArgs.push_back("-target-cpu");
9296 CmdArgs.push_back(Args.MakeArgString(CPU));
9297 }
9298
9299 // Add the target features
9300 getTargetFeatures(D, Triple, Args, CmdArgs, true);
9301
9302 // Ignore explicit -force_cpusubtype_ALL option.
9303 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
9304
9305 // Pass along any -I options so we get proper .include search paths.
9306 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
9307
9308 // Pass along any --embed-dir or similar options so we get proper embed paths.
9309 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
9310
9311 // Determine the original source input.
9312 auto FindSource = [](const Action *S) -> const Action * {
9313 while (S->getKind() != Action::InputClass) {
9314 assert(!S->getInputs().empty() && "unexpected root action!");
9315 S = S->getInputs()[0];
9316 }
9317 return S;
9318 };
9319 const Action *SourceAction = FindSource(&JA);
9320
9321 // Forward -g and handle debug info related flags, assuming we are dealing
9322 // with an actual assembly file.
9323 bool WantDebug = false;
9324 Args.ClaimAllArgs(options::OPT_g_Group);
9325 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9326 WantDebug = !A->getOption().matches(options::OPT_g0) &&
9327 !A->getOption().matches(options::OPT_ggdb0);
9328
9329 // If a -gdwarf argument appeared, remember it.
9330 bool EmitDwarf = false;
9331 if (const Arg *A = getDwarfNArg(Args))
9332 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
9333
9334 bool EmitCodeView = false;
9335 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
9336 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
9337
9338 // If the user asked for debug info but did not explicitly specify -gcodeview
9339 // or -gdwarf, ask the toolchain for the default format.
9340 if (!EmitCodeView && !EmitDwarf && WantDebug) {
9341 switch (getToolChain().getDefaultDebugFormat()) {
9342 case llvm::codegenoptions::DIF_CodeView:
9343 EmitCodeView = true;
9344 break;
9345 case llvm::codegenoptions::DIF_DWARF:
9346 EmitDwarf = true;
9347 break;
9348 }
9349 }
9350
9351 // If the arguments don't imply DWARF, don't emit any debug info here.
9352 if (!EmitDwarf)
9353 WantDebug = false;
9354
9355 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
9356 llvm::codegenoptions::NoDebugInfo;
9357
9358 // Add the -fdebug-compilation-dir flag if needed.
9359 const char *DebugCompilationDir =
9360 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
9361
9362 if (SourceAction->getType() == types::TY_Asm ||
9363 SourceAction->getType() == types::TY_PP_Asm) {
9364 // You might think that it would be ok to set DebugInfoKind outside of
9365 // the guard for source type, however there is a test which asserts
9366 // that some assembler invocation receives no -debug-info-kind,
9367 // and it's not clear whether that test is just overly restrictive.
9368 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
9369 : llvm::codegenoptions::NoDebugInfo);
9370
9371 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
9372 CmdArgs);
9373
9374 // Set the AT_producer to the clang version when using the integrated
9375 // assembler on assembly source files.
9376 CmdArgs.push_back("-dwarf-debug-producer");
9377 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
9378
9379 // And pass along -I options
9380 Args.AddAllArgs(CmdArgs, options::OPT_I);
9381 }
9382 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
9383 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
9384 llvm::DebuggerKind::Default);
9385 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
9386 renderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
9387
9388 // Handle -fPIC et al -- the relocation-model affects the assembler
9389 // for some targets.
9390 llvm::Reloc::Model RelocationModel;
9391 unsigned PICLevel;
9392 bool IsPIE;
9393 std::tie(RelocationModel, PICLevel, IsPIE) =
9394 ParsePICArgs(getToolChain(), Args);
9395
9396 const char *RMName = RelocationModelName(RelocationModel);
9397 if (RMName) {
9398 CmdArgs.push_back("-mrelocation-model");
9399 CmdArgs.push_back(RMName);
9400 }
9401
9402 // Optionally embed the -cc1as level arguments into the debug info, for build
9403 // analysis.
9404 if (getToolChain().UseDwarfDebugFlags()) {
9405 ArgStringList OriginalArgs;
9406 for (const auto &Arg : Args)
9407 Arg->render(Args, OriginalArgs);
9408
9409 SmallString<256> Flags;
9410 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9411 escapeSpacesAndBackslashes(Exec, Flags);
9412 for (const char *OriginalArg : OriginalArgs) {
9413 SmallString<128> EscapedArg;
9414 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
9415 Flags += " ";
9416 Flags += EscapedArg;
9417 }
9418 CmdArgs.push_back("-dwarf-debug-flags");
9419 CmdArgs.push_back(Args.MakeArgString(Flags));
9420 }
9421
9422 // FIXME: Add -static support, once we have it.
9423
9424 // Add target specific flags.
9425 switch (getToolChain().getArch()) {
9426 default:
9427 break;
9428
9429 case llvm::Triple::mips:
9430 case llvm::Triple::mipsel:
9431 case llvm::Triple::mips64:
9432 case llvm::Triple::mips64el:
9433 AddMIPSTargetArgs(Args, CmdArgs);
9434 break;
9435
9436 case llvm::Triple::x86:
9437 case llvm::Triple::x86_64:
9438 AddX86TargetArgs(Args, CmdArgs);
9439 break;
9440
9441 case llvm::Triple::arm:
9442 case llvm::Triple::armeb:
9443 case llvm::Triple::thumb:
9444 case llvm::Triple::thumbeb:
9445 // This isn't in AddARMTargetArgs because we want to do this for assembly
9446 // only, not C/C++.
9447 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9448 options::OPT_mno_default_build_attributes, true)) {
9449 CmdArgs.push_back("-mllvm");
9450 CmdArgs.push_back("-arm-add-build-attributes");
9451 }
9452 break;
9453
9454 case llvm::Triple::aarch64:
9455 case llvm::Triple::aarch64_32:
9456 case llvm::Triple::aarch64_be:
9457 if (Args.hasArg(options::OPT_mmark_bti_property)) {
9458 CmdArgs.push_back("-mllvm");
9459 CmdArgs.push_back("-aarch64-mark-bti-property");
9460 }
9461 break;
9462
9463 case llvm::Triple::loongarch32:
9464 case llvm::Triple::loongarch64:
9465 AddLoongArchTargetArgs(Args, CmdArgs);
9466 break;
9467
9468 case llvm::Triple::riscv32:
9469 case llvm::Triple::riscv64:
9470 case llvm::Triple::riscv32be:
9471 case llvm::Triple::riscv64be:
9472 AddRISCVTargetArgs(Args, CmdArgs);
9473 break;
9474
9475 case llvm::Triple::hexagon:
9476 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
9477 options::OPT_mno_default_build_attributes, true)) {
9478 CmdArgs.push_back("-mllvm");
9479 CmdArgs.push_back("-hexagon-add-build-attributes");
9480 }
9481 break;
9482 }
9483
9484 // Consume all the warning flags. Usually this would be handled more
9485 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
9486 // doesn't handle that so rather than warning about unused flags that are
9487 // actually used, we'll lie by omission instead.
9488 // FIXME: Stop lying and consume only the appropriate driver flags
9489 Args.ClaimAllArgs(options::OPT_W_Group);
9490
9491 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9492 getToolChain().getDriver());
9493
9494 // Forward -Xclangas arguments to -cc1as
9495 for (auto Arg : Args.filtered(options::OPT_Xclangas)) {
9496 Arg->claim();
9497 CmdArgs.push_back(Arg->getValue());
9498 }
9499
9500 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
9501
9502 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9503 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9504 Output.getFilename());
9505
9506 // Fixup any previous commands that use -object-file-name because when we
9507 // generated them, the final .obj name wasn't yet known.
9508 for (Command &J : C.getJobs()) {
9509 if (SourceAction != FindSource(&J.getSource()))
9510 continue;
9511 auto &JArgs = J.getArguments();
9512 for (unsigned I = 0; I < JArgs.size(); ++I) {
9513 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
9514 Output.isFilename()) {
9515 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9516 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
9517 Output.getFilename());
9518 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
9519 J.replaceArguments(NewArgs);
9520 break;
9521 }
9522 }
9523 }
9524
9525 assert(Output.isFilename() && "Unexpected lipo output.");
9526 CmdArgs.push_back("-o");
9527 CmdArgs.push_back(Output.getFilename());
9528
9529 const llvm::Triple &T = getToolChain().getTriple();
9530 Arg *A;
9531 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
9532 T.isOSBinFormatELF()) {
9533 CmdArgs.push_back("-split-dwarf-output");
9534 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
9535 }
9536
9537 if (Triple.isAMDGPU())
9538 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9539
9540 assert(Input.isFilename() && "Invalid input.");
9541 CmdArgs.push_back(Input.getFilename());
9542
9543 const char *Exec = getToolChain().getDriver().getDriverProgramPath();
9544 if (D.CC1Main && !D.CCGenDiagnostics) {
9545 // Invoke cc1as directly in this process.
9546 C.addCommand(std::make_unique<CC1Command>(
9547 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9548 Output, D.getPrependArg()));
9549 } else {
9550 C.addCommand(std::make_unique<Command>(
9551 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
9552 Output, D.getPrependArg()));
9553 }
9554}
9555
9556// Begin OffloadBundler
9558 const InputInfo &Output,
9559 const InputInfoList &Inputs,
9560 const llvm::opt::ArgList &TCArgs,
9561 const char *LinkingOutput) const {
9562 // The version with only one output is expected to refer to a bundling job.
9563 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9564
9565 // The bundling command looks like this:
9566 // clang-offload-bundler -type=bc
9567 // -targets=host-triple,openmp-triple1,openmp-triple2
9568 // -output=output_file
9569 // -input=unbundle_file_host
9570 // -input=unbundle_file_tgt1
9571 // -input=unbundle_file_tgt2
9572
9573 ArgStringList CmdArgs;
9574
9575 // Get the type.
9576 CmdArgs.push_back(TCArgs.MakeArgString(
9577 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
9578
9579 assert(JA.getInputs().size() == Inputs.size() &&
9580 "Not have inputs for all dependence actions??");
9581
9582 // Get the targets.
9583 SmallString<128> Triples;
9584 Triples += "-targets=";
9585 for (unsigned I = 0; I < Inputs.size(); ++I) {
9586 if (I)
9587 Triples += ',';
9588
9589 // Find ToolChain for this input.
9591 const ToolChain *CurTC = &getToolChain();
9592 const Action *CurDep = JA.getInputs()[I];
9593
9594 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9595 CurTC = nullptr;
9596 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, BoundArch BA) {
9597 assert(CurTC == nullptr && "Expected one dependence!");
9598 CurKind = A->getOffloadingDeviceKind();
9599 CurTC = TC;
9600 });
9601 }
9602 Triples += Action::GetOffloadKindName(CurKind);
9603 Triples += '-';
9604 Triples += llvm::Triple(CurTC->ComputeEffectiveClangTriple(
9605 TCArgs, CurDep->getOffloadingArch()))
9606 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9607
9608 if ((CurKind != Action::OFK_Host) && !CurDep->getOffloadingArch().empty()) {
9609 Triples += '-';
9610 Triples += CurDep->getOffloadingArch().ArchName;
9611 }
9612 }
9613 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9614
9615 // Get bundled file command.
9616 CmdArgs.push_back(
9617 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9618
9619 // Get unbundled files command.
9620 for (unsigned I = 0; I < Inputs.size(); ++I) {
9622 UB += "-input=";
9623
9624 // Find ToolChain for this input.
9625 const ToolChain *CurTC = &getToolChain();
9626 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9627 CurTC = nullptr;
9628 OA->doOnEachDependence([&](Action *, const ToolChain *TC, BoundArch) {
9629 assert(CurTC == nullptr && "Expected one dependence!");
9630 CurTC = TC;
9631 });
9632 UB += C.addTempFile(
9633 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9634 } else {
9635 UB += CurTC->getInputFilename(Inputs[I]);
9636 }
9637 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9638 }
9639 addOffloadCompressArgs(TCArgs, CmdArgs);
9640 // All the inputs are encoded as commands.
9641 C.addCommand(std::make_unique<Command>(
9642 JA, *this, ResponseFileSupport::None(),
9643 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9644 CmdArgs, ArrayRef<InputInfo>(), Output));
9645}
9646
9648 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9649 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9650 const char *LinkingOutput) const {
9651 // The version with multiple outputs is expected to refer to a unbundling job.
9652 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9653
9654 // The unbundling command looks like this:
9655 // clang-offload-bundler -type=bc
9656 // -targets=host-triple,openmp-triple1,openmp-triple2
9657 // -input=input_file
9658 // -output=unbundle_file_host
9659 // -output=unbundle_file_tgt1
9660 // -output=unbundle_file_tgt2
9661 // -unbundle
9662
9663 ArgStringList CmdArgs;
9664
9665 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9666 InputInfo Input = Inputs.front();
9667
9668 // Get the type.
9669 CmdArgs.push_back(TCArgs.MakeArgString(
9670 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9671
9672 // Get the targets.
9673 SmallString<128> Triples;
9674 Triples += "-targets=";
9675 auto DepInfo = UA.getDependentActionsInfo();
9676 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9677 if (I)
9678 Triples += ',';
9679
9680 auto &Dep = DepInfo[I];
9681 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9682 Triples += '-';
9683 Triples += llvm::Triple(Dep.DependentToolChain->ComputeEffectiveClangTriple(
9684 TCArgs, Dep.DependentBoundArch))
9685 .normalize(llvm::Triple::CanonicalForm::FOUR_IDENT);
9686
9687 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9688 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9689 !Dep.DependentBoundArch.empty()) {
9690 Triples += '-';
9691 Triples += Dep.DependentBoundArch.ArchName;
9692 }
9693 }
9694
9695 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9696
9697 // Get bundled file command.
9698 CmdArgs.push_back(
9699 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9700
9701 // Get unbundled files command.
9702 for (unsigned I = 0; I < Outputs.size(); ++I) {
9704 UB += "-output=";
9705 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9706 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9707 }
9708 CmdArgs.push_back("-unbundle");
9709 CmdArgs.push_back("-allow-missing-bundles");
9710 if (TCArgs.hasArg(options::OPT_v))
9711 CmdArgs.push_back("-verbose");
9712
9713 // All the inputs are encoded as commands.
9714 C.addCommand(std::make_unique<Command>(
9715 JA, *this, ResponseFileSupport::None(),
9716 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9717 CmdArgs, ArrayRef<InputInfo>(), Outputs));
9718}
9719
9721 const InputInfo &Output,
9722 const InputInfoList &Inputs,
9723 const llvm::opt::ArgList &Args,
9724 const char *LinkingOutput) const {
9725 ArgStringList CmdArgs;
9726
9727 // Add the output file name.
9728 assert(Output.isFilename() && "Invalid output.");
9729 CmdArgs.push_back("-o");
9730 CmdArgs.push_back(Output.getFilename());
9731
9732 // Create the inputs to bundle the needed metadata.
9733 for (const InputInfo &Input : Inputs) {
9734 const Action *OffloadAction = Input.getAction();
9736 const ArgList &TCArgs =
9737 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9739 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9741 if (Arch.empty())
9742 Arch = BoundArch(TCArgs.getLastArgValue(options::OPT_march_EQ));
9743
9744 StringRef Kind =
9746
9747 ArgStringList Features;
9748 SmallVector<StringRef> FeatureArgs;
9749 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9750 false);
9751 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9752 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9753
9754 // TODO: We need to pass in the full target-id and handle it properly in the
9755 // linker wrapper.
9757 "file=" + File.str(),
9758 "triple=" + TC->ComputeEffectiveClangTriple(TCArgs, Arch),
9759 "arch=" + (Arch.empty() ? "generic" : Arch.ArchName.str()),
9760 "kind=" + Kind.str(),
9761 };
9762
9764 for (StringRef Feature : FeatureArgs)
9765 Parts.emplace_back("feature=" + Feature.str());
9766
9767 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9768 }
9769
9770 C.addCommand(std::make_unique<Command>(
9772 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9773 CmdArgs, Inputs, Output));
9774}
9775
9776// Options that need the profile compiler-rt library on the target toolchain.
9777// Coverage mapping flags require -fprofile-instr-generate, so they belong here
9778// too.
9779static bool requiresProfileRT(unsigned ID) {
9780 switch (ID) {
9781 case options::OPT_fprofile_generate:
9782 case options::OPT_fprofile_generate_EQ:
9783 case options::OPT_fprofile_instr_generate:
9784 case options::OPT_fprofile_instr_generate_EQ:
9785 case options::OPT_fcoverage_mapping:
9786 case options::OPT_fno_coverage_mapping:
9787 case options::OPT_fcoverage_compilation_dir_EQ:
9788 case options::OPT_ffile_compilation_dir_EQ:
9789 case options::OPT_fcoverage_prefix_map_EQ:
9790 return true;
9791 default:
9792 return false;
9793 }
9794}
9795
9796// Options that need the ubsan compiler-rt library on the target toolchain.
9797static bool requiresUBSanRT(unsigned ID) {
9798 switch (ID) {
9799 case options::OPT_fsanitize_EQ:
9800 case options::OPT_fno_sanitize_EQ:
9801 case options::OPT_fsanitize_minimal_runtime:
9802 case options::OPT_fno_sanitize_minimal_runtime:
9803 return true;
9804 default:
9805 return false;
9806 }
9807}
9808
9810 const InputInfo &Output,
9811 const InputInfoList &Inputs,
9812 const ArgList &Args,
9813 const char *LinkingOutput) const {
9814 using namespace options;
9815
9816 // A list of permitted options that will be forwarded to the embedded device
9817 // compilation job.
9818 const llvm::DenseSet<unsigned> CompilerOptions{
9819 OPT_v,
9820 OPT_hip_path_EQ,
9821 OPT_O_Group,
9822 OPT_g_Group,
9823 OPT_g_flags_Group,
9824 OPT_R_value_Group,
9825 OPT_R_Group,
9826 OPT_Xcuda_ptxas,
9827 OPT_ptxas_path_EQ,
9828 OPT_ftime_report,
9829 OPT_ftime_trace,
9830 OPT_ftime_trace_EQ,
9831 OPT_ftime_trace_granularity_EQ,
9832 OPT_ftime_trace_verbose,
9833 OPT_opt_record_file,
9834 OPT_opt_record_format,
9835 OPT_opt_record_passes,
9836 OPT_fsave_optimization_record,
9837 OPT_fsave_optimization_record_EQ,
9838 OPT_fno_save_optimization_record,
9839 OPT_foptimization_record_file_EQ,
9840 OPT_foptimization_record_passes_EQ,
9841 OPT_save_temps,
9842 OPT_save_temps_EQ,
9843 OPT_mcode_object_version_EQ,
9844 OPT_load,
9845 OPT_no_canonical_prefixes,
9846 OPT_fno_lto,
9847 OPT_flto,
9848 OPT_flto_partitions_EQ,
9849 OPT_flto_EQ,
9850 OPT_hipspv_pass_plugin_EQ,
9851 OPT_use_spirv_backend,
9852 OPT_no_use_spirv_backend,
9853 OPT_fmultilib_flag,
9854 OPT_fprofile_generate,
9855 OPT_fprofile_generate_EQ,
9856 OPT_fprofile_instr_generate,
9857 OPT_fprofile_instr_generate_EQ,
9858 OPT_fcoverage_mapping,
9859 OPT_fno_coverage_mapping,
9860 OPT_fcoverage_compilation_dir_EQ,
9861 OPT_ffile_compilation_dir_EQ,
9862 OPT_fcoverage_prefix_map_EQ,
9863 OPT_fsanitize_EQ,
9864 OPT_fno_sanitize_EQ,
9865 OPT_fsanitize_minimal_runtime,
9866 OPT_fno_sanitize_minimal_runtime,
9867 OPT_fsanitize_trap_EQ,
9868 OPT_fno_sanitize_trap_EQ,
9869 OPT_fslp_vectorize,
9870 OPT_fno_slp_vectorize,
9871 OPT_hipstdpar};
9872 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9873 // Suppress verbose output for HIP non-RDC fat binaries because it confuses
9874 // CMake implicit linker argument parsing.
9875 bool SuppressHIPNoRDCVerbose =
9876 JA.getType() == types::TY_HIP_FATBIN &&
9877 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
9878 auto ToolChainHasRT = [&](const ToolChain &TC, StringRef Name) {
9879 return TC.getVFS().exists(
9880 TC.getCompilerRT(Args, Name, ToolChain::FT_Static));
9881 };
9882 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9883 unsigned ID = A->getOption().getID();
9884 // Don't forward profiling arguments if the toolchain doesn't support it.
9885 // Without this check using it on the host would result in linker errors.
9886 // Coverage mapping flags require -fprofile-instr-generate, so drop them
9887 // together to avoid a device cc1 diagnostic.
9888 if (requiresProfileRT(ID) && !ToolChainHasRT(TC, "profile"))
9889 return false;
9890 // Don't forward sanitizer arguments if the toolchain doesn't support it.
9891 // Without this check using it on the host would result in linker errors.
9892 if (requiresUBSanRT(ID) && !ToolChainHasRT(TC, "ubsan_minimal"))
9893 return false;
9894 // Don't forward -mllvm to toolchains that don't support LLVM.
9895 return TC.HasNativeLLVMSupport() || ID != OPT_mllvm;
9896 };
9897 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9898 const ToolChain &TC) {
9899 if (A->getOption().matches(OPT_v) && SuppressHIPNoRDCVerbose)
9900 return false;
9901 return (Set.contains(A->getOption().getID()) ||
9902 (A->getOption().getGroup().isValid() &&
9903 Set.contains(A->getOption().getGroup().getID()))) &&
9904 ShouldForwardForToolChain(A, TC);
9905 };
9906
9907 ArgStringList CmdArgs;
9910 auto TCRange = C.getOffloadToolChains(Kind);
9911 for (auto &I : llvm::make_range(TCRange)) {
9912 const ToolChain *TC = I.second;
9913
9914 // We do not use a bound architecture here so options passed only to a
9915 // specific architecture via -Xarch_<cpu> will not be forwarded.
9916 ArgStringList CompilerArgs;
9917 ArgStringList LinkerArgs;
9918 const DerivedArgList &ToolChainArgs =
9919 C.getArgsForToolChain(TC, /*BA=*/{}, Kind);
9920 for (Arg *A : ToolChainArgs) {
9921 if (A->getOption().matches(OPT_Zlinker_input))
9922 LinkerArgs.emplace_back(A->getValue());
9923 else if (ShouldForward(CompilerOptions, A, *TC)) {
9924 A->claim();
9925 A->render(Args, CompilerArgs);
9926 } else if (ShouldForward(LinkerOptions, A, *TC)) {
9927 A->claim();
9928 A->render(Args, LinkerArgs);
9929 }
9930 }
9931
9932 // If the user explicitly requested it via `--offload-arch` we should
9933 // extract it from any static libraries if present.
9934 for (StringRef Arg : ToolChainArgs.getAllArgValues(OPT_offload_arch_EQ))
9935 CmdArgs.emplace_back(Args.MakeArgString("--should-extract=" + Arg));
9936
9937 // If this is OpenMP the device linker will need `-lompdevice`.
9938 if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
9939 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9940 LinkerArgs.emplace_back("-lompdevice");
9941
9942 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9943 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9944 // flags to normal compilation.
9945 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9946 // flags. SYCL uses clang-sycl-linker instead of spirv-link, so skip it.
9947 if (TC->getTriple().isSPIRV() &&
9948 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9949 Kind != Action::OFK_SYCL && !TC->isUsingLTO(ToolChainArgs, Kind)) {
9950 // For SPIR-V some functions will be defined by the runtime so allow
9951 // unresolved symbols in `spirv-link`.
9952 LinkerArgs.emplace_back("--allow-partial-linkage");
9953 // Don't optimize out exported symbols.
9954 LinkerArgs.emplace_back("--create-library");
9955 }
9956
9957 // Forward the SYCL device image split option to clang-sycl-linker.
9958 // The driver and clang-sycl-linker share the same value vocabulary, so
9959 // the value is passed through verbatim after validation.
9960 if (Kind == Action::OFK_SYCL) {
9961 if (Arg *A =
9962 ToolChainArgs.getLastArg(OPT_fsycl_device_image_split_EQ)) {
9963 StringRef Mode = A->getValue();
9964 if (Mode != "kernel" && Mode != "translation_unit" &&
9965 Mode != "link_unit")
9966 C.getDriver().Diag(clang::diag::err_drv_invalid_value)
9967 << A->getSpelling() << Mode;
9968 else
9969 LinkerArgs.emplace_back(
9970 Args.MakeArgString("--module-split-mode=" + Mode));
9971 }
9972 }
9973
9974 // Forward all of these to the appropriate toolchain.
9975 for (StringRef Arg : CompilerArgs)
9976 CmdArgs.push_back(Args.MakeArgString(
9977 "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9978 for (StringRef Arg : LinkerArgs)
9979 CmdArgs.push_back(Args.MakeArgString(
9980 "--device-linker=" + TC->getTripleString() + "=" + Arg));
9981
9982 // Forward the LTO mode for this toolchain.
9983 auto DeviceLTOMode = TC->getLTOMode(ToolChainArgs, Kind);
9984 if (DeviceLTOMode == LTOK_Full)
9985 CmdArgs.push_back(Args.MakeArgString(
9986 "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9987 else if (DeviceLTOMode == LTOK_Thin) {
9988 CmdArgs.push_back(Args.MakeArgString(
9989 "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9990 if (TC->getTriple().isAMDGPU()) {
9991 CmdArgs.push_back(
9992 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9993 "=-plugin-opt=-force-import-all"));
9994 CmdArgs.push_back(
9995 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
9996 "=-plugin-opt=-avail-extern-to-local"));
9997 CmdArgs.push_back(Args.MakeArgString(
9998 "--device-linker=" + TC->getTripleString() +
9999 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
10000 if (Kind == Action::OFK_OpenMP) {
10001 CmdArgs.push_back(
10002 Args.MakeArgString("--device-linker=" + TC->getTripleString() +
10003 "=-plugin-opt=-amdgpu-internalize-symbols"));
10004 }
10005 }
10006 }
10007 }
10008 }
10009
10010 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
10011 CmdArgs.push_back(
10012 Args.MakeArgString("--host-triple=" + AuxTriple->getTriple()));
10013 else
10014 CmdArgs.push_back(Args.MakeArgString("--host-triple=" +
10015 getToolChain().getTripleString()));
10016
10017 if (Args.hasArg(options::OPT_v) && !SuppressHIPNoRDCVerbose)
10018 CmdArgs.push_back("--wrapper-verbose");
10019 if (Arg *A = Args.getLastArg(options::OPT_cuda_path_EQ)) {
10020 CmdArgs.push_back(
10021 Args.MakeArgString(Twine("--cuda-path=") + A->getValue()));
10022 CmdArgs.push_back(Args.MakeArgString(
10023 Twine("--device-compiler=--cuda-path=") + A->getValue()));
10024 }
10025 if (Arg *A = Args.getLastArg(options::OPT_rocm_path_EQ)) {
10026 CmdArgs.push_back(Args.MakeArgString(
10027 Twine("--device-compiler=--rocm-path=") + A->getValue()));
10028 }
10029
10030 // Construct the link job so we can wrap around it.
10031 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
10032 const auto &LinkCommand = C.getJobs().getJobs().back();
10033
10034 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
10035 // wrapper.
10036 for (Arg *A :
10037 Args.filtered(options::OPT_Xoffload_compiler, OPT_Xoffload_linker)) {
10038 StringRef Val = A->getValue(0);
10039 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
10040 auto WrapperOption =
10041 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
10042 if (Val.empty())
10043 CmdArgs.push_back(Args.MakeArgString(WrapperOption + A->getValue(1)));
10044 else
10045 CmdArgs.push_back(Args.MakeArgString(
10046 WrapperOption +
10047 ToolChain::normalizeOffloadTriple(Val.drop_front()).str() + "=" +
10048 A->getValue(1)));
10049 }
10050 Args.ClaimAllArgs(options::OPT_Xoffload_compiler);
10051 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
10052
10053 // Embed bitcode instead of an object in JIT mode.
10054 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
10055 options::OPT_fno_openmp_target_jit, false))
10056 CmdArgs.push_back("--embed-bitcode");
10057
10058 // Save temporary files created by the linker wrapper.
10059 if (Args.hasArg(options::OPT_save_temps_EQ) ||
10060 Args.hasArg(options::OPT_save_temps))
10061 CmdArgs.push_back("--save-temps");
10062
10063 // Pass in the C library for GPUs if present and not disabled.
10064 if (Args.hasFlag(options::OPT_offloadlib, OPT_no_offloadlib, true) &&
10065 !Args.hasArg(options::OPT_nostdlib, options::OPT_r,
10066 options::OPT_nodefaultlibs, options::OPT_nolibc,
10067 options::OPT_nogpulibc)) {
10068 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
10069 // The device C library is only available for NVPTX and AMDGPU targets
10070 // and we only link it by default for OpenMP currently.
10071 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
10073 return;
10074 bool HasLibC = TC.getStdlibIncludePath().has_value();
10075 if (HasLibC) {
10076 CmdArgs.push_back(Args.MakeArgString(
10077 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
10078 CmdArgs.push_back(Args.MakeArgString(
10079 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
10080 }
10081 auto HasCompilerRT = getToolChain().getVFS().exists(
10082 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static,
10083 /*IsFortran=*/false));
10084 if (HasCompilerRT)
10085 CmdArgs.push_back(
10086 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10087 "-lclang_rt.builtins"));
10088
10089 bool HasFlangRT = getToolChain().getVFS().exists(
10090 TC.getCompilerRT(Args, "runtime", ToolChain::FT_Static,
10091 /*IsFortran=*/true));
10092 if (HasFlangRT && C.getDriver().IsFlangMode())
10093 CmdArgs.push_back(
10094 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
10095 "-lflang_rt.runtime"));
10096 });
10097 }
10098
10099 // Add the linker arguments to be forwarded by the wrapper.
10100 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
10101 LinkCommand->getExecutable()));
10102
10103 // We use action type to differentiate two use cases of the linker wrapper.
10104 // TY_Image for normal linker wrapper work.
10105 // TY_HIP_FATBIN for HIP device-only links emitting a fat binary directly.
10106 assert(JA.getType() == types::TY_HIP_FATBIN ||
10107 JA.getType() == types::TY_Image);
10108 if (JA.getType() == types::TY_HIP_FATBIN) {
10109 CmdArgs.push_back("--emit-fatbin-only");
10110 CmdArgs.append({"-o", Output.getFilename()});
10111 for (auto Input : Inputs)
10112 CmdArgs.push_back(Input.getFilename());
10113 } else {
10114 for (const char *LinkArg : LinkCommand->getArguments())
10115 CmdArgs.push_back(LinkArg);
10116 }
10117
10118 addOffloadCompressArgs(Args, CmdArgs);
10119
10120 OffloadJobsOpt OffloadJobs = parseOffloadJobs(Args);
10121 if (OffloadJobs.A) {
10122 if (OffloadJobs.K == OffloadJobsOpt::Kind::Jobserver) {
10123 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=jobserver"));
10124 } else if (OffloadJobs.K == OffloadJobsOpt::Kind::Fixed) {
10125 CmdArgs.push_back(Args.MakeArgString("--wrapper-jobs=" +
10126 Twine(OffloadJobs.NumThreads)));
10127 } else if (!OffloadJobs.A->isClaimed()) {
10128 C.getDriver().Diag(diag::err_drv_invalid_int_value)
10129 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
10130 }
10131 }
10132
10133 // Propagate -no-canonical-prefixes.
10134 if (Args.hasArg(options::OPT_no_canonical_prefixes))
10135 CmdArgs.push_back("--no-canonical-prefixes");
10136
10137 const char *Exec =
10138 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
10139
10140 // Replace the executable and arguments of the link job with the
10141 // wrapper.
10142 LinkCommand->replaceExecutable(Exec);
10143 LinkCommand->replaceArguments(CmdArgs);
10144}
#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:3912
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition Clang.cpp:117
static void pushBackLLVMArg(ArgStringList &CmdArgs, const char *A)
Definition Clang.cpp:2291
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition Clang.cpp:4330
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition Clang.cpp:707
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:5092
static bool requiresProfileRT(unsigned ID)
Definition Clang.cpp:9779
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4511
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition Clang.cpp:756
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:70
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:1351
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition Clang.cpp:1203
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:8827
static void checkAndRemoveLLVMArg(ArgStringList &CmdArgs, StringRef Opt)
Definition Clang.cpp:2270
static bool gchProbe(const Driver &D, StringRef Path)
Definition Clang.cpp:773
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:4010
static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D, const ArgList &Args)
Definition Clang.cpp:4642
static bool CheckARMImplicitITArg(StringRef Value)
Definition Clang.cpp:2541
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1241
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition Clang.cpp:733
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:337
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition Clang.cpp:4619
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:4366
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:322
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition Clang.cpp:2546
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1252
static void addQFloatBackendArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:2322
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition Clang.cpp:2552
static StringRef getOptionName(StringRef Option, const char Delimiter='=')
Definition Clang.cpp:2263
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition Clang.cpp:4076
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:97
static bool isValidSymbolName(StringRef S)
Definition Clang.cpp:3586
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:307
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:137
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1268
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition Clang.cpp:252
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition Clang.cpp:1387
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition Clang.cpp:3596
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:4018
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3824
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Clang.cpp:3841
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition Clang.cpp:8806
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:232
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition Clang.cpp:85
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition Clang.cpp:215
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:4659
static bool requiresUBSanRT(unsigned ID)
Definition Clang.cpp:9797
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:286
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition Clang.cpp:3517
static void addQFloatLossyFastMathArgs(ArgStringList &CmdArgs)
Definition Clang.cpp:2297
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition Clang.cpp:2917
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:368
static void RenderHLSLOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition Clang.cpp:3956
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:926
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:32
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:154
const ToolChain * getOffloadingToolChain() const
Definition Action.h:218
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition Action.cpp:148
BoundArch getOffloadingArch() const
Definition Action.h:217
ActionClass getKind() const
Definition Action.h:153
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition Action.cpp:164
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:216
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:224
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:227
ActionList & getInputs()
Definition Action.h:156
unsigned getOffloadingHostActiveKinds() const
Definition Action.h:212
bool isOffloading(OffloadKind OKind) const
Definition Action.h:230
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:96
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:4969
std::string SysRoot
sysroot, if present
Definition Driver.h:196
DiagnosticsEngine & getDiags() const
Definition Driver.h:410
const char * getPrependArg() const
Definition Driver.h:421
CC1ToolFunc CC1Main
Definition Driver.h:292
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:896
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:232
unsigned CCLogDiagnostics
Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics to CCLogDiagnosticsFilename...
Definition Driver.h:270
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition Clang.cpp:4042
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:274
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:160
unsigned CCPrintInternalStats
Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal performance report to CC_PR...
Definition Driver.h:284
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
Definition Driver.cpp:7115
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition Driver.cpp:2487
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:432
std::string CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition Driver.h:220
std::string CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition Driver.h:217
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:180
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:412
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:171
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:156
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:146
HeaderIncludeFormatKind CCPrintHeadersFormat
The format of the header information that is emitted.
Definition Driver.h:253
std::string getTargetTriple() const
Definition Driver.h:429
HeaderIncludeFilteringKind CCPrintHeadersFiltering
This flag determines whether clang should filter the header information that is emitted.
Definition Driver.h:259
std::string DriverExecutable
The original path to the driver executable.
Definition Driver.h:174
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition Driver.h:226
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:223
bool getProbePrecompiled() const
Definition Driver.h:418
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:274
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:96
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:909
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition ToolChain.h:658
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:667
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition ToolChain.h:691
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:901
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:649
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition ToolChain.h:521
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:302
const Driver & getDriver() const
Definition ToolChain.h:286
RTTIMode getRTTIMode() const
Definition ToolChain.h:369
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:680
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:314
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition ToolChain.h:542
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:513
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition ToolChain.h:702
virtual bool GetDefaultStandaloneDebug() const
Definition ToolChain.h:673
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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:677
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:311
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition ToolChain.h:536
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition ToolChain.h:742
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:655
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition ToolChain.h:643
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:896
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:525
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:488
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:646
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:517
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition ToolChain.h:484
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:295
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition ToolChain.h:510
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
const ToolChain & getToolChain() const
Definition Tool.h:52
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:14
const char * getShortName() const
Definition Tool.h:50
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition XRayArgs.cpp:181
static std::optional< std::string > GetHVXVersion(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:1029
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition Hexagon.cpp:653
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9228
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9211
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9236
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:9251
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Clang.cpp:9200
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition Clang.cpp:9170
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition Clang.cpp:8661
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9185
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition Clang.cpp:9175
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:5192
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:9809
void ConstructJobMultipleOutputs(Compilation &C, const JobAction &JA, const InputInfoList &Outputs, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
Construct jobs to perform the action JA, writing to the Outputs and with Inputs, and add the jobs to ...
Definition Clang.cpp:9647
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:9557
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:9720
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:441
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 addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void handleVectorizeSLPArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fslp-vectorize based on the optimization level selected.
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 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)
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:326
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition Types.cpp:237
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:289
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:250
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition Types.cpp:328
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:262
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:52
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
U cast(CodeGen::Address addr)
Definition Address.h:327
StringRef parseMRecipOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition Version.cpp:96
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
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