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