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