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