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