clang 20.0.0git
Clang.cpp
Go to the documentation of this file.
1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "AMDGPU.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/CSKY.h"
14#include "Arch/LoongArch.h"
15#include "Arch/M68k.h"
16#include "Arch/Mips.h"
17#include "Arch/PPC.h"
18#include "Arch/RISCV.h"
19#include "Arch/Sparc.h"
20#include "Arch/SystemZ.h"
21#include "Arch/VE.h"
22#include "Arch/X86.h"
23#include "CommonArgs.h"
24#include "Hexagon.h"
25#include "MSP430.h"
26#include "PS4CPU.h"
34#include "clang/Basic/Version.h"
35#include "clang/Config/config.h"
36#include "clang/Driver/Action.h"
37#include "clang/Driver/Distro.h"
42#include "clang/Driver/Types.h"
44#include "llvm/ADT/SmallSet.h"
45#include "llvm/ADT/StringExtras.h"
46#include "llvm/BinaryFormat/Magic.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/Frontend/Debug/Options.h"
49#include "llvm/Object/ObjectFile.h"
50#include "llvm/Option/ArgList.h"
51#include "llvm/Support/CodeGen.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/Compression.h"
54#include "llvm/Support/Error.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/Path.h"
57#include "llvm/Support/Process.h"
58#include "llvm/Support/YAMLParser.h"
59#include "llvm/TargetParser/AArch64TargetParser.h"
60#include "llvm/TargetParser/ARMTargetParserCommon.h"
61#include "llvm/TargetParser/Host.h"
62#include "llvm/TargetParser/LoongArchTargetParser.h"
63#include "llvm/TargetParser/PPCTargetParser.h"
64#include "llvm/TargetParser/RISCVISAInfo.h"
65#include "llvm/TargetParser/RISCVTargetParser.h"
66#include <cctype>
67
68using namespace clang::driver;
69using namespace clang::driver::tools;
70using namespace clang;
71using namespace llvm::opt;
72
73static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
74 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
75 options::OPT_fminimize_whitespace,
76 options::OPT_fno_minimize_whitespace,
77 options::OPT_fkeep_system_includes,
78 options::OPT_fno_keep_system_includes)) {
79 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
80 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
81 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
82 << A->getBaseArg().getAsString(Args)
83 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
84 }
85 }
86}
87
88static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
89 // In gcc, only ARM checks this, but it seems reasonable to check universally.
90 if (Args.hasArg(options::OPT_static))
91 if (const Arg *A =
92 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
93 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
94 << "-static";
95}
96
97// Add backslashes to escape spaces and other backslashes.
98// This is used for the space-separated argument list specified with
99// the -dwarf-debug-flags option.
100static void EscapeSpacesAndBackslashes(const char *Arg,
102 for (; *Arg; ++Arg) {
103 switch (*Arg) {
104 default:
105 break;
106 case ' ':
107 case '\\':
108 Res.push_back('\\');
109 break;
110 }
111 Res.push_back(*Arg);
112 }
113}
114
115/// Apply \a Work on the current tool chain \a RegularToolChain and any other
116/// offloading tool chain that is associated with the current action \a JA.
117static void
119 const ToolChain &RegularToolChain,
120 llvm::function_ref<void(const ToolChain &)> Work) {
121 // Apply Work on the current/regular tool chain.
122 Work(RegularToolChain);
123
124 // Apply Work on all the offloading tool chains associated with the current
125 // action.
127 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
129 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
131 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
134
136 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
137 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
138 Work(*II->second);
140 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
141
142 //
143 // TODO: Add support for other offloading programming models here.
144 //
145}
146
147/// This is a helper function for validating the optional refinement step
148/// parameter in reciprocal argument strings. Return false if there is an error
149/// parsing the refinement step. Otherwise, return true and set the Position
150/// of the refinement step in the input string.
151static bool getRefinementStep(StringRef In, const Driver &D,
152 const Arg &A, size_t &Position) {
153 const char RefinementStepToken = ':';
154 Position = In.find(RefinementStepToken);
155 if (Position != StringRef::npos) {
156 StringRef Option = A.getOption().getName();
157 StringRef RefStep = In.substr(Position + 1);
158 // Allow exactly one numeric character for the additional refinement
159 // step parameter. This is reasonable for all currently-supported
160 // operations and architectures because we would expect that a larger value
161 // of refinement steps would cause the estimate "optimization" to
162 // under-perform the native operation. Also, if the estimate does not
163 // converge quickly, it probably will not ever converge, so further
164 // refinement steps will not produce a better answer.
165 if (RefStep.size() != 1) {
166 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
167 return false;
168 }
169 char RefStepChar = RefStep[0];
170 if (RefStepChar < '0' || RefStepChar > '9') {
171 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
172 return false;
173 }
174 }
175 return true;
176}
177
178/// The -mrecip flag requires processing of many optional parameters.
179static void ParseMRecip(const Driver &D, const ArgList &Args,
180 ArgStringList &OutStrings) {
181 StringRef DisabledPrefixIn = "!";
182 StringRef DisabledPrefixOut = "!";
183 StringRef EnabledPrefixOut = "";
184 StringRef Out = "-mrecip=";
185
186 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
187 if (!A)
188 return;
189
190 unsigned NumOptions = A->getNumValues();
191 if (NumOptions == 0) {
192 // No option is the same as "all".
193 OutStrings.push_back(Args.MakeArgString(Out + "all"));
194 return;
195 }
196
197 // Pass through "all", "none", or "default" with an optional refinement step.
198 if (NumOptions == 1) {
199 StringRef Val = A->getValue(0);
200 size_t RefStepLoc;
201 if (!getRefinementStep(Val, D, *A, RefStepLoc))
202 return;
203 StringRef ValBase = Val.slice(0, RefStepLoc);
204 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
205 OutStrings.push_back(Args.MakeArgString(Out + Val));
206 return;
207 }
208 }
209
210 // Each reciprocal type may be enabled or disabled individually.
211 // Check each input value for validity, concatenate them all back together,
212 // and pass through.
213
214 llvm::StringMap<bool> OptionStrings;
215 OptionStrings.insert(std::make_pair("divd", false));
216 OptionStrings.insert(std::make_pair("divf", false));
217 OptionStrings.insert(std::make_pair("divh", false));
218 OptionStrings.insert(std::make_pair("vec-divd", false));
219 OptionStrings.insert(std::make_pair("vec-divf", false));
220 OptionStrings.insert(std::make_pair("vec-divh", false));
221 OptionStrings.insert(std::make_pair("sqrtd", false));
222 OptionStrings.insert(std::make_pair("sqrtf", false));
223 OptionStrings.insert(std::make_pair("sqrth", false));
224 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
225 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
226 OptionStrings.insert(std::make_pair("vec-sqrth", false));
227
228 for (unsigned i = 0; i != NumOptions; ++i) {
229 StringRef Val = A->getValue(i);
230
231 bool IsDisabled = Val.starts_with(DisabledPrefixIn);
232 // Ignore the disablement token for string matching.
233 if (IsDisabled)
234 Val = Val.substr(1);
235
236 size_t RefStep;
237 if (!getRefinementStep(Val, D, *A, RefStep))
238 return;
239
240 StringRef ValBase = Val.slice(0, RefStep);
241 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
242 if (OptionIter == OptionStrings.end()) {
243 // Try again specifying float suffix.
244 OptionIter = OptionStrings.find(ValBase.str() + 'f');
245 if (OptionIter == OptionStrings.end()) {
246 // The input name did not match any known option string.
247 D.Diag(diag::err_drv_unknown_argument) << Val;
248 return;
249 }
250 // The option was specified without a half or float or double suffix.
251 // Make sure that the double or half entry was not already specified.
252 // The float entry will be checked below.
253 if (OptionStrings[ValBase.str() + 'd'] ||
254 OptionStrings[ValBase.str() + 'h']) {
255 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256 return;
257 }
258 }
259
260 if (OptionIter->second == true) {
261 // Duplicate option specified.
262 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
263 return;
264 }
265
266 // Mark the matched option as found. Do not allow duplicate specifiers.
267 OptionIter->second = true;
268
269 // If the precision was not specified, also mark the double and half entry
270 // as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
272 OptionStrings[ValBase.str() + 'd'] = true;
273 OptionStrings[ValBase.str() + 'h'] = true;
274 }
275
276 // Build the output string.
277 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
278 Out = Args.MakeArgString(Out + Prefix + Val);
279 if (i != NumOptions - 1)
280 Out = Args.MakeArgString(Out + ",");
281 }
282
283 OutStrings.push_back(Args.MakeArgString(Out));
284}
285
286/// The -mprefer-vector-width option accepts either a positive integer
287/// or the string "none".
288static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
289 ArgStringList &CmdArgs) {
290 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
291 if (!A)
292 return;
293
294 StringRef Value = A->getValue();
295 if (Value == "none") {
296 CmdArgs.push_back("-mprefer-vector-width=none");
297 } else {
298 unsigned Width;
299 if (Value.getAsInteger(10, Width)) {
300 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
301 return;
302 }
303 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
304 }
305}
306
307static bool
309 const llvm::Triple &Triple) {
310 // We use the zero-cost exception tables for Objective-C if the non-fragile
311 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
312 // later.
313 if (runtime.isNonFragile())
314 return true;
315
316 if (!Triple.isMacOSX())
317 return false;
318
319 return (!Triple.isMacOSXVersionLT(10, 5) &&
320 (Triple.getArch() == llvm::Triple::x86_64 ||
321 Triple.getArch() == llvm::Triple::arm));
322}
323
324/// Adds exception related arguments to the driver command arguments. There's a
325/// main flag, -fexceptions and also language specific flags to enable/disable
326/// C++ and Objective-C exceptions. This makes it possible to for example
327/// disable C++ exceptions but enable Objective-C exceptions.
328static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
329 const ToolChain &TC, bool KernelOrKext,
330 const ObjCRuntime &objcRuntime,
331 ArgStringList &CmdArgs) {
332 const llvm::Triple &Triple = TC.getTriple();
333
334 if (KernelOrKext) {
335 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
336 // arguments now to avoid warnings about unused arguments.
337 Args.ClaimAllArgs(options::OPT_fexceptions);
338 Args.ClaimAllArgs(options::OPT_fno_exceptions);
339 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
340 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
341 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
342 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
343 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
344 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
345 return false;
346 }
347
348 // See if the user explicitly enabled exceptions.
349 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
350 false);
351
352 // Async exceptions are Windows MSVC only.
353 if (Triple.isWindowsMSVCEnvironment()) {
354 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
355 options::OPT_fno_async_exceptions, false);
356 if (EHa) {
357 CmdArgs.push_back("-fasync-exceptions");
358 EH = true;
359 }
360 }
361
362 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
363 // is not necessarily sensible, but follows GCC.
364 if (types::isObjC(InputType) &&
365 Args.hasFlag(options::OPT_fobjc_exceptions,
366 options::OPT_fno_objc_exceptions, true)) {
367 CmdArgs.push_back("-fobjc-exceptions");
368
369 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
370 }
371
372 if (types::isCXX(InputType)) {
373 // Disable C++ EH by default on XCore and PS4/PS5.
374 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
375 !Triple.isPS() && !Triple.isDriverKit();
376 Arg *ExceptionArg = Args.getLastArg(
377 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
378 options::OPT_fexceptions, options::OPT_fno_exceptions);
379 if (ExceptionArg)
380 CXXExceptionsEnabled =
381 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
382 ExceptionArg->getOption().matches(options::OPT_fexceptions);
383
384 if (CXXExceptionsEnabled) {
385 CmdArgs.push_back("-fcxx-exceptions");
386
387 EH = true;
388 }
389 }
390
391 // OPT_fignore_exceptions means exception could still be thrown,
392 // but no clean up or catch would happen in current module.
393 // So we do not set EH to false.
394 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
395
396 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
397 options::OPT_fno_assume_nothrow_exception_dtor);
398
399 if (EH)
400 CmdArgs.push_back("-fexceptions");
401 return EH;
402}
403
404static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
405 const JobAction &JA) {
406 bool Default = true;
407 if (TC.getTriple().isOSDarwin()) {
408 // The native darwin assembler doesn't support the linker_option directives,
409 // so we disable them if we think the .s file will be passed to it.
411 }
412 // The linker_option directives are intended for host compilation.
415 Default = false;
416 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
417 Default);
418}
419
420/// Add a CC1 option to specify the debug compilation directory.
421static const char *addDebugCompDirArg(const ArgList &Args,
422 ArgStringList &CmdArgs,
423 const llvm::vfs::FileSystem &VFS) {
424 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
425 options::OPT_fdebug_compilation_dir_EQ)) {
426 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
427 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
428 A->getValue()));
429 else
430 A->render(Args, CmdArgs);
431 } else if (llvm::ErrorOr<std::string> CWD =
432 VFS.getCurrentWorkingDirectory()) {
433 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
434 }
435 StringRef Path(CmdArgs.back());
436 return Path.substr(Path.find('=') + 1).data();
437}
438
439static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
440 const char *DebugCompilationDir,
441 const char *OutputFileName) {
442 // No need to generate a value for -object-file-name if it was provided.
443 for (auto *Arg : Args.filtered(options::OPT_Xclang))
444 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
445 return;
446
447 if (Args.hasArg(options::OPT_object_file_name_EQ))
448 return;
449
450 SmallString<128> ObjFileNameForDebug(OutputFileName);
451 if (ObjFileNameForDebug != "-" &&
452 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
453 (!DebugCompilationDir ||
454 llvm::sys::path::is_absolute(DebugCompilationDir))) {
455 // Make the path absolute in the debug infos like MSVC does.
456 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
457 }
458 // If the object file name is a relative path, then always use Windows
459 // backslash style as -object-file-name is used for embedding object file path
460 // in codeview and it can only be generated when targeting on Windows.
461 // Otherwise, just use native absolute path.
462 llvm::sys::path::Style Style =
463 llvm::sys::path::is_absolute(ObjFileNameForDebug)
464 ? llvm::sys::path::Style::native
465 : llvm::sys::path::Style::windows_backslash;
466 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
467 Style);
468 CmdArgs.push_back(
469 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
470}
471
472/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
473static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
474 const ArgList &Args, ArgStringList &CmdArgs) {
475 auto AddOneArg = [&](StringRef Map, StringRef Name) {
476 if (!Map.contains('='))
477 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
478 else
479 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
480 };
481
482 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
483 options::OPT_fdebug_prefix_map_EQ)) {
484 AddOneArg(A->getValue(), A->getOption().getName());
485 A->claim();
486 }
487 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
488 if (GlobalRemapEntry.empty())
489 return;
490 AddOneArg(GlobalRemapEntry, "environment");
491}
492
493/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
494static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
495 ArgStringList &CmdArgs) {
496 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
497 options::OPT_fmacro_prefix_map_EQ)) {
498 StringRef Map = A->getValue();
499 if (!Map.contains('='))
500 D.Diag(diag::err_drv_invalid_argument_to_option)
501 << Map << A->getOption().getName();
502 else
503 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
504 A->claim();
505 }
506}
507
508/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
509static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
510 ArgStringList &CmdArgs) {
511 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
512 options::OPT_fcoverage_prefix_map_EQ)) {
513 StringRef Map = A->getValue();
514 if (!Map.contains('='))
515 D.Diag(diag::err_drv_invalid_argument_to_option)
516 << Map << A->getOption().getName();
517 else
518 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
519 A->claim();
520 }
521}
522
523/// Vectorize at all optimization levels greater than 1 except for -Oz.
524/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
525/// enabled.
526static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
527 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
528 if (A->getOption().matches(options::OPT_O4) ||
529 A->getOption().matches(options::OPT_Ofast))
530 return true;
531
532 if (A->getOption().matches(options::OPT_O0))
533 return false;
534
535 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
536
537 // Vectorize -Os.
538 StringRef S(A->getValue());
539 if (S == "s")
540 return true;
541
542 // Don't vectorize -Oz, unless it's the slp vectorizer.
543 if (S == "z")
544 return isSlpVec;
545
546 unsigned OptLevel = 0;
547 if (S.getAsInteger(10, OptLevel))
548 return false;
549
550 return OptLevel > 1;
551 }
552
553 return false;
554}
555
556/// Add -x lang to \p CmdArgs for \p Input.
557static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
558 ArgStringList &CmdArgs) {
559 // When using -verify-pch, we don't want to provide the type
560 // 'precompiled-header' if it was inferred from the file extension
561 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
562 return;
563
564 CmdArgs.push_back("-x");
565 if (Args.hasArg(options::OPT_rewrite_objc))
566 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
567 else {
568 // Map the driver type to the frontend type. This is mostly an identity
569 // mapping, except that the distinction between module interface units
570 // and other source files does not exist at the frontend layer.
571 const char *ClangType;
572 switch (Input.getType()) {
573 case types::TY_CXXModule:
574 ClangType = "c++";
575 break;
576 case types::TY_PP_CXXModule:
577 ClangType = "c++-cpp-output";
578 break;
579 default:
580 ClangType = types::getTypeName(Input.getType());
581 break;
582 }
583 CmdArgs.push_back(ClangType);
584 }
585}
586
588 const JobAction &JA, const InputInfo &Output,
589 const ArgList &Args, SanitizerArgs &SanArgs,
590 ArgStringList &CmdArgs) {
591 const Driver &D = TC.getDriver();
592 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
593 options::OPT_fprofile_generate_EQ,
594 options::OPT_fno_profile_generate);
595 if (PGOGenerateArg &&
596 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
597 PGOGenerateArg = nullptr;
598
599 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
600
601 auto *ProfileGenerateArg = Args.getLastArg(
602 options::OPT_fprofile_instr_generate,
603 options::OPT_fprofile_instr_generate_EQ,
604 options::OPT_fno_profile_instr_generate);
605 if (ProfileGenerateArg &&
606 ProfileGenerateArg->getOption().matches(
607 options::OPT_fno_profile_instr_generate))
608 ProfileGenerateArg = nullptr;
609
610 if (PGOGenerateArg && ProfileGenerateArg)
611 D.Diag(diag::err_drv_argument_not_allowed_with)
612 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
613
614 auto *ProfileUseArg = getLastProfileUseArg(Args);
615
616 if (PGOGenerateArg && ProfileUseArg)
617 D.Diag(diag::err_drv_argument_not_allowed_with)
618 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
619
620 if (ProfileGenerateArg && ProfileUseArg)
621 D.Diag(diag::err_drv_argument_not_allowed_with)
622 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
623
624 if (CSPGOGenerateArg && PGOGenerateArg) {
625 D.Diag(diag::err_drv_argument_not_allowed_with)
626 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
627 PGOGenerateArg = nullptr;
628 }
629
630 if (TC.getTriple().isOSAIX()) {
631 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
632 D.Diag(diag::err_drv_unsupported_opt_for_target)
633 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
634 }
635
636 if (ProfileGenerateArg) {
637 if (ProfileGenerateArg->getOption().matches(
638 options::OPT_fprofile_instr_generate_EQ))
639 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
640 ProfileGenerateArg->getValue()));
641 // The default is to use Clang Instrumentation.
642 CmdArgs.push_back("-fprofile-instrument=clang");
643 if (TC.getTriple().isWindowsMSVCEnvironment() &&
644 Args.hasFlag(options::OPT_frtlib_defaultlib,
645 options::OPT_fno_rtlib_defaultlib, true)) {
646 // Add dependent lib for clang_rt.profile
647 CmdArgs.push_back(Args.MakeArgString(
648 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
649 }
650 }
651
652 Arg *PGOGenArg = nullptr;
653 if (PGOGenerateArg) {
654 assert(!CSPGOGenerateArg);
655 PGOGenArg = PGOGenerateArg;
656 CmdArgs.push_back("-fprofile-instrument=llvm");
657 }
658 if (CSPGOGenerateArg) {
659 assert(!PGOGenerateArg);
660 PGOGenArg = CSPGOGenerateArg;
661 CmdArgs.push_back("-fprofile-instrument=csllvm");
662 }
663 if (PGOGenArg) {
664 if (TC.getTriple().isWindowsMSVCEnvironment() &&
665 Args.hasFlag(options::OPT_frtlib_defaultlib,
666 options::OPT_fno_rtlib_defaultlib, true)) {
667 // Add dependent lib for clang_rt.profile
668 CmdArgs.push_back(Args.MakeArgString(
669 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
670 }
671 if (PGOGenArg->getOption().matches(
672 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
673 : options::OPT_fcs_profile_generate_EQ)) {
674 SmallString<128> Path(PGOGenArg->getValue());
675 llvm::sys::path::append(Path, "default_%m.profraw");
676 CmdArgs.push_back(
677 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
678 }
679 }
680
681 if (ProfileUseArg) {
682 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
683 CmdArgs.push_back(Args.MakeArgString(
684 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
685 else if ((ProfileUseArg->getOption().matches(
686 options::OPT_fprofile_use_EQ) ||
687 ProfileUseArg->getOption().matches(
688 options::OPT_fprofile_instr_use))) {
690 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
691 if (Path.empty() || llvm::sys::fs::is_directory(Path))
692 llvm::sys::path::append(Path, "default.profdata");
693 CmdArgs.push_back(
694 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
695 }
696 }
697
698 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
699 options::OPT_fno_test_coverage, false) ||
700 Args.hasArg(options::OPT_coverage);
701 bool EmitCovData = TC.needsGCovInstrumentation(Args);
702
703 if (Args.hasFlag(options::OPT_fcoverage_mapping,
704 options::OPT_fno_coverage_mapping, false)) {
705 if (!ProfileGenerateArg)
706 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
707 << "-fcoverage-mapping"
708 << "-fprofile-instr-generate";
709
710 CmdArgs.push_back("-fcoverage-mapping");
711 }
712
713 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
714 false)) {
715 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
716 options::OPT_fno_coverage_mapping, false))
717 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
718 << "-fcoverage-mcdc"
719 << "-fcoverage-mapping";
720
721 CmdArgs.push_back("-fcoverage-mcdc");
722 }
723
724 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
725 options::OPT_fcoverage_compilation_dir_EQ)) {
726 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
727 CmdArgs.push_back(Args.MakeArgString(
728 Twine("-fcoverage-compilation-dir=") + A->getValue()));
729 else
730 A->render(Args, CmdArgs);
731 } else if (llvm::ErrorOr<std::string> CWD =
732 D.getVFS().getCurrentWorkingDirectory()) {
733 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
734 }
735
736 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
737 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
738 if (!Args.hasArg(options::OPT_coverage))
739 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
740 << "-fprofile-exclude-files="
741 << "--coverage";
742
743 StringRef v = Arg->getValue();
744 CmdArgs.push_back(
745 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
746 }
747
748 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
749 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
750 if (!Args.hasArg(options::OPT_coverage))
751 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
752 << "-fprofile-filter-files="
753 << "--coverage";
754
755 StringRef v = Arg->getValue();
756 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
757 }
758
759 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
760 StringRef Val = A->getValue();
761 if (Val == "atomic" || Val == "prefer-atomic")
762 CmdArgs.push_back("-fprofile-update=atomic");
763 else if (Val != "single")
764 D.Diag(diag::err_drv_unsupported_option_argument)
765 << A->getSpelling() << Val;
766 }
767
768 int FunctionGroups = 1;
769 int SelectedFunctionGroup = 0;
770 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
771 StringRef Val = A->getValue();
772 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
773 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
774 }
775 if (const auto *A =
776 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
777 StringRef Val = A->getValue();
778 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
779 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
780 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
781 }
782 if (FunctionGroups != 1)
783 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
784 Twine(FunctionGroups)));
785 if (SelectedFunctionGroup != 0)
786 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
787 Twine(SelectedFunctionGroup)));
788
789 // Leave -fprofile-dir= an unused argument unless .gcda emission is
790 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
791 // the flag used. There is no -fno-profile-dir, so the user has no
792 // targeted way to suppress the warning.
793 Arg *FProfileDir = nullptr;
794 if (Args.hasArg(options::OPT_fprofile_arcs) ||
795 Args.hasArg(options::OPT_coverage))
796 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
797
798 // Put the .gcno and .gcda files (if needed) next to the primary output file,
799 // or fall back to a file in the current directory for `clang -c --coverage
800 // d/a.c` in the absence of -o.
801 if (EmitCovNotes || EmitCovData) {
802 SmallString<128> CoverageFilename;
803 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
804 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
805 // path separator.
806 CoverageFilename = DumpDir->getValue();
807 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
808 } else if (Arg *FinalOutput =
809 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
810 CoverageFilename = FinalOutput->getValue();
811 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
812 CoverageFilename = FinalOutput->getValue();
813 } else {
814 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
815 }
816 if (llvm::sys::path::is_relative(CoverageFilename))
817 (void)D.getVFS().makeAbsolute(CoverageFilename);
818 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
819 if (EmitCovNotes) {
820 CmdArgs.push_back(
821 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
822 }
823
824 if (EmitCovData) {
825 if (FProfileDir) {
826 SmallString<128> Gcno = std::move(CoverageFilename);
827 CoverageFilename = FProfileDir->getValue();
828 llvm::sys::path::append(CoverageFilename, Gcno);
829 }
830 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
831 CmdArgs.push_back(
832 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
833 }
834 }
835}
836
837static void
838RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
839 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
840 unsigned DwarfVersion,
841 llvm::DebuggerKind DebuggerTuning) {
842 addDebugInfoKind(CmdArgs, DebugInfoKind);
843 if (DwarfVersion > 0)
844 CmdArgs.push_back(
845 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
846 switch (DebuggerTuning) {
847 case llvm::DebuggerKind::GDB:
848 CmdArgs.push_back("-debugger-tuning=gdb");
849 break;
850 case llvm::DebuggerKind::LLDB:
851 CmdArgs.push_back("-debugger-tuning=lldb");
852 break;
853 case llvm::DebuggerKind::SCE:
854 CmdArgs.push_back("-debugger-tuning=sce");
855 break;
856 case llvm::DebuggerKind::DBX:
857 CmdArgs.push_back("-debugger-tuning=dbx");
858 break;
859 default:
860 break;
861 }
862}
863
864static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
865 const Driver &D, const ToolChain &TC) {
866 assert(A && "Expected non-nullptr argument.");
867 if (TC.supportsDebugInfoOption(A))
868 return true;
869 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
870 << A->getAsString(Args) << TC.getTripleString();
871 return false;
872}
873
874static void RenderDebugInfoCompressionArgs(const ArgList &Args,
875 ArgStringList &CmdArgs,
876 const Driver &D,
877 const ToolChain &TC) {
878 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
879 if (!A)
880 return;
881 if (checkDebugInfoOption(A, Args, D, TC)) {
882 StringRef Value = A->getValue();
883 if (Value == "none") {
884 CmdArgs.push_back("--compress-debug-sections=none");
885 } else if (Value == "zlib") {
886 if (llvm::compression::zlib::isAvailable()) {
887 CmdArgs.push_back(
888 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
889 } else {
890 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
891 }
892 } else if (Value == "zstd") {
893 if (llvm::compression::zstd::isAvailable()) {
894 CmdArgs.push_back(
895 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
896 } else {
897 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
898 }
899 } else {
900 D.Diag(diag::err_drv_unsupported_option_argument)
901 << A->getSpelling() << Value;
902 }
903 }
904}
905
907 const ArgList &Args,
908 ArgStringList &CmdArgs,
909 bool IsCC1As = false) {
910 // If no version was requested by the user, use the default value from the
911 // back end. This is consistent with the value returned from
912 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
913 // requiring the corresponding llvm to have the AMDGPU target enabled,
914 // provided the user (e.g. front end tests) can use the default.
916 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
917 CmdArgs.insert(CmdArgs.begin() + 1,
918 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
919 Twine(CodeObjVer)));
920 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
921 // -cc1as does not accept -mcode-object-version option.
922 if (!IsCC1As)
923 CmdArgs.insert(CmdArgs.begin() + 1,
924 Args.MakeArgString(Twine("-mcode-object-version=") +
925 Twine(CodeObjVer)));
926 }
927}
928
929static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
930 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
931 D.getVFS().getBufferForFile(Path);
932 if (!MemBuf)
933 return false;
934 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
935 if (Magic == llvm::file_magic::unknown)
936 return false;
937 // Return true for both raw Clang AST files and object files which may
938 // contain a __clangast section.
939 if (Magic == llvm::file_magic::clang_ast)
940 return true;
942 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
943 return !Obj.takeError();
944}
945
946static bool gchProbe(const Driver &D, StringRef Path) {
947 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
948 if (!Status)
949 return false;
950
951 if (Status->isDirectory()) {
952 std::error_code EC;
953 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
954 !EC && DI != DE; DI = DI.increment(EC)) {
955 if (maybeHasClangPchSignature(D, DI->path()))
956 return true;
957 }
958 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
959 return false;
960 }
961
963 return true;
964 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
965 return false;
966}
967
968void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
969 const Driver &D, const ArgList &Args,
970 ArgStringList &CmdArgs,
971 const InputInfo &Output,
972 const InputInfoList &Inputs) const {
973 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
974
976
977 Args.AddLastArg(CmdArgs, options::OPT_C);
978 Args.AddLastArg(CmdArgs, options::OPT_CC);
979
980 // Handle dependency file generation.
981 Arg *ArgM = Args.getLastArg(options::OPT_MM);
982 if (!ArgM)
983 ArgM = Args.getLastArg(options::OPT_M);
984 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
985 if (!ArgMD)
986 ArgMD = Args.getLastArg(options::OPT_MD);
987
988 // -M and -MM imply -w.
989 if (ArgM)
990 CmdArgs.push_back("-w");
991 else
992 ArgM = ArgMD;
993
994 if (ArgM) {
995 // Determine the output location.
996 const char *DepFile;
997 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
998 DepFile = MF->getValue();
999 C.addFailureResultFile(DepFile, &JA);
1000 } else if (Output.getType() == types::TY_Dependencies) {
1001 DepFile = Output.getFilename();
1002 } else if (!ArgMD) {
1003 DepFile = "-";
1004 } else {
1005 DepFile = getDependencyFileName(Args, Inputs);
1006 C.addFailureResultFile(DepFile, &JA);
1007 }
1008 CmdArgs.push_back("-dependency-file");
1009 CmdArgs.push_back(DepFile);
1010
1011 bool HasTarget = false;
1012 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1013 HasTarget = true;
1014 A->claim();
1015 if (A->getOption().matches(options::OPT_MT)) {
1016 A->render(Args, CmdArgs);
1017 } else {
1018 CmdArgs.push_back("-MT");
1020 quoteMakeTarget(A->getValue(), Quoted);
1021 CmdArgs.push_back(Args.MakeArgString(Quoted));
1022 }
1023 }
1024
1025 // Add a default target if one wasn't specified.
1026 if (!HasTarget) {
1027 const char *DepTarget;
1028
1029 // If user provided -o, that is the dependency target, except
1030 // when we are only generating a dependency file.
1031 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
1032 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1033 DepTarget = OutputOpt->getValue();
1034 } else {
1035 // Otherwise derive from the base input.
1036 //
1037 // FIXME: This should use the computed output file location.
1038 SmallString<128> P(Inputs[0].getBaseInput());
1039 llvm::sys::path::replace_extension(P, "o");
1040 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1041 }
1042
1043 CmdArgs.push_back("-MT");
1045 quoteMakeTarget(DepTarget, Quoted);
1046 CmdArgs.push_back(Args.MakeArgString(Quoted));
1047 }
1048
1049 if (ArgM->getOption().matches(options::OPT_M) ||
1050 ArgM->getOption().matches(options::OPT_MD))
1051 CmdArgs.push_back("-sys-header-deps");
1052 if ((isa<PrecompileJobAction>(JA) &&
1053 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1054 Args.hasArg(options::OPT_fmodule_file_deps))
1055 CmdArgs.push_back("-module-file-deps");
1056 }
1057
1058 if (Args.hasArg(options::OPT_MG)) {
1059 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1060 ArgM->getOption().matches(options::OPT_MMD))
1061 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1062 CmdArgs.push_back("-MG");
1063 }
1064
1065 Args.AddLastArg(CmdArgs, options::OPT_MP);
1066 Args.AddLastArg(CmdArgs, options::OPT_MV);
1067
1068 // Add offload include arguments specific for CUDA/HIP. This must happen
1069 // before we -I or -include anything else, because we must pick up the
1070 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1071 // from e.g. /usr/local/include.
1073 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1075 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1076
1077 // If we are offloading to a target via OpenMP we need to include the
1078 // openmp_wrappers folder which contains alternative system headers.
1080 !Args.hasArg(options::OPT_nostdinc) &&
1081 !Args.hasArg(options::OPT_nogpuinc) &&
1082 (getToolChain().getTriple().isNVPTX() ||
1083 getToolChain().getTriple().isAMDGCN())) {
1084 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1085 // Add openmp_wrappers/* to our system include path. This lets us wrap
1086 // standard library headers.
1087 SmallString<128> P(D.ResourceDir);
1088 llvm::sys::path::append(P, "include");
1089 llvm::sys::path::append(P, "openmp_wrappers");
1090 CmdArgs.push_back("-internal-isystem");
1091 CmdArgs.push_back(Args.MakeArgString(P));
1092 }
1093
1094 CmdArgs.push_back("-include");
1095 CmdArgs.push_back("__clang_openmp_device_functions.h");
1096 }
1097
1098 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
1099 // Add llvm_wrappers/* to our system include path. This lets us wrap
1100 // standard library headers and other headers.
1101 SmallString<128> P(D.ResourceDir);
1102 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
1103 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
1105 CmdArgs.push_back("__llvm_offload_device.h");
1106 else
1107 CmdArgs.push_back("__llvm_offload_host.h");
1108 }
1109
1110 // Add -i* options, and automatically translate to
1111 // -include-pch/-include-pth for transparent PCH support. It's
1112 // wonky, but we include looking for .gch so we can support seamless
1113 // replacement into a build system already set up to be generating
1114 // .gch files.
1115
1116 if (getToolChain().getDriver().IsCLMode()) {
1117 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1118 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1119 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1121 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1122 // -fpch-instantiate-templates is the default when creating
1123 // precomp using /Yc
1124 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1125 options::OPT_fno_pch_instantiate_templates, true))
1126 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1127 }
1128 if (YcArg || YuArg) {
1129 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1130 if (!isa<PrecompileJobAction>(JA)) {
1131 CmdArgs.push_back("-include-pch");
1132 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1133 C, !ThroughHeader.empty()
1134 ? ThroughHeader
1135 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1136 }
1137
1138 if (ThroughHeader.empty()) {
1139 CmdArgs.push_back(Args.MakeArgString(
1140 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1141 } else {
1142 CmdArgs.push_back(
1143 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1144 }
1145 }
1146 }
1147
1148 bool RenderedImplicitInclude = false;
1149 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1150 if (A->getOption().matches(options::OPT_include) &&
1151 D.getProbePrecompiled()) {
1152 // Handling of gcc-style gch precompiled headers.
1153 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1154 RenderedImplicitInclude = true;
1155
1156 bool FoundPCH = false;
1157 SmallString<128> P(A->getValue());
1158 // We want the files to have a name like foo.h.pch. Add a dummy extension
1159 // so that replace_extension does the right thing.
1160 P += ".dummy";
1161 llvm::sys::path::replace_extension(P, "pch");
1162 if (D.getVFS().exists(P))
1163 FoundPCH = true;
1164
1165 if (!FoundPCH) {
1166 // For GCC compat, probe for a file or directory ending in .gch instead.
1167 llvm::sys::path::replace_extension(P, "gch");
1168 FoundPCH = gchProbe(D, P.str());
1169 }
1170
1171 if (FoundPCH) {
1172 if (IsFirstImplicitInclude) {
1173 A->claim();
1174 CmdArgs.push_back("-include-pch");
1175 CmdArgs.push_back(Args.MakeArgString(P));
1176 continue;
1177 } else {
1178 // Ignore the PCH if not first on command line and emit warning.
1179 D.Diag(diag::warn_drv_pch_not_first_include) << P
1180 << A->getAsString(Args);
1181 }
1182 }
1183 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1184 // Handling of paths which must come late. These entries are handled by
1185 // the toolchain itself after the resource dir is inserted in the right
1186 // search order.
1187 // Do not claim the argument so that the use of the argument does not
1188 // silently go unnoticed on toolchains which do not honour the option.
1189 continue;
1190 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1191 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1192 continue;
1193 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1194 // This is used only by the driver. No need to pass to cc1.
1195 continue;
1196 }
1197
1198 // Not translated, render as usual.
1199 A->claim();
1200 A->render(Args, CmdArgs);
1201 }
1202
1203 Args.addAllArgs(CmdArgs,
1204 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1205 options::OPT_F, options::OPT_index_header_map,
1206 options::OPT_embed_dir_EQ});
1207
1208 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1209
1210 // FIXME: There is a very unfortunate problem here, some troubled
1211 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1212 // really support that we would have to parse and then translate
1213 // those options. :(
1214 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1215 options::OPT_Xpreprocessor);
1216
1217 // -I- is a deprecated GCC feature, reject it.
1218 if (Arg *A = Args.getLastArg(options::OPT_I_))
1219 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1220
1221 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1222 // -isysroot to the CC1 invocation.
1223 StringRef sysroot = C.getSysRoot();
1224 if (sysroot != "") {
1225 if (!Args.hasArg(options::OPT_isysroot)) {
1226 CmdArgs.push_back("-isysroot");
1227 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1228 }
1229 }
1230
1231 // Parse additional include paths from environment variables.
1232 // FIXME: We should probably sink the logic for handling these from the
1233 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1234 // CPATH - included following the user specified includes (but prior to
1235 // builtin and standard includes).
1236 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1237 // C_INCLUDE_PATH - system includes enabled when compiling C.
1238 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1239 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1240 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1241 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1242 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1243 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1244 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1245
1246 // While adding the include arguments, we also attempt to retrieve the
1247 // arguments of related offloading toolchains or arguments that are specific
1248 // of an offloading programming model.
1249
1250 // Add C++ include arguments, if needed.
1251 if (types::isCXX(Inputs[0].getType())) {
1252 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1254 C, JA, getToolChain(),
1255 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1256 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1257 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1258 });
1259 }
1260
1261 // If we are compiling for a GPU target we want to override the system headers
1262 // with ones created by the 'libc' project if present.
1263 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1264 // OffloadKind as an argument.
1265 if (!Args.hasArg(options::OPT_nostdinc) &&
1266 !Args.hasArg(options::OPT_nogpuinc) &&
1267 !Args.hasArg(options::OPT_nobuiltininc)) {
1268 // Without an offloading language we will include these headers directly.
1269 // Offloading languages will instead only use the declarations stored in
1270 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1271 if ((getToolChain().getTriple().isNVPTX() ||
1272 getToolChain().getTriple().isAMDGCN()) &&
1273 C.getActiveOffloadKinds() == Action::OFK_None) {
1274 SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
1275 llvm::sys::path::append(P, "include");
1276 llvm::sys::path::append(P, getToolChain().getTripleString());
1277 CmdArgs.push_back("-internal-isystem");
1278 CmdArgs.push_back(Args.MakeArgString(P));
1279 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1280 // TODO: CUDA / HIP include their own headers for some common functions
1281 // implemented here. We'll need to clean those up so they do not conflict.
1282 SmallString<128> P(D.ResourceDir);
1283 llvm::sys::path::append(P, "include");
1284 llvm::sys::path::append(P, "llvm_libc_wrappers");
1285 CmdArgs.push_back("-internal-isystem");
1286 CmdArgs.push_back(Args.MakeArgString(P));
1287 }
1288 }
1289
1290 // Add system include arguments for all targets but IAMCU.
1291 if (!IsIAMCU)
1293 [&Args, &CmdArgs](const ToolChain &TC) {
1294 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1295 });
1296 else {
1297 // For IAMCU add special include arguments.
1298 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1299 }
1300
1301 addMacroPrefixMapArg(D, Args, CmdArgs);
1302 addCoveragePrefixMapArg(D, Args, CmdArgs);
1303
1304 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1305 options::OPT_fno_file_reproducible);
1306
1307 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1308 CmdArgs.push_back("-source-date-epoch");
1309 CmdArgs.push_back(Args.MakeArgString(Epoch));
1310 }
1311
1312 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1313 options::OPT_fno_define_target_os_macros);
1314}
1315
1316// FIXME: Move to target hook.
1317static bool isSignedCharDefault(const llvm::Triple &Triple) {
1318 switch (Triple.getArch()) {
1319 default:
1320 return true;
1321
1322 case llvm::Triple::aarch64:
1323 case llvm::Triple::aarch64_32:
1324 case llvm::Triple::aarch64_be:
1325 case llvm::Triple::arm:
1326 case llvm::Triple::armeb:
1327 case llvm::Triple::thumb:
1328 case llvm::Triple::thumbeb:
1329 if (Triple.isOSDarwin() || Triple.isOSWindows())
1330 return true;
1331 return false;
1332
1333 case llvm::Triple::ppc:
1334 case llvm::Triple::ppc64:
1335 if (Triple.isOSDarwin())
1336 return true;
1337 return false;
1338
1339 case llvm::Triple::hexagon:
1340 case llvm::Triple::ppcle:
1341 case llvm::Triple::ppc64le:
1342 case llvm::Triple::riscv32:
1343 case llvm::Triple::riscv64:
1344 case llvm::Triple::systemz:
1345 case llvm::Triple::xcore:
1346 return false;
1347 }
1348}
1349
1350static bool hasMultipleInvocations(const llvm::Triple &Triple,
1351 const ArgList &Args) {
1352 // Supported only on Darwin where we invoke the compiler multiple times
1353 // followed by an invocation to lipo.
1354 if (!Triple.isOSDarwin())
1355 return false;
1356 // If more than one "-arch <arch>" is specified, we're targeting multiple
1357 // architectures resulting in a fat binary.
1358 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1359}
1360
1361static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1362 const llvm::Triple &Triple) {
1363 // When enabling remarks, we need to error if:
1364 // * The remark file is specified but we're targeting multiple architectures,
1365 // which means more than one remark file is being generated.
1367 bool hasExplicitOutputFile =
1368 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1369 if (hasMultipleInvocations && hasExplicitOutputFile) {
1370 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1371 << "-foptimization-record-file";
1372 return false;
1373 }
1374 return true;
1375}
1376
1377static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1378 const llvm::Triple &Triple,
1379 const InputInfo &Input,
1380 const InputInfo &Output, const JobAction &JA) {
1381 StringRef Format = "yaml";
1382 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1383 Format = A->getValue();
1384
1385 CmdArgs.push_back("-opt-record-file");
1386
1387 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1388 if (A) {
1389 CmdArgs.push_back(A->getValue());
1390 } else {
1391 bool hasMultipleArchs =
1392 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1393 Args.getAllArgValues(options::OPT_arch).size() > 1;
1394
1396
1397 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1398 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1399 F = FinalOutput->getValue();
1400 } else {
1401 if (Format != "yaml" && // For YAML, keep the original behavior.
1402 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1403 Output.isFilename())
1404 F = Output.getFilename();
1405 }
1406
1407 if (F.empty()) {
1408 // Use the input filename.
1409 F = llvm::sys::path::stem(Input.getBaseInput());
1410
1411 // If we're compiling for an offload architecture (i.e. a CUDA device),
1412 // we need to make the file name for the device compilation different
1413 // from the host compilation.
1416 llvm::sys::path::replace_extension(F, "");
1418 Triple.normalize());
1419 F += "-";
1420 F += JA.getOffloadingArch();
1421 }
1422 }
1423
1424 // If we're having more than one "-arch", we should name the files
1425 // differently so that every cc1 invocation writes to a different file.
1426 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1427 // name from the triple.
1428 if (hasMultipleArchs) {
1429 // First, remember the extension.
1430 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1431 // then, remove it.
1432 llvm::sys::path::replace_extension(F, "");
1433 // attach -<arch> to it.
1434 F += "-";
1435 F += Triple.getArchName();
1436 // put back the extension.
1437 llvm::sys::path::replace_extension(F, OldExtension);
1438 }
1439
1440 SmallString<32> Extension;
1441 Extension += "opt.";
1442 Extension += Format;
1443
1444 llvm::sys::path::replace_extension(F, Extension);
1445 CmdArgs.push_back(Args.MakeArgString(F));
1446 }
1447
1448 if (const Arg *A =
1449 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1450 CmdArgs.push_back("-opt-record-passes");
1451 CmdArgs.push_back(A->getValue());
1452 }
1453
1454 if (!Format.empty()) {
1455 CmdArgs.push_back("-opt-record-format");
1456 CmdArgs.push_back(Format.data());
1457 }
1458}
1459
1460void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1461 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1462 options::OPT_fno_aapcs_bitfield_width, true))
1463 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1464
1465 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1466 CmdArgs.push_back("-faapcs-bitfield-load");
1467}
1468
1469namespace {
1470void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1471 const ArgList &Args, ArgStringList &CmdArgs) {
1472 // Select the ABI to use.
1473 // FIXME: Support -meabi.
1474 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1475 const char *ABIName = nullptr;
1476 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1477 ABIName = A->getValue();
1478 } else {
1479 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1480 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1481 }
1482
1483 CmdArgs.push_back("-target-abi");
1484 CmdArgs.push_back(ABIName);
1485}
1486
1487void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1488 auto StrictAlignIter =
1489 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1490 return Arg == "+strict-align" || Arg == "-strict-align";
1491 });
1492 if (StrictAlignIter != CmdArgs.rend() &&
1493 StringRef(*StrictAlignIter) == "+strict-align")
1494 CmdArgs.push_back("-Wunaligned-access");
1495}
1496}
1497
1498// Each combination of options here forms a signing schema, and in most cases
1499// each signing schema is its own incompatible ABI. The default values of the
1500// options represent the default signing schema.
1501static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args) {
1502 if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
1503 options::OPT_fno_ptrauth_intrinsics))
1504 CC1Args.push_back("-fptrauth-intrinsics");
1505
1506 if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
1507 options::OPT_fno_ptrauth_calls))
1508 CC1Args.push_back("-fptrauth-calls");
1509
1510 if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
1511 options::OPT_fno_ptrauth_returns))
1512 CC1Args.push_back("-fptrauth-returns");
1513
1514 if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
1515 options::OPT_fno_ptrauth_auth_traps))
1516 CC1Args.push_back("-fptrauth-auth-traps");
1517
1518 if (!DriverArgs.hasArg(
1519 options::OPT_fptrauth_vtable_pointer_address_discrimination,
1520 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
1521 CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
1522
1523 if (!DriverArgs.hasArg(
1524 options::OPT_fptrauth_vtable_pointer_type_discrimination,
1525 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
1526 CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
1527
1528 if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
1529 options::OPT_fno_ptrauth_indirect_gotos))
1530 CC1Args.push_back("-fptrauth-indirect-gotos");
1531
1532 if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
1533 options::OPT_fno_ptrauth_init_fini))
1534 CC1Args.push_back("-fptrauth-init-fini");
1535}
1536
1537static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1538 ArgStringList &CmdArgs, bool isAArch64) {
1539 const Arg *A = isAArch64
1540 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1541 options::OPT_mbranch_protection_EQ)
1542 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1543 if (!A)
1544 return;
1545
1546 const Driver &D = TC.getDriver();
1547 const llvm::Triple &Triple = TC.getEffectiveTriple();
1548 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1549 D.Diag(diag::warn_incompatible_branch_protection_option)
1550 << Triple.getArchName();
1551
1552 StringRef Scope, Key;
1553 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1554
1555 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1556 Scope = A->getValue();
1557 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1558 D.Diag(diag::err_drv_unsupported_option_argument)
1559 << A->getSpelling() << Scope;
1560 Key = "a_key";
1561 IndirectBranches = false;
1562 BranchProtectionPAuthLR = false;
1563 GuardedControlStack = false;
1564 } else {
1565 StringRef DiagMsg;
1566 llvm::ARM::ParsedBranchProtection PBP;
1567 bool EnablePAuthLR = false;
1568
1569 // To know if we need to enable PAuth-LR As part of the standard branch
1570 // protection option, it needs to be determined if the feature has been
1571 // activated in the `march` argument. This information is stored within the
1572 // CmdArgs variable and can be found using a search.
1573 if (isAArch64) {
1574 auto isPAuthLR = [](const char *member) {
1575 llvm::AArch64::ExtensionInfo pauthlr_extension =
1576 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1577 return pauthlr_extension.PosTargetFeature == member;
1578 };
1579
1580 if (std::any_of(CmdArgs.begin(), CmdArgs.end(), isPAuthLR))
1581 EnablePAuthLR = true;
1582 }
1583 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1584 EnablePAuthLR))
1585 D.Diag(diag::err_drv_unsupported_option_argument)
1586 << A->getSpelling() << DiagMsg;
1587 if (!isAArch64 && PBP.Key == "b_key")
1588 D.Diag(diag::warn_unsupported_branch_protection)
1589 << "b-key" << A->getAsString(Args);
1590 Scope = PBP.Scope;
1591 Key = PBP.Key;
1592 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1593 IndirectBranches = PBP.BranchTargetEnforcement;
1594 GuardedControlStack = PBP.GuardedControlStack;
1595 }
1596
1597 CmdArgs.push_back(
1598 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1599 if (Scope != "none") {
1600 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1601 D.Diag(diag::err_drv_unsupported_opt_for_target)
1602 << A->getAsString(Args) << Triple.getTriple();
1603 CmdArgs.push_back(
1604 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1605 }
1606 if (BranchProtectionPAuthLR) {
1607 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1608 D.Diag(diag::err_drv_unsupported_opt_for_target)
1609 << A->getAsString(Args) << Triple.getTriple();
1610 CmdArgs.push_back(
1611 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1612 }
1613 if (IndirectBranches)
1614 CmdArgs.push_back("-mbranch-target-enforce");
1615 // GCS is currently untested with PAuthABI, but enabling this could be allowed
1616 // in future after testing with a suitable system.
1617 if (GuardedControlStack) {
1618 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1619 D.Diag(diag::err_drv_unsupported_opt_for_target)
1620 << A->getAsString(Args) << Triple.getTriple();
1621 CmdArgs.push_back("-mguarded-control-stack");
1622 }
1623}
1624
1625void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1626 ArgStringList &CmdArgs, bool KernelOrKext) const {
1627 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1628
1629 // Determine floating point ABI from the options & target defaults.
1631 if (ABI == arm::FloatABI::Soft) {
1632 // Floating point operations and argument passing are soft.
1633 // FIXME: This changes CPP defines, we need -target-soft-float.
1634 CmdArgs.push_back("-msoft-float");
1635 CmdArgs.push_back("-mfloat-abi");
1636 CmdArgs.push_back("soft");
1637 } else if (ABI == arm::FloatABI::SoftFP) {
1638 // Floating point operations are hard, but argument passing is soft.
1639 CmdArgs.push_back("-mfloat-abi");
1640 CmdArgs.push_back("soft");
1641 } else {
1642 // Floating point operations and argument passing are hard.
1643 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1644 CmdArgs.push_back("-mfloat-abi");
1645 CmdArgs.push_back("hard");
1646 }
1647
1648 // Forward the -mglobal-merge option for explicit control over the pass.
1649 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1650 options::OPT_mno_global_merge)) {
1651 CmdArgs.push_back("-mllvm");
1652 if (A->getOption().matches(options::OPT_mno_global_merge))
1653 CmdArgs.push_back("-arm-global-merge=false");
1654 else
1655 CmdArgs.push_back("-arm-global-merge=true");
1656 }
1657
1658 if (!Args.hasFlag(options::OPT_mimplicit_float,
1659 options::OPT_mno_implicit_float, true))
1660 CmdArgs.push_back("-no-implicit-float");
1661
1662 if (Args.getLastArg(options::OPT_mcmse))
1663 CmdArgs.push_back("-mcmse");
1664
1665 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1666
1667 // Enable/disable return address signing and indirect branch targets.
1668 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1669
1670 AddUnalignedAccessWarning(CmdArgs);
1671}
1672
1673void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1674 const ArgList &Args, bool KernelOrKext,
1675 ArgStringList &CmdArgs) const {
1676 const ToolChain &TC = getToolChain();
1677
1678 // Add the target features
1679 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1680
1681 // Add target specific flags.
1682 switch (TC.getArch()) {
1683 default:
1684 break;
1685
1686 case llvm::Triple::arm:
1687 case llvm::Triple::armeb:
1688 case llvm::Triple::thumb:
1689 case llvm::Triple::thumbeb:
1690 // Use the effective triple, which takes into account the deployment target.
1691 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1692 break;
1693
1694 case llvm::Triple::aarch64:
1695 case llvm::Triple::aarch64_32:
1696 case llvm::Triple::aarch64_be:
1697 AddAArch64TargetArgs(Args, CmdArgs);
1698 break;
1699
1700 case llvm::Triple::loongarch32:
1701 case llvm::Triple::loongarch64:
1702 AddLoongArchTargetArgs(Args, CmdArgs);
1703 break;
1704
1705 case llvm::Triple::mips:
1706 case llvm::Triple::mipsel:
1707 case llvm::Triple::mips64:
1708 case llvm::Triple::mips64el:
1709 AddMIPSTargetArgs(Args, CmdArgs);
1710 break;
1711
1712 case llvm::Triple::ppc:
1713 case llvm::Triple::ppcle:
1714 case llvm::Triple::ppc64:
1715 case llvm::Triple::ppc64le:
1716 AddPPCTargetArgs(Args, CmdArgs);
1717 break;
1718
1719 case llvm::Triple::riscv32:
1720 case llvm::Triple::riscv64:
1721 AddRISCVTargetArgs(Args, CmdArgs);
1722 break;
1723
1724 case llvm::Triple::sparc:
1725 case llvm::Triple::sparcel:
1726 case llvm::Triple::sparcv9:
1727 AddSparcTargetArgs(Args, CmdArgs);
1728 break;
1729
1730 case llvm::Triple::systemz:
1731 AddSystemZTargetArgs(Args, CmdArgs);
1732 break;
1733
1734 case llvm::Triple::x86:
1735 case llvm::Triple::x86_64:
1736 AddX86TargetArgs(Args, CmdArgs);
1737 break;
1738
1739 case llvm::Triple::lanai:
1740 AddLanaiTargetArgs(Args, CmdArgs);
1741 break;
1742
1743 case llvm::Triple::hexagon:
1744 AddHexagonTargetArgs(Args, CmdArgs);
1745 break;
1746
1747 case llvm::Triple::wasm32:
1748 case llvm::Triple::wasm64:
1749 AddWebAssemblyTargetArgs(Args, CmdArgs);
1750 break;
1751
1752 case llvm::Triple::ve:
1753 AddVETargetArgs(Args, CmdArgs);
1754 break;
1755 }
1756}
1757
1758namespace {
1759void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1760 ArgStringList &CmdArgs) {
1761 const char *ABIName = nullptr;
1762 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1763 ABIName = A->getValue();
1764 else if (Triple.isOSDarwin())
1765 ABIName = "darwinpcs";
1766 else if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1767 ABIName = "pauthtest";
1768 else
1769 ABIName = "aapcs";
1770
1771 CmdArgs.push_back("-target-abi");
1772 CmdArgs.push_back(ABIName);
1773}
1774}
1775
1776void Clang::AddAArch64TargetArgs(const ArgList &Args,
1777 ArgStringList &CmdArgs) const {
1778 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1779
1780 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1781 Args.hasArg(options::OPT_mkernel) ||
1782 Args.hasArg(options::OPT_fapple_kext))
1783 CmdArgs.push_back("-disable-red-zone");
1784
1785 if (!Args.hasFlag(options::OPT_mimplicit_float,
1786 options::OPT_mno_implicit_float, true))
1787 CmdArgs.push_back("-no-implicit-float");
1788
1789 RenderAArch64ABI(Triple, Args, CmdArgs);
1790
1791 // Forward the -mglobal-merge option for explicit control over the pass.
1792 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1793 options::OPT_mno_global_merge)) {
1794 CmdArgs.push_back("-mllvm");
1795 if (A->getOption().matches(options::OPT_mno_global_merge))
1796 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1797 else
1798 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1799 }
1800
1801 // Enable/disable return address signing and indirect branch targets.
1802 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1803
1804 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1805 handlePAuthABI(Args, CmdArgs);
1806
1807 // Handle -msve_vector_bits=<bits>
1808 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1809 StringRef Val = A->getValue();
1810 const Driver &D = getToolChain().getDriver();
1811 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1812 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1813 Val == "1024+" || Val == "2048+") {
1814 unsigned Bits = 0;
1815 if (!Val.consume_back("+")) {
1816 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1817 assert(!Invalid && "Failed to parse value");
1818 CmdArgs.push_back(
1819 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1820 }
1821
1822 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1823 assert(!Invalid && "Failed to parse value");
1824 CmdArgs.push_back(
1825 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1826 // Silently drop requests for vector-length agnostic code as it's implied.
1827 } else if (Val != "scalable")
1828 // Handle the unsupported values passed to msve-vector-bits.
1829 D.Diag(diag::err_drv_unsupported_option_argument)
1830 << A->getSpelling() << Val;
1831 }
1832
1833 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1834
1835 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1836 CmdArgs.push_back("-tune-cpu");
1837 if (strcmp(A->getValue(), "native") == 0)
1838 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1839 else
1840 CmdArgs.push_back(A->getValue());
1841 }
1842
1843 AddUnalignedAccessWarning(CmdArgs);
1844
1845 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1846 options::OPT_fno_ptrauth_intrinsics);
1847 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1848 options::OPT_fno_ptrauth_calls);
1849 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1850 options::OPT_fno_ptrauth_returns);
1851 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1852 options::OPT_fno_ptrauth_auth_traps);
1853 Args.addOptInFlag(
1854 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1855 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1856 Args.addOptInFlag(
1857 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1858 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1859 Args.addOptInFlag(
1860 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1861 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1862 Args.addOptInFlag(
1863 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1864 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1865
1866 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1867 options::OPT_fno_ptrauth_indirect_gotos);
1868 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1869 options::OPT_fno_ptrauth_init_fini);
1870 Args.addOptInFlag(CmdArgs,
1871 options::OPT_fptrauth_init_fini_address_discrimination,
1872 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1873}
1874
1875void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1876 ArgStringList &CmdArgs) const {
1877 const llvm::Triple &Triple = getToolChain().getTriple();
1878
1879 CmdArgs.push_back("-target-abi");
1880 CmdArgs.push_back(
1881 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1882 .data());
1883
1884 // Handle -mtune.
1885 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1886 std::string TuneCPU = A->getValue();
1887 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1888 CmdArgs.push_back("-tune-cpu");
1889 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1890 }
1891}
1892
1893void Clang::AddMIPSTargetArgs(const ArgList &Args,
1894 ArgStringList &CmdArgs) const {
1895 const Driver &D = getToolChain().getDriver();
1896 StringRef CPUName;
1897 StringRef ABIName;
1898 const llvm::Triple &Triple = getToolChain().getTriple();
1899 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1900
1901 CmdArgs.push_back("-target-abi");
1902 CmdArgs.push_back(ABIName.data());
1903
1904 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1905 if (ABI == mips::FloatABI::Soft) {
1906 // Floating point operations and argument passing are soft.
1907 CmdArgs.push_back("-msoft-float");
1908 CmdArgs.push_back("-mfloat-abi");
1909 CmdArgs.push_back("soft");
1910 } else {
1911 // Floating point operations and argument passing are hard.
1912 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1913 CmdArgs.push_back("-mfloat-abi");
1914 CmdArgs.push_back("hard");
1915 }
1916
1917 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1918 options::OPT_mno_ldc1_sdc1)) {
1919 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1920 CmdArgs.push_back("-mllvm");
1921 CmdArgs.push_back("-mno-ldc1-sdc1");
1922 }
1923 }
1924
1925 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1926 options::OPT_mno_check_zero_division)) {
1927 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1928 CmdArgs.push_back("-mllvm");
1929 CmdArgs.push_back("-mno-check-zero-division");
1930 }
1931 }
1932
1933 if (Args.getLastArg(options::OPT_mfix4300)) {
1934 CmdArgs.push_back("-mllvm");
1935 CmdArgs.push_back("-mfix4300");
1936 }
1937
1938 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1939 StringRef v = A->getValue();
1940 CmdArgs.push_back("-mllvm");
1941 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1942 A->claim();
1943 }
1944
1945 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1946 Arg *ABICalls =
1947 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1948
1949 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1950 // -mgpopt is the default for static, -fno-pic environments but these two
1951 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1952 // the only case where -mllvm -mgpopt is passed.
1953 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1954 // passed explicitly when compiling something with -mabicalls
1955 // (implictly) in affect. Currently the warning is in the backend.
1956 //
1957 // When the ABI in use is N64, we also need to determine the PIC mode that
1958 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1959 bool NoABICalls =
1960 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1961
1962 llvm::Reloc::Model RelocationModel;
1963 unsigned PICLevel;
1964 bool IsPIE;
1965 std::tie(RelocationModel, PICLevel, IsPIE) =
1966 ParsePICArgs(getToolChain(), Args);
1967
1968 NoABICalls = NoABICalls ||
1969 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1970
1971 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1972 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1973 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1974 CmdArgs.push_back("-mllvm");
1975 CmdArgs.push_back("-mgpopt");
1976
1977 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1978 options::OPT_mno_local_sdata);
1979 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1980 options::OPT_mno_extern_sdata);
1981 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1982 options::OPT_mno_embedded_data);
1983 if (LocalSData) {
1984 CmdArgs.push_back("-mllvm");
1985 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1986 CmdArgs.push_back("-mlocal-sdata=1");
1987 } else {
1988 CmdArgs.push_back("-mlocal-sdata=0");
1989 }
1990 LocalSData->claim();
1991 }
1992
1993 if (ExternSData) {
1994 CmdArgs.push_back("-mllvm");
1995 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1996 CmdArgs.push_back("-mextern-sdata=1");
1997 } else {
1998 CmdArgs.push_back("-mextern-sdata=0");
1999 }
2000 ExternSData->claim();
2001 }
2002
2003 if (EmbeddedData) {
2004 CmdArgs.push_back("-mllvm");
2005 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
2006 CmdArgs.push_back("-membedded-data=1");
2007 } else {
2008 CmdArgs.push_back("-membedded-data=0");
2009 }
2010 EmbeddedData->claim();
2011 }
2012
2013 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
2014 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
2015
2016 if (GPOpt)
2017 GPOpt->claim();
2018
2019 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
2020 StringRef Val = StringRef(A->getValue());
2021 if (mips::hasCompactBranches(CPUName)) {
2022 if (Val == "never" || Val == "always" || Val == "optimal") {
2023 CmdArgs.push_back("-mllvm");
2024 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2025 } else
2026 D.Diag(diag::err_drv_unsupported_option_argument)
2027 << A->getSpelling() << Val;
2028 } else
2029 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2030 }
2031
2032 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2033 options::OPT_mno_relax_pic_calls)) {
2034 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2035 CmdArgs.push_back("-mllvm");
2036 CmdArgs.push_back("-mips-jalr-reloc=0");
2037 }
2038 }
2039}
2040
2041void Clang::AddPPCTargetArgs(const ArgList &Args,
2042 ArgStringList &CmdArgs) const {
2043 const Driver &D = getToolChain().getDriver();
2044 const llvm::Triple &T = getToolChain().getTriple();
2045 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2046 CmdArgs.push_back("-tune-cpu");
2047 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
2048 CmdArgs.push_back(Args.MakeArgString(CPU.str()));
2049 }
2050
2051 // Select the ABI to use.
2052 const char *ABIName = nullptr;
2053 if (T.isOSBinFormatELF()) {
2054 switch (getToolChain().getArch()) {
2055 case llvm::Triple::ppc64: {
2056 if (T.isPPC64ELFv2ABI())
2057 ABIName = "elfv2";
2058 else
2059 ABIName = "elfv1";
2060 break;
2061 }
2062 case llvm::Triple::ppc64le:
2063 ABIName = "elfv2";
2064 break;
2065 default:
2066 break;
2067 }
2068 }
2069
2070 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2071 bool VecExtabi = false;
2072 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2073 StringRef V = A->getValue();
2074 if (V == "ieeelongdouble") {
2075 IEEELongDouble = true;
2076 A->claim();
2077 } else if (V == "ibmlongdouble") {
2078 IEEELongDouble = false;
2079 A->claim();
2080 } else if (V == "vec-default") {
2081 VecExtabi = false;
2082 A->claim();
2083 } else if (V == "vec-extabi") {
2084 VecExtabi = true;
2085 A->claim();
2086 } else if (V == "elfv1") {
2087 ABIName = "elfv1";
2088 A->claim();
2089 } else if (V == "elfv2") {
2090 ABIName = "elfv2";
2091 A->claim();
2092 } else if (V != "altivec")
2093 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2094 // the option if given as we don't have backend support for any targets
2095 // that don't use the altivec abi.
2096 ABIName = A->getValue();
2097 }
2098 if (IEEELongDouble)
2099 CmdArgs.push_back("-mabi=ieeelongdouble");
2100 if (VecExtabi) {
2101 if (!T.isOSAIX())
2102 D.Diag(diag::err_drv_unsupported_opt_for_target)
2103 << "-mabi=vec-extabi" << T.str();
2104 CmdArgs.push_back("-mabi=vec-extabi");
2105 }
2106
2108 if (FloatABI == ppc::FloatABI::Soft) {
2109 // Floating point operations and argument passing are soft.
2110 CmdArgs.push_back("-msoft-float");
2111 CmdArgs.push_back("-mfloat-abi");
2112 CmdArgs.push_back("soft");
2113 } else {
2114 // Floating point operations and argument passing are hard.
2115 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2116 CmdArgs.push_back("-mfloat-abi");
2117 CmdArgs.push_back("hard");
2118 }
2119
2120 if (ABIName) {
2121 CmdArgs.push_back("-target-abi");
2122 CmdArgs.push_back(ABIName);
2123 }
2124}
2125
2126static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2127 ArgStringList &CmdArgs) {
2128 const Driver &D = TC.getDriver();
2129 const llvm::Triple &Triple = TC.getTriple();
2130 // Default small data limitation is eight.
2131 const char *SmallDataLimit = "8";
2132 // Get small data limitation.
2133 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2134 options::OPT_fPIC)) {
2135 // Not support linker relaxation for PIC.
2136 SmallDataLimit = "0";
2137 if (Args.hasArg(options::OPT_G)) {
2138 D.Diag(diag::warn_drv_unsupported_sdata);
2139 }
2140 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2141 .equals_insensitive("large") &&
2142 (Triple.getArch() == llvm::Triple::riscv64)) {
2143 // Not support linker relaxation for RV64 with large code model.
2144 SmallDataLimit = "0";
2145 if (Args.hasArg(options::OPT_G)) {
2146 D.Diag(diag::warn_drv_unsupported_sdata);
2147 }
2148 } else if (Triple.isAndroid()) {
2149 // GP relaxation is not supported on Android.
2150 SmallDataLimit = "0";
2151 if (Args.hasArg(options::OPT_G)) {
2152 D.Diag(diag::warn_drv_unsupported_sdata);
2153 }
2154 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2155 SmallDataLimit = A->getValue();
2156 }
2157 // Forward the -msmall-data-limit= option.
2158 CmdArgs.push_back("-msmall-data-limit");
2159 CmdArgs.push_back(SmallDataLimit);
2160}
2161
2162void Clang::AddRISCVTargetArgs(const ArgList &Args,
2163 ArgStringList &CmdArgs) const {
2164 const llvm::Triple &Triple = getToolChain().getTriple();
2165 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2166
2167 CmdArgs.push_back("-target-abi");
2168 CmdArgs.push_back(ABIName.data());
2169
2170 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2171
2172 if (!Args.hasFlag(options::OPT_mimplicit_float,
2173 options::OPT_mno_implicit_float, true))
2174 CmdArgs.push_back("-no-implicit-float");
2175
2176 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2177 CmdArgs.push_back("-tune-cpu");
2178 if (strcmp(A->getValue(), "native") == 0)
2179 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2180 else
2181 CmdArgs.push_back(A->getValue());
2182 }
2183
2184 // Handle -mrvv-vector-bits=<bits>
2185 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2186 StringRef Val = A->getValue();
2187 const Driver &D = getToolChain().getDriver();
2188
2189 // Get minimum VLen from march.
2190 unsigned MinVLen = 0;
2191 std::string Arch = riscv::getRISCVArch(Args, Triple);
2192 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2193 Arch, /*EnableExperimentalExtensions*/ true);
2194 // Ignore parsing error.
2195 if (!errorToBool(ISAInfo.takeError()))
2196 MinVLen = (*ISAInfo)->getMinVLen();
2197
2198 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2199 // as integer as long as we have a MinVLen.
2200 unsigned Bits = 0;
2201 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2202 Bits = MinVLen;
2203 } else if (!Val.getAsInteger(10, Bits)) {
2204 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2205 // at least MinVLen.
2206 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2207 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2208 Bits = 0;
2209 }
2210
2211 // If we got a valid value try to use it.
2212 if (Bits != 0) {
2213 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2214 CmdArgs.push_back(
2215 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2216 CmdArgs.push_back(
2217 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2218 } else if (Val != "scalable") {
2219 // Handle the unsupported values passed to mrvv-vector-bits.
2220 D.Diag(diag::err_drv_unsupported_option_argument)
2221 << A->getSpelling() << Val;
2222 }
2223 }
2224}
2225
2226void Clang::AddSparcTargetArgs(const ArgList &Args,
2227 ArgStringList &CmdArgs) const {
2229 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2230
2231 if (FloatABI == sparc::FloatABI::Soft) {
2232 // Floating point operations and argument passing are soft.
2233 CmdArgs.push_back("-msoft-float");
2234 CmdArgs.push_back("-mfloat-abi");
2235 CmdArgs.push_back("soft");
2236 } else {
2237 // Floating point operations and argument passing are hard.
2238 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2239 CmdArgs.push_back("-mfloat-abi");
2240 CmdArgs.push_back("hard");
2241 }
2242
2243 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2244 StringRef Name = A->getValue();
2245 std::string TuneCPU;
2246 if (Name == "native")
2247 TuneCPU = std::string(llvm::sys::getHostCPUName());
2248 else
2249 TuneCPU = std::string(Name);
2250
2251 CmdArgs.push_back("-tune-cpu");
2252 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2253 }
2254}
2255
2256void Clang::AddSystemZTargetArgs(const ArgList &Args,
2257 ArgStringList &CmdArgs) const {
2258 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2259 CmdArgs.push_back("-tune-cpu");
2260 if (strcmp(A->getValue(), "native") == 0)
2261 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2262 else
2263 CmdArgs.push_back(A->getValue());
2264 }
2265
2266 bool HasBackchain =
2267 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2268 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2269 options::OPT_mno_packed_stack, false);
2271 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2272 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2273 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2274 const Driver &D = getToolChain().getDriver();
2275 D.Diag(diag::err_drv_unsupported_opt)
2276 << "-mpacked-stack -mbackchain -mhard-float";
2277 }
2278 if (HasBackchain)
2279 CmdArgs.push_back("-mbackchain");
2280 if (HasPackedStack)
2281 CmdArgs.push_back("-mpacked-stack");
2282 if (HasSoftFloat) {
2283 // Floating point operations and argument passing are soft.
2284 CmdArgs.push_back("-msoft-float");
2285 CmdArgs.push_back("-mfloat-abi");
2286 CmdArgs.push_back("soft");
2287 }
2288}
2289
2290void Clang::AddX86TargetArgs(const ArgList &Args,
2291 ArgStringList &CmdArgs) const {
2292 const Driver &D = getToolChain().getDriver();
2293 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2294
2295 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2296 Args.hasArg(options::OPT_mkernel) ||
2297 Args.hasArg(options::OPT_fapple_kext))
2298 CmdArgs.push_back("-disable-red-zone");
2299
2300 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2301 options::OPT_mno_tls_direct_seg_refs, true))
2302 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2303
2304 // Default to avoid implicit floating-point for kernel/kext code, but allow
2305 // that to be overridden with -mno-soft-float.
2306 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2307 Args.hasArg(options::OPT_fapple_kext));
2308 if (Arg *A = Args.getLastArg(
2309 options::OPT_msoft_float, options::OPT_mno_soft_float,
2310 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2311 const Option &O = A->getOption();
2312 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2313 O.matches(options::OPT_msoft_float));
2314 }
2315 if (NoImplicitFloat)
2316 CmdArgs.push_back("-no-implicit-float");
2317
2318 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2319 StringRef Value = A->getValue();
2320 if (Value == "intel" || Value == "att") {
2321 CmdArgs.push_back("-mllvm");
2322 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2323 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2324 } else {
2325 D.Diag(diag::err_drv_unsupported_option_argument)
2326 << A->getSpelling() << Value;
2327 }
2328 } else if (D.IsCLMode()) {
2329 CmdArgs.push_back("-mllvm");
2330 CmdArgs.push_back("-x86-asm-syntax=intel");
2331 }
2332
2333 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2334 options::OPT_mno_skip_rax_setup))
2335 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2336 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2337
2338 // Set flags to support MCU ABI.
2339 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2340 CmdArgs.push_back("-mfloat-abi");
2341 CmdArgs.push_back("soft");
2342 CmdArgs.push_back("-mstack-alignment=4");
2343 }
2344
2345 // Handle -mtune.
2346
2347 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2348 std::string TuneCPU;
2349 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2350 !getToolChain().getTriple().isPS())
2351 TuneCPU = "generic";
2352
2353 // Override based on -mtune.
2354 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2355 StringRef Name = A->getValue();
2356
2357 if (Name == "native") {
2358 Name = llvm::sys::getHostCPUName();
2359 if (!Name.empty())
2360 TuneCPU = std::string(Name);
2361 } else
2362 TuneCPU = std::string(Name);
2363 }
2364
2365 if (!TuneCPU.empty()) {
2366 CmdArgs.push_back("-tune-cpu");
2367 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2368 }
2369}
2370
2371void Clang::AddHexagonTargetArgs(const ArgList &Args,
2372 ArgStringList &CmdArgs) const {
2373 CmdArgs.push_back("-mqdsp6-compat");
2374 CmdArgs.push_back("-Wreturn-type");
2375
2377 CmdArgs.push_back("-mllvm");
2378 CmdArgs.push_back(
2379 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2380 }
2381
2382 if (!Args.hasArg(options::OPT_fno_short_enums))
2383 CmdArgs.push_back("-fshort-enums");
2384 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2385 CmdArgs.push_back("-mllvm");
2386 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2387 }
2388 CmdArgs.push_back("-mllvm");
2389 CmdArgs.push_back("-machine-sink-split=0");
2390}
2391
2392void Clang::AddLanaiTargetArgs(const ArgList &Args,
2393 ArgStringList &CmdArgs) const {
2394 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2395 StringRef CPUName = A->getValue();
2396
2397 CmdArgs.push_back("-target-cpu");
2398 CmdArgs.push_back(Args.MakeArgString(CPUName));
2399 }
2400 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2401 StringRef Value = A->getValue();
2402 // Only support mregparm=4 to support old usage. Report error for all other
2403 // cases.
2404 int Mregparm;
2405 if (Value.getAsInteger(10, Mregparm)) {
2406 if (Mregparm != 4) {
2408 diag::err_drv_unsupported_option_argument)
2409 << A->getSpelling() << Value;
2410 }
2411 }
2412 }
2413}
2414
2415void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2416 ArgStringList &CmdArgs) const {
2417 // Default to "hidden" visibility.
2418 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2419 options::OPT_fvisibility_ms_compat))
2420 CmdArgs.push_back("-fvisibility=hidden");
2421}
2422
2423void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2424 // Floating point operations and argument passing are hard.
2425 CmdArgs.push_back("-mfloat-abi");
2426 CmdArgs.push_back("hard");
2427}
2428
2429void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2430 StringRef Target, const InputInfo &Output,
2431 const InputInfo &Input, const ArgList &Args) const {
2432 // If this is a dry run, do not create the compilation database file.
2433 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2434 return;
2435
2436 using llvm::yaml::escape;
2437 const Driver &D = getToolChain().getDriver();
2438
2439 if (!CompilationDatabase) {
2440 std::error_code EC;
2441 auto File = std::make_unique<llvm::raw_fd_ostream>(
2442 Filename, EC,
2443 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2444 if (EC) {
2445 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2446 << EC.message();
2447 return;
2448 }
2449 CompilationDatabase = std::move(File);
2450 }
2451 auto &CDB = *CompilationDatabase;
2452 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2453 if (!CWD)
2454 CWD = ".";
2455 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2456 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2457 if (Output.isFilename())
2458 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2459 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2460 SmallString<128> Buf;
2461 Buf = "-x";
2462 Buf += types::getTypeName(Input.getType());
2463 CDB << ", \"" << escape(Buf) << "\"";
2464 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2465 Buf = "--sysroot=";
2466 Buf += D.SysRoot;
2467 CDB << ", \"" << escape(Buf) << "\"";
2468 }
2469 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2470 if (Output.isFilename())
2471 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2472 for (auto &A: Args) {
2473 auto &O = A->getOption();
2474 // Skip language selection, which is positional.
2475 if (O.getID() == options::OPT_x)
2476 continue;
2477 // Skip writing dependency output and the compilation database itself.
2478 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2479 continue;
2480 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2481 continue;
2482 // Skip inputs.
2483 if (O.getKind() == Option::InputClass)
2484 continue;
2485 // Skip output.
2486 if (O.getID() == options::OPT_o)
2487 continue;
2488 // All other arguments are quoted and appended.
2489 ArgStringList ASL;
2490 A->render(Args, ASL);
2491 for (auto &it: ASL)
2492 CDB << ", \"" << escape(it) << "\"";
2493 }
2494 Buf = "--target=";
2495 Buf += Target;
2496 CDB << ", \"" << escape(Buf) << "\"]},\n";
2497}
2498
2499void Clang::DumpCompilationDatabaseFragmentToDir(
2500 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2501 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2502 // If this is a dry run, do not create the compilation database file.
2503 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2504 return;
2505
2506 if (CompilationDatabase)
2507 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2508
2509 SmallString<256> Path = Dir;
2510 const auto &Driver = C.getDriver();
2511 Driver.getVFS().makeAbsolute(Path);
2512 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2513 if (Err) {
2514 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2515 return;
2516 }
2517
2518 llvm::sys::path::append(
2519 Path,
2520 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2521 int FD;
2522 SmallString<256> TempPath;
2523 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2524 llvm::sys::fs::OF_Text);
2525 if (Err) {
2526 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2527 return;
2528 }
2529 CompilationDatabase =
2530 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2531 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2532}
2533
2534static bool CheckARMImplicitITArg(StringRef Value) {
2535 return Value == "always" || Value == "never" || Value == "arm" ||
2536 Value == "thumb";
2537}
2538
2539static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2540 StringRef Value) {
2541 CmdArgs.push_back("-mllvm");
2542 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2543}
2544
2546 const ArgList &Args,
2547 ArgStringList &CmdArgs,
2548 const Driver &D) {
2549 // Default to -mno-relax-all.
2550 //
2551 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2552 // cannot be done by assembler branch relaxation as it needs a free temporary
2553 // register. Because of this, branch relaxation is handled by a MachineIR pass
2554 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2555 // MachineIR branch relaxation inaccurate and it will miss cases where an
2556 // indirect branch is necessary.
2557 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2558 options::OPT_mno_relax_all);
2559
2560 // Only default to -mincremental-linker-compatible if we think we are
2561 // targeting the MSVC linker.
2562 bool DefaultIncrementalLinkerCompatible =
2563 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2564 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2565 options::OPT_mno_incremental_linker_compatible,
2566 DefaultIncrementalLinkerCompatible))
2567 CmdArgs.push_back("-mincremental-linker-compatible");
2568
2569 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2570
2571 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2572 options::OPT_fno_emit_compact_unwind_non_canonical);
2573
2574 // If you add more args here, also add them to the block below that
2575 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2576
2577 // When passing -I arguments to the assembler we sometimes need to
2578 // unconditionally take the next argument. For example, when parsing
2579 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2580 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2581 // arg after parsing the '-I' arg.
2582 bool TakeNextArg = false;
2583
2584 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2585 bool Crel = false, ExperimentalCrel = false;
2586 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2587 bool UseNoExecStack = false;
2588 const char *MipsTargetFeature = nullptr;
2589 StringRef ImplicitIt;
2590 for (const Arg *A :
2591 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2592 options::OPT_mimplicit_it_EQ)) {
2593 A->claim();
2594
2595 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2596 switch (C.getDefaultToolChain().getArch()) {
2597 case llvm::Triple::arm:
2598 case llvm::Triple::armeb:
2599 case llvm::Triple::thumb:
2600 case llvm::Triple::thumbeb:
2601 // Only store the value; the last value set takes effect.
2602 ImplicitIt = A->getValue();
2603 if (!CheckARMImplicitITArg(ImplicitIt))
2604 D.Diag(diag::err_drv_unsupported_option_argument)
2605 << A->getSpelling() << ImplicitIt;
2606 continue;
2607 default:
2608 break;
2609 }
2610 }
2611
2612 for (StringRef Value : A->getValues()) {
2613 if (TakeNextArg) {
2614 CmdArgs.push_back(Value.data());
2615 TakeNextArg = false;
2616 continue;
2617 }
2618
2619 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2620 Value == "-mbig-obj")
2621 continue; // LLVM handles bigobj automatically
2622
2623 switch (C.getDefaultToolChain().getArch()) {
2624 default:
2625 break;
2626 case llvm::Triple::x86:
2627 case llvm::Triple::x86_64:
2628 if (Value == "-msse2avx") {
2629 CmdArgs.push_back("-msse2avx");
2630 continue;
2631 }
2632 break;
2633 case llvm::Triple::wasm32:
2634 case llvm::Triple::wasm64:
2635 if (Value == "--no-type-check") {
2636 CmdArgs.push_back("-mno-type-check");
2637 continue;
2638 }
2639 break;
2640 case llvm::Triple::thumb:
2641 case llvm::Triple::thumbeb:
2642 case llvm::Triple::arm:
2643 case llvm::Triple::armeb:
2644 if (Value.starts_with("-mimplicit-it=")) {
2645 // Only store the value; the last value set takes effect.
2646 ImplicitIt = Value.split("=").second;
2647 if (CheckARMImplicitITArg(ImplicitIt))
2648 continue;
2649 }
2650 if (Value == "-mthumb")
2651 // -mthumb has already been processed in ComputeLLVMTriple()
2652 // recognize but skip over here.
2653 continue;
2654 break;
2655 case llvm::Triple::mips:
2656 case llvm::Triple::mipsel:
2657 case llvm::Triple::mips64:
2658 case llvm::Triple::mips64el:
2659 if (Value == "--trap") {
2660 CmdArgs.push_back("-target-feature");
2661 CmdArgs.push_back("+use-tcc-in-div");
2662 continue;
2663 }
2664 if (Value == "--break") {
2665 CmdArgs.push_back("-target-feature");
2666 CmdArgs.push_back("-use-tcc-in-div");
2667 continue;
2668 }
2669 if (Value.starts_with("-msoft-float")) {
2670 CmdArgs.push_back("-target-feature");
2671 CmdArgs.push_back("+soft-float");
2672 continue;
2673 }
2674 if (Value.starts_with("-mhard-float")) {
2675 CmdArgs.push_back("-target-feature");
2676 CmdArgs.push_back("-soft-float");
2677 continue;
2678 }
2679
2680 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2681 .Case("-mips1", "+mips1")
2682 .Case("-mips2", "+mips2")
2683 .Case("-mips3", "+mips3")
2684 .Case("-mips4", "+mips4")
2685 .Case("-mips5", "+mips5")
2686 .Case("-mips32", "+mips32")
2687 .Case("-mips32r2", "+mips32r2")
2688 .Case("-mips32r3", "+mips32r3")
2689 .Case("-mips32r5", "+mips32r5")
2690 .Case("-mips32r6", "+mips32r6")
2691 .Case("-mips64", "+mips64")
2692 .Case("-mips64r2", "+mips64r2")
2693 .Case("-mips64r3", "+mips64r3")
2694 .Case("-mips64r5", "+mips64r5")
2695 .Case("-mips64r6", "+mips64r6")
2696 .Default(nullptr);
2697 if (MipsTargetFeature)
2698 continue;
2699 }
2700
2701 if (Value == "-force_cpusubtype_ALL") {
2702 // Do nothing, this is the default and we don't support anything else.
2703 } else if (Value == "-L") {
2704 CmdArgs.push_back("-msave-temp-labels");
2705 } else if (Value == "--fatal-warnings") {
2706 CmdArgs.push_back("-massembler-fatal-warnings");
2707 } else if (Value == "--no-warn" || Value == "-W") {
2708 CmdArgs.push_back("-massembler-no-warn");
2709 } else if (Value == "--noexecstack") {
2710 UseNoExecStack = true;
2711 } else if (Value.starts_with("-compress-debug-sections") ||
2712 Value.starts_with("--compress-debug-sections") ||
2713 Value == "-nocompress-debug-sections" ||
2714 Value == "--nocompress-debug-sections") {
2715 CmdArgs.push_back(Value.data());
2716 } else if (Value == "--crel") {
2717 Crel = true;
2718 } else if (Value == "--no-crel") {
2719 Crel = false;
2720 } else if (Value == "--allow-experimental-crel") {
2721 ExperimentalCrel = true;
2722 } else if (Value == "-mrelax-relocations=yes" ||
2723 Value == "--mrelax-relocations=yes") {
2724 UseRelaxRelocations = true;
2725 } else if (Value == "-mrelax-relocations=no" ||
2726 Value == "--mrelax-relocations=no") {
2727 UseRelaxRelocations = false;
2728 } else if (Value.starts_with("-I")) {
2729 CmdArgs.push_back(Value.data());
2730 // We need to consume the next argument if the current arg is a plain
2731 // -I. The next arg will be the include directory.
2732 if (Value == "-I")
2733 TakeNextArg = true;
2734 } else if (Value.starts_with("-gdwarf-")) {
2735 // "-gdwarf-N" options are not cc1as options.
2736 unsigned DwarfVersion = DwarfVersionNum(Value);
2737 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2738 CmdArgs.push_back(Value.data());
2739 } else {
2740 RenderDebugEnablingArgs(Args, CmdArgs,
2741 llvm::codegenoptions::DebugInfoConstructor,
2742 DwarfVersion, llvm::DebuggerKind::Default);
2743 }
2744 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2745 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2746 // Do nothing, we'll validate it later.
2747 } else if (Value == "-defsym" || Value == "--defsym") {
2748 if (A->getNumValues() != 2) {
2749 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2750 break;
2751 }
2752 const char *S = A->getValue(1);
2753 auto Pair = StringRef(S).split('=');
2754 auto Sym = Pair.first;
2755 auto SVal = Pair.second;
2756
2757 if (Sym.empty() || SVal.empty()) {
2758 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2759 break;
2760 }
2761 int64_t IVal;
2762 if (SVal.getAsInteger(0, IVal)) {
2763 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2764 break;
2765 }
2766 CmdArgs.push_back("--defsym");
2767 TakeNextArg = true;
2768 } else if (Value == "-fdebug-compilation-dir") {
2769 CmdArgs.push_back("-fdebug-compilation-dir");
2770 TakeNextArg = true;
2771 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2772 // The flag is a -Wa / -Xassembler argument and Options doesn't
2773 // parse the argument, so this isn't automatically aliased to
2774 // -fdebug-compilation-dir (without '=') here.
2775 CmdArgs.push_back("-fdebug-compilation-dir");
2776 CmdArgs.push_back(Value.data());
2777 } else if (Value == "--version") {
2778 D.PrintVersion(C, llvm::outs());
2779 } else {
2780 D.Diag(diag::err_drv_unsupported_option_argument)
2781 << A->getSpelling() << Value;
2782 }
2783 }
2784 }
2785 if (ImplicitIt.size())
2786 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2787 if (Crel) {
2788 if (!ExperimentalCrel)
2789 D.Diag(diag::err_drv_experimental_crel);
2790 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2791 CmdArgs.push_back("--crel");
2792 } else {
2793 D.Diag(diag::err_drv_unsupported_opt_for_target)
2794 << "-Wa,--crel" << D.getTargetTriple();
2795 }
2796 }
2797 if (!UseRelaxRelocations)
2798 CmdArgs.push_back("-mrelax-relocations=no");
2799 if (UseNoExecStack)
2800 CmdArgs.push_back("-mnoexecstack");
2801 if (MipsTargetFeature != nullptr) {
2802 CmdArgs.push_back("-target-feature");
2803 CmdArgs.push_back(MipsTargetFeature);
2804 }
2805
2806 // forward -fembed-bitcode to assmebler
2807 if (C.getDriver().embedBitcodeEnabled() ||
2808 C.getDriver().embedBitcodeMarkerOnly())
2809 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2810
2811 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2812 CmdArgs.push_back("-as-secure-log-file");
2813 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2814 }
2815}
2816
2818 switch (Range) {
2820 return "full";
2821 break;
2823 return "basic";
2824 break;
2826 return "improved";
2827 break;
2829 return "promoted";
2830 break;
2831 default:
2832 return "";
2833 }
2834}
2835
2838 ? ""
2839 : "-fcomplex-arithmetic=" + ComplexRangeKindToStr(Range);
2840}
2841
2842static void EmitComplexRangeDiag(const Driver &D, std::string str1,
2843 std::string str2) {
2844 if ((str1.compare(str2) != 0) && !str2.empty() && !str1.empty()) {
2845 D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
2846 }
2847}
2848
2849static std::string
2851 std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
2852 if (!ComplexRangeStr.empty())
2853 return "-complex-range=" + ComplexRangeStr;
2854 return ComplexRangeStr;
2855}
2856
2857static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2858 bool OFastEnabled, const ArgList &Args,
2859 ArgStringList &CmdArgs,
2860 const JobAction &JA) {
2861 // Handle various floating point optimization flags, mapping them to the
2862 // appropriate LLVM code generation flags. This is complicated by several
2863 // "umbrella" flags, so we do this by stepping through the flags incrementally
2864 // adjusting what we think is enabled/disabled, then at the end setting the
2865 // LLVM flags based on the final state.
2866 bool HonorINFs = true;
2867 bool HonorNaNs = true;
2868 bool ApproxFunc = false;
2869 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2870 bool MathErrno = TC.IsMathErrnoDefault();
2871 bool AssociativeMath = false;
2872 bool ReciprocalMath = false;
2873 bool SignedZeros = true;
2874 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2875 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2876 // overriden by ffp-exception-behavior?
2877 bool RoundingFPMath = false;
2878 // -ffp-model values: strict, fast, precise
2879 StringRef FPModel = "";
2880 // -ffp-exception-behavior options: strict, maytrap, ignore
2881 StringRef FPExceptionBehavior = "";
2882 // -ffp-eval-method options: double, extended, source
2883 StringRef FPEvalMethod = "";
2884 llvm::DenormalMode DenormalFPMath =
2885 TC.getDefaultDenormalModeForType(Args, JA);
2886 llvm::DenormalMode DenormalFP32Math =
2887 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2888
2889 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2890 // If one wasn't given by the user, don't pass it here.
2891 StringRef FPContract;
2892 StringRef LastSeenFfpContractOption;
2893 StringRef LastFpContractOverrideOption;
2894 bool SeenUnsafeMathModeOption = false;
2897 FPContract = "on";
2898 bool StrictFPModel = false;
2899 StringRef Float16ExcessPrecision = "";
2900 StringRef BFloat16ExcessPrecision = "";
2902 std::string ComplexRangeStr = "";
2903 std::string GccRangeComplexOption = "";
2904
2905 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2906 auto applyFastMath = [&]() {
2907 HonorINFs = false;
2908 HonorNaNs = false;
2909 MathErrno = false;
2910 AssociativeMath = true;
2911 ReciprocalMath = true;
2912 ApproxFunc = true;
2913 SignedZeros = false;
2914 TrappingMath = false;
2915 RoundingFPMath = false;
2916 FPExceptionBehavior = "";
2917 // If fast-math is set then set the fp-contract mode to fast.
2918 FPContract = "fast";
2919 // ffast-math enables basic range rules for complex multiplication and
2920 // division.
2921 // Warn if user expects to perform full implementation of complex
2922 // multiplication or division in the presence of nan or ninf flags.
2928 !GccRangeComplexOption.empty()
2929 ? GccRangeComplexOption
2932 SeenUnsafeMathModeOption = true;
2933 };
2934
2935 // Lambda to consolidate common handling for fp-contract
2936 auto restoreFPContractState = [&]() {
2937 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2938 // For other targets, if the state has been changed by one of the
2939 // unsafe-math umbrella options a subsequent -fno-fast-math or
2940 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2941 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2942 // option. If we have not seen an unsafe-math option or -ffp-contract,
2943 // we leave the FPContract state unchanged.
2946 if (LastSeenFfpContractOption != "")
2947 FPContract = LastSeenFfpContractOption;
2948 else if (SeenUnsafeMathModeOption)
2949 FPContract = "on";
2950 }
2951 // In this case, we're reverting to the last explicit fp-contract option
2952 // or the platform default
2953 LastFpContractOverrideOption = "";
2954 };
2955
2956 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2957 CmdArgs.push_back("-mlimit-float-precision");
2958 CmdArgs.push_back(A->getValue());
2959 }
2960
2961 for (const Arg *A : Args) {
2962 switch (A->getOption().getID()) {
2963 // If this isn't an FP option skip the claim below
2964 default: continue;
2965
2966 case options::OPT_fcx_limited_range:
2967 if (GccRangeComplexOption.empty()) {
2970 "-fcx-limited-range");
2971 } else {
2972 if (GccRangeComplexOption != "-fno-cx-limited-range")
2973 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-limited-range");
2974 }
2975 GccRangeComplexOption = "-fcx-limited-range";
2977 break;
2978 case options::OPT_fno_cx_limited_range:
2979 if (GccRangeComplexOption.empty()) {
2981 "-fno-cx-limited-range");
2982 } else {
2983 if (GccRangeComplexOption.compare("-fcx-limited-range") != 0 &&
2984 GccRangeComplexOption.compare("-fno-cx-fortran-rules") != 0)
2985 EmitComplexRangeDiag(D, GccRangeComplexOption,
2986 "-fno-cx-limited-range");
2987 }
2988 GccRangeComplexOption = "-fno-cx-limited-range";
2990 break;
2991 case options::OPT_fcx_fortran_rules:
2992 if (GccRangeComplexOption.empty())
2994 "-fcx-fortran-rules");
2995 else
2996 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-fortran-rules");
2997 GccRangeComplexOption = "-fcx-fortran-rules";
2999 break;
3000 case options::OPT_fno_cx_fortran_rules:
3001 if (GccRangeComplexOption.empty()) {
3003 "-fno-cx-fortran-rules");
3004 } else {
3005 if (GccRangeComplexOption != "-fno-cx-limited-range")
3006 EmitComplexRangeDiag(D, GccRangeComplexOption,
3007 "-fno-cx-fortran-rules");
3008 }
3009 GccRangeComplexOption = "-fno-cx-fortran-rules";
3011 break;
3012 case options::OPT_fcomplex_arithmetic_EQ: {
3014 StringRef Val = A->getValue();
3015 if (Val == "full")
3017 else if (Val == "improved")
3019 else if (Val == "promoted")
3021 else if (Val == "basic")
3023 else {
3024 D.Diag(diag::err_drv_unsupported_option_argument)
3025 << A->getSpelling() << Val;
3026 break;
3027 }
3028 if (!GccRangeComplexOption.empty()) {
3029 if (GccRangeComplexOption.compare("-fcx-limited-range") != 0) {
3030 if (GccRangeComplexOption.compare("-fcx-fortran-rules") != 0) {
3032 EmitComplexRangeDiag(D, GccRangeComplexOption,
3033 ComplexArithmeticStr(RangeVal));
3034 } else {
3035 EmitComplexRangeDiag(D, GccRangeComplexOption,
3036 ComplexArithmeticStr(RangeVal));
3037 }
3038 } else {
3040 EmitComplexRangeDiag(D, GccRangeComplexOption,
3041 ComplexArithmeticStr(RangeVal));
3042 }
3043 }
3044 Range = RangeVal;
3045 break;
3046 }
3047 case options::OPT_ffp_model_EQ: {
3048 // If -ffp-model= is seen, reset to fno-fast-math
3049 HonorINFs = true;
3050 HonorNaNs = true;
3051 ApproxFunc = false;
3052 // Turning *off* -ffast-math restores the toolchain default.
3053 MathErrno = TC.IsMathErrnoDefault();
3054 AssociativeMath = false;
3055 ReciprocalMath = false;
3056 SignedZeros = true;
3057
3058 StringRef Val = A->getValue();
3059 if (OFastEnabled && Val != "fast") {
3060 // Only -ffp-model=fast is compatible with OFast, ignore.
3061 D.Diag(clang::diag::warn_drv_overriding_option)
3062 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3063 break;
3064 }
3065 StrictFPModel = false;
3066 if (!FPModel.empty() && FPModel != Val)
3067 D.Diag(clang::diag::warn_drv_overriding_option)
3068 << Args.MakeArgString("-ffp-model=" + FPModel)
3069 << Args.MakeArgString("-ffp-model=" + Val);
3070 if (Val == "fast") {
3071 FPModel = Val;
3072 applyFastMath();
3073 // applyFastMath sets fp-contract="fast"
3074 LastFpContractOverrideOption = "-ffp-model=fast";
3075 } else if (Val == "precise") {
3076 FPModel = Val;
3077 FPContract = "on";
3078 LastFpContractOverrideOption = "-ffp-model=precise";
3079 } else if (Val == "strict") {
3080 StrictFPModel = true;
3081 FPExceptionBehavior = "strict";
3082 FPModel = Val;
3083 FPContract = "off";
3084 LastFpContractOverrideOption = "-ffp-model=strict";
3085 TrappingMath = true;
3086 RoundingFPMath = true;
3087 } else
3088 D.Diag(diag::err_drv_unsupported_option_argument)
3089 << A->getSpelling() << Val;
3090 break;
3091 }
3092
3093 // Options controlling individual features
3094 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3095 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3096 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3097 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3098 case options::OPT_fapprox_func: ApproxFunc = true; break;
3099 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3100 case options::OPT_fmath_errno: MathErrno = true; break;
3101 case options::OPT_fno_math_errno: MathErrno = false; break;
3102 case options::OPT_fassociative_math: AssociativeMath = true; break;
3103 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3104 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3105 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3106 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3107 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3108 case options::OPT_ftrapping_math:
3109 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3110 FPExceptionBehavior != "strict")
3111 // Warn that previous value of option is overridden.
3112 D.Diag(clang::diag::warn_drv_overriding_option)
3113 << Args.MakeArgString("-ffp-exception-behavior=" +
3114 FPExceptionBehavior)
3115 << "-ftrapping-math";
3116 TrappingMath = true;
3117 TrappingMathPresent = true;
3118 FPExceptionBehavior = "strict";
3119 break;
3120 case options::OPT_fno_trapping_math:
3121 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3122 FPExceptionBehavior != "ignore")
3123 // Warn that previous value of option is overridden.
3124 D.Diag(clang::diag::warn_drv_overriding_option)
3125 << Args.MakeArgString("-ffp-exception-behavior=" +
3126 FPExceptionBehavior)
3127 << "-fno-trapping-math";
3128 TrappingMath = false;
3129 TrappingMathPresent = true;
3130 FPExceptionBehavior = "ignore";
3131 break;
3132
3133 case options::OPT_frounding_math:
3134 RoundingFPMath = true;
3135 break;
3136
3137 case options::OPT_fno_rounding_math:
3138 RoundingFPMath = false;
3139 break;
3140
3141 case options::OPT_fdenormal_fp_math_EQ:
3142 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3143 DenormalFP32Math = DenormalFPMath;
3144 if (!DenormalFPMath.isValid()) {
3145 D.Diag(diag::err_drv_invalid_value)
3146 << A->getAsString(Args) << A->getValue();
3147 }
3148 break;
3149
3150 case options::OPT_fdenormal_fp_math_f32_EQ:
3151 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3152 if (!DenormalFP32Math.isValid()) {
3153 D.Diag(diag::err_drv_invalid_value)
3154 << A->getAsString(Args) << A->getValue();
3155 }
3156 break;
3157
3158 // Validate and pass through -ffp-contract option.
3159 case options::OPT_ffp_contract: {
3160 StringRef Val = A->getValue();
3161 if (Val == "fast" || Val == "on" || Val == "off" ||
3162 Val == "fast-honor-pragmas") {
3163 if (Val != FPContract && LastFpContractOverrideOption != "") {
3164 D.Diag(clang::diag::warn_drv_overriding_option)
3165 << LastFpContractOverrideOption
3166 << Args.MakeArgString("-ffp-contract=" + Val);
3167 }
3168
3169 FPContract = Val;
3170 LastSeenFfpContractOption = Val;
3171 LastFpContractOverrideOption = "";
3172 } else
3173 D.Diag(diag::err_drv_unsupported_option_argument)
3174 << A->getSpelling() << Val;
3175 break;
3176 }
3177
3178 // Validate and pass through -ffp-exception-behavior option.
3179 case options::OPT_ffp_exception_behavior_EQ: {
3180 StringRef Val = A->getValue();
3181 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3182 FPExceptionBehavior != Val)
3183 // Warn that previous value of option is overridden.
3184 D.Diag(clang::diag::warn_drv_overriding_option)
3185 << Args.MakeArgString("-ffp-exception-behavior=" +
3186 FPExceptionBehavior)
3187 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3188 TrappingMath = TrappingMathPresent = false;
3189 if (Val == "ignore" || Val == "maytrap")
3190 FPExceptionBehavior = Val;
3191 else if (Val == "strict") {
3192 FPExceptionBehavior = Val;
3193 TrappingMath = TrappingMathPresent = true;
3194 } else
3195 D.Diag(diag::err_drv_unsupported_option_argument)
3196 << A->getSpelling() << Val;
3197 break;
3198 }
3199
3200 // Validate and pass through -ffp-eval-method option.
3201 case options::OPT_ffp_eval_method_EQ: {
3202 StringRef Val = A->getValue();
3203 if (Val == "double" || Val == "extended" || Val == "source")
3204 FPEvalMethod = Val;
3205 else
3206 D.Diag(diag::err_drv_unsupported_option_argument)
3207 << A->getSpelling() << Val;
3208 break;
3209 }
3210
3211 case options::OPT_fexcess_precision_EQ: {
3212 StringRef Val = A->getValue();
3213 const llvm::Triple::ArchType Arch = TC.getArch();
3214 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3215 if (Val == "standard" || Val == "fast")
3216 Float16ExcessPrecision = Val;
3217 // To make it GCC compatible, allow the value of "16" which
3218 // means disable excess precision, the same meaning than clang's
3219 // equivalent value "none".
3220 else if (Val == "16")
3221 Float16ExcessPrecision = "none";
3222 else
3223 D.Diag(diag::err_drv_unsupported_option_argument)
3224 << A->getSpelling() << Val;
3225 } else {
3226 if (!(Val == "standard" || Val == "fast"))
3227 D.Diag(diag::err_drv_unsupported_option_argument)
3228 << A->getSpelling() << Val;
3229 }
3230 BFloat16ExcessPrecision = Float16ExcessPrecision;
3231 break;
3232 }
3233 case options::OPT_ffinite_math_only:
3234 HonorINFs = false;
3235 HonorNaNs = false;
3236 break;
3237 case options::OPT_fno_finite_math_only:
3238 HonorINFs = true;
3239 HonorNaNs = true;
3240 break;
3241
3242 case options::OPT_funsafe_math_optimizations:
3243 AssociativeMath = true;
3244 ReciprocalMath = true;
3245 SignedZeros = false;
3246 ApproxFunc = true;
3247 TrappingMath = false;
3248 FPExceptionBehavior = "";
3249 FPContract = "fast";
3250 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3251 SeenUnsafeMathModeOption = true;
3252 break;
3253 case options::OPT_fno_unsafe_math_optimizations:
3254 AssociativeMath = false;
3255 ReciprocalMath = false;
3256 SignedZeros = true;
3257 ApproxFunc = false;
3258 restoreFPContractState();
3259 break;
3260
3261 case options::OPT_Ofast:
3262 // If -Ofast is the optimization level, then -ffast-math should be enabled
3263 if (!OFastEnabled)
3264 continue;
3265 [[fallthrough]];
3266 case options::OPT_ffast_math:
3267 applyFastMath();
3268 if (A->getOption().getID() == options::OPT_Ofast)
3269 LastFpContractOverrideOption = "-Ofast";
3270 else
3271 LastFpContractOverrideOption = "-ffast-math";
3272 break;
3273 case options::OPT_fno_fast_math:
3274 HonorINFs = true;
3275 HonorNaNs = true;
3276 // Turning on -ffast-math (with either flag) removes the need for
3277 // MathErrno. However, turning *off* -ffast-math merely restores the
3278 // toolchain default (which may be false).
3279 MathErrno = TC.IsMathErrnoDefault();
3280 AssociativeMath = false;
3281 ReciprocalMath = false;
3282 ApproxFunc = false;
3283 SignedZeros = true;
3284 restoreFPContractState();
3285 LastFpContractOverrideOption = "";
3286 break;
3287 } // End switch (A->getOption().getID())
3288
3289 // The StrictFPModel local variable is needed to report warnings
3290 // in the way we intend. If -ffp-model=strict has been used, we
3291 // want to report a warning for the next option encountered that
3292 // takes us out of the settings described by fp-model=strict, but
3293 // we don't want to continue issuing warnings for other conflicting
3294 // options after that.
3295 if (StrictFPModel) {
3296 // If -ffp-model=strict has been specified on command line but
3297 // subsequent options conflict then emit warning diagnostic.
3298 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3299 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3300 FPContract == "off")
3301 // OK: Current Arg doesn't conflict with -ffp-model=strict
3302 ;
3303 else {
3304 StrictFPModel = false;
3305 FPModel = "";
3306 // The warning for -ffp-contract would have been reported by the
3307 // OPT_ffp_contract_EQ handler above. A special check here is needed
3308 // to avoid duplicating the warning.
3309 auto RHS = (A->getNumValues() == 0)
3310 ? A->getSpelling()
3311 : Args.MakeArgString(A->getSpelling() + A->getValue());
3312 if (A->getSpelling() != "-ffp-contract=") {
3313 if (RHS != "-ffp-model=strict")
3314 D.Diag(clang::diag::warn_drv_overriding_option)
3315 << "-ffp-model=strict" << RHS;
3316 }
3317 }
3318 }
3319
3320 // If we handled this option claim it
3321 A->claim();
3322 }
3323
3324 if (!HonorINFs)
3325 CmdArgs.push_back("-menable-no-infs");
3326
3327 if (!HonorNaNs)
3328 CmdArgs.push_back("-menable-no-nans");
3329
3330 if (ApproxFunc)
3331 CmdArgs.push_back("-fapprox-func");
3332
3333 if (MathErrno)
3334 CmdArgs.push_back("-fmath-errno");
3335
3336 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3337 !TrappingMath)
3338 CmdArgs.push_back("-funsafe-math-optimizations");
3339
3340 if (!SignedZeros)
3341 CmdArgs.push_back("-fno-signed-zeros");
3342
3343 if (AssociativeMath && !SignedZeros && !TrappingMath)
3344 CmdArgs.push_back("-mreassociate");
3345
3346 if (ReciprocalMath)
3347 CmdArgs.push_back("-freciprocal-math");
3348
3349 if (TrappingMath) {
3350 // FP Exception Behavior is also set to strict
3351 assert(FPExceptionBehavior == "strict");
3352 }
3353
3354 // The default is IEEE.
3355 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3356 llvm::SmallString<64> DenormFlag;
3357 llvm::raw_svector_ostream ArgStr(DenormFlag);
3358 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3359 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3360 }
3361
3362 // Add f32 specific denormal mode flag if it's different.
3363 if (DenormalFP32Math != DenormalFPMath) {
3364 llvm::SmallString<64> DenormFlag;
3365 llvm::raw_svector_ostream ArgStr(DenormFlag);
3366 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3367 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3368 }
3369
3370 if (!FPContract.empty())
3371 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3372
3373 if (RoundingFPMath)
3374 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3375 else
3376 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3377
3378 if (!FPExceptionBehavior.empty())
3379 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3380 FPExceptionBehavior));
3381
3382 if (!FPEvalMethod.empty())
3383 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3384
3385 if (!Float16ExcessPrecision.empty())
3386 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3387 Float16ExcessPrecision));
3388 if (!BFloat16ExcessPrecision.empty())
3389 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3390 BFloat16ExcessPrecision));
3391
3392 ParseMRecip(D, Args, CmdArgs);
3393
3394 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3395 // individual features enabled by -ffast-math instead of the option itself as
3396 // that's consistent with gcc's behaviour.
3397 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3398 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3399 CmdArgs.push_back("-ffast-math");
3400
3401 // Handle __FINITE_MATH_ONLY__ similarly.
3402 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3403 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3404 // -menable-no-nans are set by the user.
3405 bool shouldAddFiniteMathOnly = false;
3406 if (!HonorINFs && !HonorNaNs) {
3407 shouldAddFiniteMathOnly = true;
3408 } else {
3409 bool InfValues = true;
3410 bool NanValues = true;
3411 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3412 StringRef ArgValue = Arg->getValue();
3413 if (ArgValue == "-menable-no-nans")
3414 NanValues = false;
3415 else if (ArgValue == "-menable-no-infs")
3416 InfValues = false;
3417 }
3418 if (!NanValues && !InfValues)
3419 shouldAddFiniteMathOnly = true;
3420 }
3421 if (shouldAddFiniteMathOnly) {
3422 CmdArgs.push_back("-ffinite-math-only");
3423 }
3424 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3425 CmdArgs.push_back("-mfpmath");
3426 CmdArgs.push_back(A->getValue());
3427 }
3428
3429 // Disable a codegen optimization for floating-point casts.
3430 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3431 options::OPT_fstrict_float_cast_overflow, false))
3432 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3433
3435 ComplexRangeStr = RenderComplexRangeOption(Range);
3436 if (!ComplexRangeStr.empty()) {
3437 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3438 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3439 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3441 }
3442 if (Args.hasArg(options::OPT_fcx_limited_range))
3443 CmdArgs.push_back("-fcx-limited-range");
3444 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3445 CmdArgs.push_back("-fcx-fortran-rules");
3446 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3447 CmdArgs.push_back("-fno-cx-limited-range");
3448 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3449 CmdArgs.push_back("-fno-cx-fortran-rules");
3450}
3451
3452static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3453 const llvm::Triple &Triple,
3454 const InputInfo &Input) {
3455 // Add default argument set.
3456 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3457 CmdArgs.push_back("-analyzer-checker=core");
3458 CmdArgs.push_back("-analyzer-checker=apiModeling");
3459
3460 if (!Triple.isWindowsMSVCEnvironment()) {
3461 CmdArgs.push_back("-analyzer-checker=unix");
3462 } else {
3463 // Enable "unix" checkers that also work on Windows.
3464 CmdArgs.push_back("-analyzer-checker=unix.API");
3465 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3466 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3467 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3468 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3469 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3470 }
3471
3472 // Disable some unix checkers for PS4/PS5.
3473 if (Triple.isPS()) {
3474 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3475 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3476 }
3477
3478 if (Triple.isOSDarwin()) {
3479 CmdArgs.push_back("-analyzer-checker=osx");
3480 CmdArgs.push_back(
3481 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3482 }
3483 else if (Triple.isOSFuchsia())
3484 CmdArgs.push_back("-analyzer-checker=fuchsia");
3485
3486 CmdArgs.push_back("-analyzer-checker=deadcode");
3487
3488 if (types::isCXX(Input.getType()))
3489 CmdArgs.push_back("-analyzer-checker=cplusplus");
3490
3491 if (!Triple.isPS()) {
3492 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3493 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3494 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3495 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3496 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3497 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3498 }
3499
3500 // Default nullability checks.
3501 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3502 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3503 }
3504
3505 // Set the output format. The default is plist, for (lame) historical reasons.
3506 CmdArgs.push_back("-analyzer-output");
3507 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3508 CmdArgs.push_back(A->getValue());
3509 else
3510 CmdArgs.push_back("plist");
3511
3512 // Disable the presentation of standard compiler warnings when using
3513 // --analyze. We only want to show static analyzer diagnostics or frontend
3514 // errors.
3515 CmdArgs.push_back("-w");
3516
3517 // Add -Xanalyzer arguments when running as analyzer.
3518 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3519}
3520
3521static bool isValidSymbolName(StringRef S) {
3522 if (S.empty())
3523 return false;
3524
3525 if (std::isdigit(S[0]))
3526 return false;
3527
3528 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3529}
3530
3531static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3532 const ArgList &Args, ArgStringList &CmdArgs,
3533 bool KernelOrKext) {
3534 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3535
3536 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3537 // doesn't even have a stack!
3538 if (EffectiveTriple.isNVPTX())
3539 return;
3540
3541 // -stack-protector=0 is default.
3543 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3544 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3545
3546 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3547 options::OPT_fstack_protector_all,
3548 options::OPT_fstack_protector_strong,
3549 options::OPT_fstack_protector)) {
3550 if (A->getOption().matches(options::OPT_fstack_protector))
3551 StackProtectorLevel =
3552 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3553 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3554 StackProtectorLevel = LangOptions::SSPStrong;
3555 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3556 StackProtectorLevel = LangOptions::SSPReq;
3557
3558 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3559 D.Diag(diag::warn_drv_unsupported_option_for_target)
3560 << A->getSpelling() << EffectiveTriple.getTriple();
3561 StackProtectorLevel = DefaultStackProtectorLevel;
3562 }
3563 } else {
3564 StackProtectorLevel = DefaultStackProtectorLevel;
3565 }
3566
3567 if (StackProtectorLevel) {
3568 CmdArgs.push_back("-stack-protector");
3569 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3570 }
3571
3572 // --param ssp-buffer-size=
3573 for (const Arg *A : Args.filtered(options::OPT__param)) {
3574 StringRef Str(A->getValue());
3575 if (Str.starts_with("ssp-buffer-size=")) {
3576 if (StackProtectorLevel) {
3577 CmdArgs.push_back("-stack-protector-buffer-size");
3578 // FIXME: Verify the argument is a valid integer.
3579 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3580 }
3581 A->claim();
3582 }
3583 }
3584
3585 const std::string &TripleStr = EffectiveTriple.getTriple();
3586 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3587 StringRef Value = A->getValue();
3588 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3589 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3590 D.Diag(diag::err_drv_unsupported_opt_for_target)
3591 << A->getAsString(Args) << TripleStr;
3592 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3593 EffectiveTriple.isThumb()) &&
3594 Value != "tls" && Value != "global") {
3595 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3596 << A->getOption().getName() << Value << "tls global";
3597 return;
3598 }
3599 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3600 Value == "tls") {
3601 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3602 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3603 << A->getAsString(Args);
3604 return;
3605 }
3606 // Check whether the target subarch supports the hardware TLS register
3607 if (!arm::isHardTPSupported(EffectiveTriple)) {
3608 D.Diag(diag::err_target_unsupported_tp_hard)
3609 << EffectiveTriple.getArchName();
3610 return;
3611 }
3612 // Check whether the user asked for something other than -mtp=cp15
3613 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3614 StringRef Value = A->getValue();
3615 if (Value != "cp15") {
3616 D.Diag(diag::err_drv_argument_not_allowed_with)
3617 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3618 return;
3619 }
3620 }
3621 CmdArgs.push_back("-target-feature");
3622 CmdArgs.push_back("+read-tp-tpidruro");
3623 }
3624 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3625 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3626 << A->getOption().getName() << Value << "sysreg global";
3627 return;
3628 }
3629 A->render(Args, CmdArgs);
3630 }
3631
3632 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3633 StringRef Value = A->getValue();
3634 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3635 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3636 D.Diag(diag::err_drv_unsupported_opt_for_target)
3637 << A->getAsString(Args) << TripleStr;
3638 int Offset;
3639 if (Value.getAsInteger(10, Offset)) {
3640 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3641 return;
3642 }
3643 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3644 (Offset < 0 || Offset > 0xfffff)) {
3645 D.Diag(diag::err_drv_invalid_int_value)
3646 << A->getOption().getName() << Value;
3647 return;
3648 }
3649 A->render(Args, CmdArgs);
3650 }
3651
3652 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3653 StringRef Value = A->getValue();
3654 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3655 D.Diag(diag::err_drv_unsupported_opt_for_target)
3656 << A->getAsString(Args) << TripleStr;
3657 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3658 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3659 << A->getOption().getName() << Value << "fs gs";
3660 return;
3661 }
3662 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3663 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3664 return;
3665 }
3666 A->render(Args, CmdArgs);
3667 }
3668
3669 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3670 StringRef Value = A->getValue();
3671 if (!isValidSymbolName(Value)) {
3672 D.Diag(diag::err_drv_argument_only_allowed_with)
3673 << A->getOption().getName() << "legal symbol name";
3674 return;
3675 }
3676 A->render(Args, CmdArgs);
3677 }
3678}
3679
3680static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3681 ArgStringList &CmdArgs) {
3682 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3683
3684 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3685 return;
3686
3687 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3688 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
3689 return;
3690
3691 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3692 options::OPT_fno_stack_clash_protection);
3693}
3694
3696 const ToolChain &TC,
3697 const ArgList &Args,
3698 ArgStringList &CmdArgs) {
3699 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3700 StringRef TrivialAutoVarInit = "";
3701
3702 for (const Arg *A : Args) {
3703 switch (A->getOption().getID()) {
3704 default:
3705 continue;
3706 case options::OPT_ftrivial_auto_var_init: {
3707 A->claim();
3708 StringRef Val = A->getValue();
3709 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3710 TrivialAutoVarInit = Val;
3711 else
3712 D.Diag(diag::err_drv_unsupported_option_argument)
3713 << A->getSpelling() << Val;
3714 break;
3715 }
3716 }
3717 }
3718
3719 if (TrivialAutoVarInit.empty())
3720 switch (DefaultTrivialAutoVarInit) {
3722 break;
3724 TrivialAutoVarInit = "pattern";
3725 break;
3727 TrivialAutoVarInit = "zero";
3728 break;
3729 }
3730
3731 if (!TrivialAutoVarInit.empty()) {
3732 CmdArgs.push_back(
3733 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3734 }
3735
3736 if (Arg *A =
3737 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3738 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3739 StringRef(
3740 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3741 "uninitialized")
3742 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3743 A->claim();
3744 StringRef Val = A->getValue();
3745 if (std::stoi(Val.str()) <= 0)
3746 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3747 CmdArgs.push_back(
3748 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3749 }
3750
3751 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3752 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3753 StringRef(
3754 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3755 "uninitialized")
3756 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3757 A->claim();
3758 StringRef Val = A->getValue();
3759 if (std::stoi(Val.str()) <= 0)
3760 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3761 CmdArgs.push_back(
3762 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3763 }
3764}
3765
3766static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3767 types::ID InputType) {
3768 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3769 // for denormal flushing handling based on the target.
3770 const unsigned ForwardedArguments[] = {
3771 options::OPT_cl_opt_disable,
3772 options::OPT_cl_strict_aliasing,
3773 options::OPT_cl_single_precision_constant,
3774 options::OPT_cl_finite_math_only,
3775 options::OPT_cl_kernel_arg_info,
3776 options::OPT_cl_unsafe_math_optimizations,
3777 options::OPT_cl_fast_relaxed_math,
3778 options::OPT_cl_mad_enable,
3779 options::OPT_cl_no_signed_zeros,
3780 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3781 options::OPT_cl_uniform_work_group_size
3782 };
3783
3784 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3785 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3786 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3787 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3788 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3789 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3790 }
3791
3792 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3793 CmdArgs.push_back("-menable-no-infs");
3794 CmdArgs.push_back("-menable-no-nans");
3795 }
3796
3797 for (const auto &Arg : ForwardedArguments)
3798 if (const auto *A = Args.getLastArg(Arg))
3799 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3800
3801 // Only add the default headers if we are compiling OpenCL sources.
3802 if ((types::isOpenCL(InputType) ||
3803 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3804 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3805 CmdArgs.push_back("-finclude-default-header");
3806 CmdArgs.push_back("-fdeclare-opencl-builtins");
3807 }
3808}
3809
3810static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3811 types::ID InputType) {
3812 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3813 options::OPT_D,
3814 options::OPT_I,
3815 options::OPT_O,
3816 options::OPT_emit_llvm,
3817 options::OPT_emit_obj,
3818 options::OPT_disable_llvm_passes,
3819 options::OPT_fnative_half_type,
3820 options::OPT_hlsl_entrypoint};
3821 if (!types::isHLSL(InputType))
3822 return;
3823 for (const auto &Arg : ForwardedArguments)
3824 if (const auto *A = Args.getLastArg(Arg))
3825 A->renderAsInput(Args, CmdArgs);
3826 // Add the default headers if dxc_no_stdinc is not set.
3827 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3828 !Args.hasArg(options::OPT_nostdinc))
3829 CmdArgs.push_back("-finclude-default-header");
3830}
3831
3832static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3833 ArgStringList &CmdArgs, types::ID InputType) {
3834 if (!Args.hasArg(options::OPT_fopenacc))
3835 return;
3836
3837 CmdArgs.push_back("-fopenacc");
3838
3839 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3840 StringRef Value = A->getValue();
3841 int Version;
3842 if (!Value.getAsInteger(10, Version))
3843 A->renderAsInput(Args, CmdArgs);
3844 else
3845 D.Diag(diag::err_drv_clang_unsupported) << Value;
3846 }
3847}
3848
3849static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3850 ArgStringList &CmdArgs) {
3851 bool ARCMTEnabled = false;
3852 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3853 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3854 options::OPT_ccc_arcmt_modify,
3855 options::OPT_ccc_arcmt_migrate)) {
3856 ARCMTEnabled = true;
3857 switch (A->getOption().getID()) {
3858 default: llvm_unreachable("missed a case");
3859 case options::OPT_ccc_arcmt_check:
3860 CmdArgs.push_back("-arcmt-action=check");
3861 break;
3862 case options::OPT_ccc_arcmt_modify:
3863 CmdArgs.push_back("-arcmt-action=modify");
3864 break;
3865 case options::OPT_ccc_arcmt_migrate:
3866 CmdArgs.push_back("-arcmt-action=migrate");
3867 CmdArgs.push_back("-mt-migrate-directory");
3868 CmdArgs.push_back(A->getValue());
3869
3870 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3871 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3872 break;
3873 }
3874 }
3875 } else {
3876 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3877 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3878 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3879 }
3880
3881 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3882 if (ARCMTEnabled)
3883 D.Diag(diag::err_drv_argument_not_allowed_with)
3884 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3885
3886 CmdArgs.push_back("-mt-migrate-directory");
3887 CmdArgs.push_back(A->getValue());
3888
3889 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3890 options::OPT_objcmt_migrate_subscripting,
3891 options::OPT_objcmt_migrate_property)) {
3892 // None specified, means enable them all.
3893 CmdArgs.push_back("-objcmt-migrate-literals");
3894 CmdArgs.push_back("-objcmt-migrate-subscripting");
3895 CmdArgs.push_back("-objcmt-migrate-property");
3896 } else {
3897 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3898 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3899 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3900 }
3901 } else {
3902 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3903 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3904 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3905 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3906 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3907 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3908 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3909 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3910 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3911 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3912 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3913 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3914 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3915 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3916 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3917 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3918 }
3919}
3920
3921static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3922 const ArgList &Args, ArgStringList &CmdArgs) {
3923 // -fbuiltin is default unless -mkernel is used.
3924 bool UseBuiltins =
3925 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3926 !Args.hasArg(options::OPT_mkernel));
3927 if (!UseBuiltins)
3928 CmdArgs.push_back("-fno-builtin");
3929
3930 // -ffreestanding implies -fno-builtin.
3931 if (Args.hasArg(options::OPT_ffreestanding))
3932 UseBuiltins = false;
3933
3934 // Process the -fno-builtin-* options.
3935 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3936 A->claim();
3937
3938 // If -fno-builtin is specified, then there's no need to pass the option to
3939 // the frontend.
3940 if (UseBuiltins)
3941 A->render(Args, CmdArgs);
3942 }
3943}
3944
3946 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3947 Twine Path{Str};
3948 Path.toVector(Result);
3949 return Path.getSingleStringRef() != "";
3950 }
3951 if (llvm::sys::path::cache_directory(Result)) {
3952 llvm::sys::path::append(Result, "clang");
3953 llvm::sys::path::append(Result, "ModuleCache");
3954 return true;
3955 }
3956 return false;
3957}
3958
3961 const char *BaseInput) {
3962 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
3963 return StringRef(ModuleOutputEQ->getValue());
3964
3965 SmallString<256> OutputPath;
3966 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3967 FinalOutput && Args.hasArg(options::OPT_c))
3968 OutputPath = FinalOutput->getValue();
3969 else
3970 OutputPath = BaseInput;
3971
3972 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
3973 llvm::sys::path::replace_extension(OutputPath, Extension);
3974 return OutputPath;
3975}
3976
3978 const ArgList &Args, const InputInfo &Input,
3979 const InputInfo &Output, bool HaveStd20,
3980 ArgStringList &CmdArgs) {
3981 bool IsCXX = types::isCXX(Input.getType());
3982 bool HaveStdCXXModules = IsCXX && HaveStd20;
3983 bool HaveModules = HaveStdCXXModules;
3984
3985 // -fmodules enables the use of precompiled modules (off by default).
3986 // Users can pass -fno-cxx-modules to turn off modules support for
3987 // C++/Objective-C++ programs.
3988 bool HaveClangModules = false;
3989 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3990 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3991 options::OPT_fno_cxx_modules, true);
3992 if (AllowedInCXX || !IsCXX) {
3993 CmdArgs.push_back("-fmodules");
3994 HaveClangModules = true;
3995 }
3996 }
3997
3998 HaveModules |= HaveClangModules;
3999
4000 // -fmodule-maps enables implicit reading of module map files. By default,
4001 // this is enabled if we are using Clang's flavor of precompiled modules.
4002 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4003 options::OPT_fno_implicit_module_maps, HaveClangModules))
4004 CmdArgs.push_back("-fimplicit-module-maps");
4005
4006 // -fmodules-decluse checks that modules used are declared so (off by default)
4007 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4008 options::OPT_fno_modules_decluse);
4009
4010 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4011 // all #included headers are part of modules.
4012 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4013 options::OPT_fno_modules_strict_decluse, false))
4014 CmdArgs.push_back("-fmodules-strict-decluse");
4015
4016 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4017 options::OPT_fno_modulemap_allow_subdirectory_search);
4018
4019 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4020 bool ImplicitModules = false;
4021 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4022 options::OPT_fno_implicit_modules, HaveClangModules)) {
4023 if (HaveModules)
4024 CmdArgs.push_back("-fno-implicit-modules");
4025 } else if (HaveModules) {
4026 ImplicitModules = true;
4027 // -fmodule-cache-path specifies where our implicitly-built module files
4028 // should be written.
4030 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4031 Path = A->getValue();
4032
4033 bool HasPath = true;
4034 if (C.isForDiagnostics()) {
4035 // When generating crash reports, we want to emit the modules along with
4036 // the reproduction sources, so we ignore any provided module path.
4037 Path = Output.getFilename();
4038 llvm::sys::path::replace_extension(Path, ".cache");
4039 llvm::sys::path::append(Path, "modules");
4040 } else if (Path.empty()) {
4041 // No module path was provided: use the default.
4043 }
4044
4045 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4046 // That being said, that failure is unlikely and not caching is harmless.
4047 if (HasPath) {
4048 const char Arg[] = "-fmodules-cache-path=";
4049 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4050 CmdArgs.push_back(Args.MakeArgString(Path));
4051 }
4052 }
4053
4054 if (HaveModules) {
4055 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4056 options::OPT_fno_prebuilt_implicit_modules, false))
4057 CmdArgs.push_back("-fprebuilt-implicit-modules");
4058 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4059 options::OPT_fno_modules_validate_input_files_content,
4060 false))
4061 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4062 }
4063
4064 // -fmodule-name specifies the module that is currently being built (or
4065 // used for header checking by -fmodule-maps).
4066 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4067
4068 // -fmodule-map-file can be used to specify files containing module
4069 // definitions.
4070 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4071
4072 // -fbuiltin-module-map can be used to load the clang
4073 // builtin headers modulemap file.
4074 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4075 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4076 llvm::sys::path::append(BuiltinModuleMap, "include");
4077 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4078 if (llvm::sys::fs::exists(BuiltinModuleMap))
4079 CmdArgs.push_back(
4080 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4081 }
4082
4083 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4084 // names to precompiled module files (the module is loaded only if used).
4085 // The -fmodule-file=<file> form can be used to unconditionally load
4086 // precompiled module files (whether used or not).
4087 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4088 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4089
4090 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4091 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4092 CmdArgs.push_back(Args.MakeArgString(
4093 std::string("-fprebuilt-module-path=") + A->getValue()));
4094 A->claim();
4095 }
4096 } else
4097 Args.ClaimAllArgs(options::OPT_fmodule_file);
4098
4099 // When building modules and generating crashdumps, we need to dump a module
4100 // dependency VFS alongside the output.
4101 if (HaveClangModules && C.isForDiagnostics()) {
4102 SmallString<128> VFSDir(Output.getFilename());
4103 llvm::sys::path::replace_extension(VFSDir, ".cache");
4104 // Add the cache directory as a temp so the crash diagnostics pick it up.
4105 C.addTempFile(Args.MakeArgString(VFSDir));
4106
4107 llvm::sys::path::append(VFSDir, "vfs");
4108 CmdArgs.push_back("-module-dependency-dir");
4109 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4110 }
4111
4112 if (HaveClangModules)
4113 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4114
4115 // Pass through all -fmodules-ignore-macro arguments.
4116 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4117 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4118 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4119
4120 if (HaveClangModules) {
4121 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4122
4123 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4124 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4125 D.Diag(diag::err_drv_argument_not_allowed_with)
4126 << A->getAsString(Args) << "-fbuild-session-timestamp";
4127
4128 llvm::sys::fs::file_status Status;
4129 if (llvm::sys::fs::status(A->getValue(), Status))
4130 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4131 CmdArgs.push_back(Args.MakeArgString(
4132 "-fbuild-session-timestamp=" +
4133 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4134 Status.getLastModificationTime().time_since_epoch())
4135 .count())));
4136 }
4137
4138 if (Args.getLastArg(
4139 options::OPT_fmodules_validate_once_per_build_session)) {
4140 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4141 options::OPT_fbuild_session_file))
4142 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4143
4144 Args.AddLastArg(CmdArgs,
4145 options::OPT_fmodules_validate_once_per_build_session);
4146 }
4147
4148 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4149 options::OPT_fno_modules_validate_system_headers,
4150 ImplicitModules))
4151 CmdArgs.push_back("-fmodules-validate-system-headers");
4152
4153 Args.AddLastArg(CmdArgs,
4154 options::OPT_fmodules_disable_diagnostic_validation);
4155 } else {
4156 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4157 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4158 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4159 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4160 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4161 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4162 }
4163
4164 // FIXME: We provisionally don't check ODR violations for decls in the global
4165 // module fragment.
4166 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4167
4168 if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
4169 (Input.getType() == driver::types::TY_CXXModule ||
4170 Input.getType() == driver::types::TY_PP_CXXModule)) {
4171 CmdArgs.push_back("-fexperimental-modules-reduced-bmi");
4172
4173 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4174 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4175 else
4176 CmdArgs.push_back(Args.MakeArgString(
4177 "-fmodule-output=" +
4179 }
4180
4181 // Noop if we see '-fexperimental-modules-reduced-bmi' with other translation
4182 // units than module units. This is more user friendly to allow end uers to
4183 // enable this feature without asking for help from build systems.
4184 Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
4185
4186 // We need to include the case the input file is a module file here.
4187 // Since the default compilation model for C++ module interface unit will
4188 // create temporary module file and compile the temporary module file
4189 // to get the object file. Then the `-fmodule-output` flag will be
4190 // brought to the second compilation process. So we have to claim it for
4191 // the case too.
4192 if (Input.getType() == driver::types::TY_CXXModule ||
4193 Input.getType() == driver::types::TY_PP_CXXModule ||
4194 Input.getType() == driver::types::TY_ModuleFile) {
4195 Args.ClaimAllArgs(options::OPT_fmodule_output);
4196 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4197 }
4198
4199 return HaveModules;
4200}
4201
4202static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4203 ArgStringList &CmdArgs) {
4204 // -fsigned-char is default.
4205 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4206 options::OPT_fno_signed_char,
4207 options::OPT_funsigned_char,
4208 options::OPT_fno_unsigned_char)) {
4209 if (A->getOption().matches(options::OPT_funsigned_char) ||
4210 A->getOption().matches(options::OPT_fno_signed_char)) {
4211 CmdArgs.push_back("-fno-signed-char");
4212 }
4213 } else if (!isSignedCharDefault(T)) {
4214 CmdArgs.push_back("-fno-signed-char");
4215 }
4216
4217 // The default depends on the language standard.
4218 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4219
4220 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4221 options::OPT_fno_short_wchar)) {
4222 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4223 CmdArgs.push_back("-fwchar-type=short");
4224 CmdArgs.push_back("-fno-signed-wchar");
4225 } else {
4226 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4227 CmdArgs.push_back("-fwchar-type=int");
4228 if (T.isOSzOS() ||
4229 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4230 CmdArgs.push_back("-fno-signed-wchar");
4231 else
4232 CmdArgs.push_back("-fsigned-wchar");
4233 }
4234 } else if (T.isOSzOS())
4235 CmdArgs.push_back("-fno-signed-wchar");
4236}
4237
4238static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4239 const llvm::Triple &T, const ArgList &Args,
4240 ObjCRuntime &Runtime, bool InferCovariantReturns,
4241 const InputInfo &Input, ArgStringList &CmdArgs) {
4242 const llvm::Triple::ArchType Arch = TC.getArch();
4243
4244 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4245 // is the default. Except for deployment target of 10.5, next runtime is
4246 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4247 if (Runtime.isNonFragile()) {
4248 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4249 options::OPT_fno_objc_legacy_dispatch,
4250 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4251 if (TC.UseObjCMixedDispatch())
4252 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4253 else
4254 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4255 }
4256 }
4257
4258 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4259 // to do Array/Dictionary subscripting by default.
4260 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4261 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4262 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4263
4264 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4265 // NOTE: This logic is duplicated in ToolChains.cpp.
4266 if (isObjCAutoRefCount(Args)) {
4267 TC.CheckObjCARC();
4268
4269 CmdArgs.push_back("-fobjc-arc");
4270
4271 // FIXME: It seems like this entire block, and several around it should be
4272 // wrapped in isObjC, but for now we just use it here as this is where it
4273 // was being used previously.
4274 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4276 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4277 else
4278 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4279 }
4280
4281 // Allow the user to enable full exceptions code emission.
4282 // We default off for Objective-C, on for Objective-C++.
4283 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4284 options::OPT_fno_objc_arc_exceptions,
4285 /*Default=*/types::isCXX(Input.getType())))
4286 CmdArgs.push_back("-fobjc-arc-exceptions");
4287 }
4288
4289 // Silence warning for full exception code emission options when explicitly
4290 // set to use no ARC.
4291 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4292 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4293 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4294 }
4295
4296 // Allow the user to control whether messages can be converted to runtime
4297 // functions.
4298 if (types::isObjC(Input.getType())) {
4299 auto *Arg = Args.getLastArg(
4300 options::OPT_fobjc_convert_messages_to_runtime_calls,
4301 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4302 if (Arg &&
4303 Arg->getOption().matches(
4304 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4305 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4306 }
4307
4308 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4309 // rewriter.
4310 if (InferCovariantReturns)
4311 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4312
4313 // Pass down -fobjc-weak or -fno-objc-weak if present.
4314 if (types::isObjC(Input.getType())) {
4315 auto WeakArg =
4316 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4317 if (!WeakArg) {
4318 // nothing to do
4319 } else if (!Runtime.allowsWeak()) {
4320 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4321 D.Diag(diag::err_objc_weak_unsupported);
4322 } else {
4323 WeakArg->render(Args, CmdArgs);
4324 }
4325 }
4326
4327 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4328 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4329}
4330
4331static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4332 ArgStringList &CmdArgs) {
4333 bool CaretDefault = true;
4334 bool ColumnDefault = true;
4335
4336 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4337 options::OPT__SLASH_diagnostics_column,
4338 options::OPT__SLASH_diagnostics_caret)) {
4339 switch (A->getOption().getID()) {
4340 case options::OPT__SLASH_diagnostics_caret:
4341 CaretDefault = true;
4342 ColumnDefault = true;
4343 break;
4344 case options::OPT__SLASH_diagnostics_column:
4345 CaretDefault = false;
4346 ColumnDefault = true;
4347 break;
4348 case options::OPT__SLASH_diagnostics_classic:
4349 CaretDefault = false;
4350 ColumnDefault = false;
4351 break;
4352 }
4353 }
4354
4355 // -fcaret-diagnostics is default.
4356 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4357 options::OPT_fno_caret_diagnostics, CaretDefault))
4358 CmdArgs.push_back("-fno-caret-diagnostics");
4359
4360 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4361 options::OPT_fno_diagnostics_fixit_info);
4362 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4363 options::OPT_fno_diagnostics_show_option);
4364
4365 if (const Arg *A =
4366 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4367 CmdArgs.push_back("-fdiagnostics-show-category");
4368 CmdArgs.push_back(A->getValue());
4369 }
4370
4371 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4372 options::OPT_fno_diagnostics_show_hotness);
4373
4374 if (const Arg *A =
4375 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4376 std::string Opt =
4377 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4378 CmdArgs.push_back(Args.MakeArgString(Opt));
4379 }
4380
4381 if (const Arg *A =
4382 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4383 std::string Opt =
4384 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4385 CmdArgs.push_back(Args.MakeArgString(Opt));
4386 }
4387
4388 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4389 CmdArgs.push_back("-fdiagnostics-format");
4390 CmdArgs.push_back(A->getValue());
4391 if (StringRef(A->getValue()) == "sarif" ||
4392 StringRef(A->getValue()) == "SARIF")
4393 D.Diag(diag::warn_drv_sarif_format_unstable);
4394 }
4395
4396 if (const Arg *A = Args.getLastArg(
4397 options::OPT_fdiagnostics_show_note_include_stack,
4398 options::OPT_fno_diagnostics_show_note_include_stack)) {
4399 const Option &O = A->getOption();
4400 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4401 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4402 else
4403 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4404 }
4405
4406 // Color diagnostics are parsed by the driver directly from argv and later
4407 // re-parsed to construct this job; claim any possible color diagnostic here
4408 // to avoid warn_drv_unused_argument and diagnose bad
4409 // OPT_fdiagnostics_color_EQ values.
4410 Args.getLastArg(options::OPT_fcolor_diagnostics,
4411 options::OPT_fno_color_diagnostics);
4412 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4413 StringRef Value(A->getValue());
4414 if (Value != "always" && Value != "never" && Value != "auto")
4415 D.Diag(diag::err_drv_invalid_argument_to_option)
4416 << Value << A->getOption().getName();
4417 }
4418
4419 if (D.getDiags().getDiagnosticOptions().ShowColors)
4420 CmdArgs.push_back("-fcolor-diagnostics");
4421
4422 if (Args.hasArg(options::OPT_fansi_escape_codes))
4423 CmdArgs.push_back("-fansi-escape-codes");
4424
4425 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4426 options::OPT_fno_show_source_location);
4427
4428 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4429 options::OPT_fno_diagnostics_show_line_numbers);
4430
4431 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4432 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4433
4434 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4435 ColumnDefault))
4436 CmdArgs.push_back("-fno-show-column");
4437
4438 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4439 options::OPT_fno_spell_checking);
4440}
4441
4443 const ArgList &Args, Arg *&Arg) {
4444 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4445 options::OPT_gno_split_dwarf);
4446 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4448
4449 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4451
4452 StringRef Value = Arg->getValue();
4453 if (Value == "split")
4455 if (Value == "single")
4457
4458 D.Diag(diag::err_drv_unsupported_option_argument)
4459 << Arg->getSpelling() << Arg->getValue();
4461}
4462
4463static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4464 const ArgList &Args, ArgStringList &CmdArgs,
4465 unsigned DwarfVersion) {
4466 auto *DwarfFormatArg =
4467 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4468 if (!DwarfFormatArg)
4469 return;
4470
4471 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4472 if (DwarfVersion < 3)
4473 D.Diag(diag::err_drv_argument_only_allowed_with)
4474 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4475 else if (!T.isArch64Bit())
4476 D.Diag(diag::err_drv_argument_only_allowed_with)
4477 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4478 else if (!T.isOSBinFormatELF())
4479 D.Diag(diag::err_drv_argument_only_allowed_with)
4480 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4481 }
4482
4483 DwarfFormatArg->render(Args, CmdArgs);
4484}
4485
4486static void
4487renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4488 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4489 const InputInfo &Output,
4490 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4491 DwarfFissionKind &DwarfFission) {
4492 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4493 options::OPT_fno_debug_info_for_profiling, false) &&
4495 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4496 CmdArgs.push_back("-fdebug-info-for-profiling");
4497
4498 // The 'g' groups options involve a somewhat intricate sequence of decisions
4499 // about what to pass from the driver to the frontend, but by the time they
4500 // reach cc1 they've been factored into three well-defined orthogonal choices:
4501 // * what level of debug info to generate
4502 // * what dwarf version to write
4503 // * what debugger tuning to use
4504 // This avoids having to monkey around further in cc1 other than to disable
4505 // codeview if not running in a Windows environment. Perhaps even that
4506 // decision should be made in the driver as well though.
4507 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4508
4509 bool SplitDWARFInlining =
4510 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4511 options::OPT_fno_split_dwarf_inlining, false);
4512
4513 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4514 // object file generation and no IR generation, -gN should not be needed. So
4515 // allow -gsplit-dwarf with either -gN or IR input.
4516 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4517 Arg *SplitDWARFArg;
4518 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4519 if (DwarfFission != DwarfFissionKind::None &&
4520 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4521 DwarfFission = DwarfFissionKind::None;
4522 SplitDWARFInlining = false;
4523 }
4524 }
4525 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4526 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4527
4528 // If the last option explicitly specified a debug-info level, use it.
4529 if (checkDebugInfoOption(A, Args, D, TC) &&
4530 A->getOption().matches(options::OPT_gN_Group)) {
4531 DebugInfoKind = debugLevelToInfoKind(*A);
4532 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4533 // complicated if you've disabled inline info in the skeleton CUs
4534 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4535 // line-tables-only, so let those compose naturally in that case.
4536 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4537 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4538 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4539 SplitDWARFInlining))
4540 DwarfFission = DwarfFissionKind::None;
4541 }
4542 }
4543
4544 // If a debugger tuning argument appeared, remember it.
4545 bool HasDebuggerTuning = false;
4546 if (const Arg *A =
4547 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4548 HasDebuggerTuning = true;
4549 if (checkDebugInfoOption(A, Args, D, TC)) {
4550 if (A->getOption().matches(options::OPT_glldb))
4551 DebuggerTuning = llvm::DebuggerKind::LLDB;
4552 else if (A->getOption().matches(options::OPT_gsce))
4553 DebuggerTuning = llvm::DebuggerKind::SCE;
4554 else if (A->getOption().matches(options::OPT_gdbx))
4555 DebuggerTuning = llvm::DebuggerKind::DBX;
4556 else
4557 DebuggerTuning = llvm::DebuggerKind::GDB;
4558 }
4559 }
4560
4561 // If a -gdwarf argument appeared, remember it.
4562 bool EmitDwarf = false;
4563 if (const Arg *A = getDwarfNArg(Args))
4564 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4565
4566 bool EmitCodeView = false;
4567 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4568 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4569
4570 // If the user asked for debug info but did not explicitly specify -gcodeview
4571 // or -gdwarf, ask the toolchain for the default format.
4572 if (!EmitCodeView && !EmitDwarf &&
4573 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4574 switch (TC.getDefaultDebugFormat()) {
4575 case llvm::codegenoptions::DIF_CodeView:
4576 EmitCodeView = true;
4577 break;
4578 case llvm::codegenoptions::DIF_DWARF:
4579 EmitDwarf = true;
4580 break;
4581 }
4582 }
4583
4584 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4585 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4586 // be lower than what the user wanted.
4587 if (EmitDwarf) {
4588 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4589 // Clamp effective DWARF version to the max supported by the toolchain.
4590 EffectiveDWARFVersion =
4591 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4592 } else {
4593 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4594 }
4595
4596 // -gline-directives-only supported only for the DWARF debug info.
4597 if (RequestedDWARFVersion == 0 &&
4598 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4599 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4600
4601 // strict DWARF is set to false by default. But for DBX, we need it to be set
4602 // as true by default.
4603 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4604 (void)checkDebugInfoOption(A, Args, D, TC);
4605 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4606 DebuggerTuning == llvm::DebuggerKind::DBX))
4607 CmdArgs.push_back("-gstrict-dwarf");
4608
4609 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4610 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4611
4612 // Column info is included by default for everything except SCE and
4613 // CodeView. Clang doesn't track end columns, just starting columns, which,
4614 // in theory, is fine for CodeView (and PDB). In practice, however, the
4615 // Microsoft debuggers don't handle missing end columns well, and the AIX
4616 // debugger DBX also doesn't handle the columns well, so it's better not to
4617 // include any column info.
4618 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4619 (void)checkDebugInfoOption(A, Args, D, TC);
4620 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4621 !EmitCodeView &&
4622 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4623 DebuggerTuning != llvm::DebuggerKind::DBX)))
4624 CmdArgs.push_back("-gno-column-info");
4625
4626 // FIXME: Move backend command line options to the module.
4627 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4628 // If -gline-tables-only or -gline-directives-only is the last option it
4629 // wins.
4630 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4631 TC)) {
4632 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4633 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4634 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4635 CmdArgs.push_back("-dwarf-ext-refs");
4636 CmdArgs.push_back("-fmodule-format=obj");
4637 }
4638 }
4639 }
4640
4641 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4642 CmdArgs.push_back("-fsplit-dwarf-inlining");
4643
4644 // After we've dealt with all combinations of things that could
4645 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4646 // figure out if we need to "upgrade" it to standalone debug info.
4647 // We parse these two '-f' options whether or not they will be used,
4648 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4649 bool NeedFullDebug = Args.hasFlag(
4650 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4651 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4653 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4654 (void)checkDebugInfoOption(A, Args, D, TC);
4655
4656 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4657 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4658 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4659 options::OPT_feliminate_unused_debug_types, false))
4660 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4661 else if (NeedFullDebug)
4662 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4663 }
4664
4665 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4666 false)) {
4667 // Source embedding is a vendor extension to DWARF v5. By now we have
4668 // checked if a DWARF version was stated explicitly, and have otherwise
4669 // fallen back to the target default, so if this is still not at least 5
4670 // we emit an error.
4671 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4672 if (RequestedDWARFVersion < 5)
4673 D.Diag(diag::err_drv_argument_only_allowed_with)
4674 << A->getAsString(Args) << "-gdwarf-5";
4675 else if (EffectiveDWARFVersion < 5)
4676 // The toolchain has reduced allowed dwarf version, so we can't enable
4677 // -gembed-source.
4678 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4679 << A->getAsString(Args) << TC.getTripleString() << 5
4680 << EffectiveDWARFVersion;
4681 else if (checkDebugInfoOption(A, Args, D, TC))
4682 CmdArgs.push_back("-gembed-source");
4683 }
4684
4685 if (EmitCodeView) {
4686 CmdArgs.push_back("-gcodeview");
4687
4688 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4689 options::OPT_gno_codeview_ghash);
4690
4691 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4692 options::OPT_gno_codeview_command_line);
4693 }
4694
4695 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4696 options::OPT_gno_inline_line_tables);
4697
4698 // When emitting remarks, we need at least debug lines in the output.
4699 if (willEmitRemarks(Args) &&
4700 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4701 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4702
4703 // Adjust the debug info kind for the given toolchain.
4704 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4705
4706 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4707 // set.
4708 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4709 T.isOSAIX() && !HasDebuggerTuning
4710 ? llvm::DebuggerKind::Default
4711 : DebuggerTuning);
4712
4713 // -fdebug-macro turns on macro debug info generation.
4714 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4715 false))
4716 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4717 D, TC))
4718 CmdArgs.push_back("-debug-info-macro");
4719
4720 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4721 const auto *PubnamesArg =
4722 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4723 options::OPT_gpubnames, options::OPT_gno_pubnames);
4724 if (DwarfFission != DwarfFissionKind::None ||
4725 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4726 const bool OptionSet =
4727 (PubnamesArg &&
4728 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4729 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4730 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4731 (!PubnamesArg ||
4732 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4733 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4734 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4735 options::OPT_gpubnames)
4736 ? "-gpubnames"
4737 : "-ggnu-pubnames");
4738 }
4739 const auto *SimpleTemplateNamesArg =
4740 Args.getLastArg(options::OPT_gsimple_template_names,
4741 options::OPT_gno_simple_template_names);
4742 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4743 if (SimpleTemplateNamesArg &&
4744 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4745 const auto &Opt = SimpleTemplateNamesArg->getOption();
4746 if (Opt.matches(options::OPT_gsimple_template_names)) {
4747 ForwardTemplateParams = true;
4748 CmdArgs.push_back("-gsimple-template-names=simple");
4749 }
4750 }
4751
4752 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4753 bool UseDebugTemplateAlias =
4754 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4755 if (const auto *DebugTemplateAlias = Args.getLastArg(
4756 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4757 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4758 // asks for it we should let them have it (if the target supports it).
4759 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4760 const auto &Opt = DebugTemplateAlias->getOption();
4761 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4762 }
4763 }
4764 if (UseDebugTemplateAlias)
4765 CmdArgs.push_back("-gtemplate-alias");
4766
4767 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4768 StringRef v = A->getValue();
4769 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4770 }
4771
4772 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4773 options::OPT_fno_debug_ranges_base_address);
4774
4775 // -gdwarf-aranges turns on the emission of the aranges section in the
4776 // backend.
4777 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4778 A && checkDebugInfoOption(A, Args, D, TC)) {
4779 CmdArgs.push_back("-mllvm");
4780 CmdArgs.push_back("-generate-arange-section");
4781 }
4782
4783 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4784 options::OPT_fno_force_dwarf_frame);
4785
4786 bool EnableTypeUnits = false;
4787 if (Args.hasFlag(options::OPT_fdebug_types_section,
4788 options::OPT_fno_debug_types_section, false)) {
4789 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4790 D.Diag(diag::err_drv_unsupported_opt_for_target)
4791 << Args.getLastArg(options::OPT_fdebug_types_section)
4792 ->getAsString(Args)
4793 << T.getTriple();
4794 } else if (checkDebugInfoOption(
4795 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4796 TC)) {
4797 EnableTypeUnits = true;
4798 CmdArgs.push_back("-mllvm");
4799 CmdArgs.push_back("-generate-type-units");
4800 }
4801 }
4802
4803 if (const Arg *A =
4804 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4805 options::OPT_gno_omit_unreferenced_methods))
4806 (void)checkDebugInfoOption(A, Args, D, TC);
4807 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4808 options::OPT_gno_omit_unreferenced_methods, false) &&
4809 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4810 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4811 !EnableTypeUnits) {
4812 CmdArgs.push_back("-gomit-unreferenced-methods");
4813 }
4814
4815 // To avoid join/split of directory+filename, the integrated assembler prefers
4816 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4817 // form before DWARF v5.
4818 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4819 options::OPT_fno_dwarf_directory_asm,
4820 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4821 CmdArgs.push_back("-fno-dwarf-directory-asm");
4822
4823 // Decide how to render forward declarations of template instantiations.
4824 // SCE wants full descriptions, others just get them in the name.
4825 if (ForwardTemplateParams)
4826 CmdArgs.push_back("-debug-forward-template-params");
4827
4828 // Do we need to explicitly import anonymous namespaces into the parent
4829 // scope?
4830 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4831 CmdArgs.push_back("-dwarf-explicit-import");
4832
4833 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4834 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4835
4836 // This controls whether or not we perform JustMyCode instrumentation.
4837 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4838 if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
4839 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4840 CmdArgs.push_back("-fjmc");
4841 else if (D.IsCLMode())
4842 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4843 << "'/Zi', '/Z7'";
4844 else
4845 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4846 << "-g";
4847 } else {
4848 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4849 }
4850 }
4851
4852 // Add in -fdebug-compilation-dir if necessary.
4853 const char *DebugCompilationDir =
4854 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4855
4856 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4857
4858 // Add the output path to the object file for CodeView debug infos.
4859 if (EmitCodeView && Output.isFilename())
4860 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4861 Output.getFilename());
4862}
4863
4864static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4865 ArgStringList &CmdArgs) {
4866 unsigned RTOptionID = options::OPT__SLASH_MT;
4867
4868 if (Args.hasArg(options::OPT__SLASH_LDd))
4869 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4870 // but defining _DEBUG is sticky.
4871 RTOptionID = options::OPT__SLASH_MTd;
4872
4873 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4874 RTOptionID = A->getOption().getID();
4875
4876 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4877 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4878 .Case("static", options::OPT__SLASH_MT)
4879 .Case("static_dbg", options::OPT__SLASH_MTd)
4880 .Case("dll", options::OPT__SLASH_MD)
4881 .Case("dll_dbg", options::OPT__SLASH_MDd)
4882 .Default(options::OPT__SLASH_MT);
4883 }
4884
4885 StringRef FlagForCRT;
4886 switch (RTOptionID) {
4887 case options::OPT__SLASH_MD:
4888 if (Args.hasArg(options::OPT__SLASH_LDd))
4889 CmdArgs.push_back("-D_DEBUG");
4890 CmdArgs.push_back("-D_MT");
4891 CmdArgs.push_back("-D_DLL");
4892 FlagForCRT = "--dependent-lib=msvcrt";
4893 break;
4894 case options::OPT__SLASH_MDd:
4895 CmdArgs.push_back("-D_DEBUG");
4896 CmdArgs.push_back("-D_MT");
4897 CmdArgs.push_back("-D_DLL");
4898 FlagForCRT = "--dependent-lib=msvcrtd";
4899 break;
4900 case options::OPT__SLASH_MT:
4901 if (Args.hasArg(options::OPT__SLASH_LDd))
4902 CmdArgs.push_back("-D_DEBUG");
4903 CmdArgs.push_back("-D_MT");
4904 CmdArgs.push_back("-flto-visibility-public-std");
4905 FlagForCRT = "--dependent-lib=libcmt";
4906 break;
4907 case options::OPT__SLASH_MTd:
4908 CmdArgs.push_back("-D_DEBUG");
4909 CmdArgs.push_back("-D_MT");
4910 CmdArgs.push_back("-flto-visibility-public-std");
4911 FlagForCRT = "--dependent-lib=libcmtd";
4912 break;
4913 default:
4914 llvm_unreachable("Unexpected option ID.");
4915 }
4916
4917 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4918 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4919 } else {
4920 CmdArgs.push_back(FlagForCRT.data());
4921
4922 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4923 // users want. The /Za flag to cl.exe turns this off, but it's not
4924 // implemented in clang.
4925 CmdArgs.push_back("--dependent-lib=oldnames");
4926 }
4927
4928 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4929 // even if the file doesn't actually refer to any of the routines because
4930 // the CRT itself has incomplete dependency markings.
4931 if (TC.getTriple().isWindowsArm64EC())
4932 CmdArgs.push_back("--dependent-lib=softintrin");
4933}
4934
4936 const InputInfo &Output, const InputInfoList &Inputs,
4937 const ArgList &Args, const char *LinkingOutput) const {
4938 const auto &TC = getToolChain();
4939 const llvm::Triple &RawTriple = TC.getTriple();
4940 const llvm::Triple &Triple = TC.getEffectiveTriple();
4941 const std::string &TripleStr = Triple.getTriple();
4942
4943 bool KernelOrKext =
4944 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4945 const Driver &D = TC.getDriver();
4946 ArgStringList CmdArgs;
4947
4948 assert(Inputs.size() >= 1 && "Must have at least one input.");
4949 // CUDA/HIP compilation may have multiple inputs (source file + results of
4950 // device-side compilations). OpenMP device jobs also take the host IR as a
4951 // second input. Module precompilation accepts a list of header files to
4952 // include as part of the module. API extraction accepts a list of header
4953 // files whose API information is emitted in the output. All other jobs are
4954 // expected to have exactly one input.
4955 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4956 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4957 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4958 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4959 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4960 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4961 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4963 bool IsHostOffloadingAction =
4965 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4966 Args.hasFlag(options::OPT_offload_new_driver,
4967 options::OPT_no_offload_new_driver, false));
4968
4969 bool IsRDCMode =
4970 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4971
4972 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4973 bool IsUsingLTO = LTOMode != LTOK_None;
4974
4975 // Extract API doesn't have a main input file, so invent a fake one as a
4976 // placeholder.
4977 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4978 "extract-api");
4979
4980 const InputInfo &Input =
4981 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4982
4983 InputInfoList ExtractAPIInputs;
4984 InputInfoList HostOffloadingInputs;
4985 const InputInfo *CudaDeviceInput = nullptr;
4986 const InputInfo *OpenMPDeviceInput = nullptr;
4987 for (const InputInfo &I : Inputs) {
4988 if (&I == &Input || I.getType() == types::TY_Nothing) {
4989 // This is the primary input or contains nothing.
4990 } else if (IsExtractAPI) {
4991 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4992 if (I.getType() != ExpectedInputType) {
4993 D.Diag(diag::err_drv_extract_api_wrong_kind)
4994 << I.getFilename() << types::getTypeName(I.getType())
4995 << types::getTypeName(ExpectedInputType);
4996 }
4997 ExtractAPIInputs.push_back(I);
4998 } else if (IsHostOffloadingAction) {
4999 HostOffloadingInputs.push_back(I);
5000 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5001 CudaDeviceInput = &I;
5002 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5003 OpenMPDeviceInput = &I;
5004 } else {
5005 llvm_unreachable("unexpectedly given multiple inputs");
5006 }
5007 }
5008
5009 const llvm::Triple *AuxTriple =
5010 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
5011 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5012 bool IsIAMCU = RawTriple.isOSIAMCU();
5013
5014 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
5015 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5016 // Windows), we need to pass Windows-specific flags to cc1.
5017 if (IsCuda || IsHIP)
5018 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
5019
5020 // C++ is not supported for IAMCU.
5021 if (IsIAMCU && types::isCXX(Input.getType()))
5022 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5023
5024 // Invoke ourselves in -cc1 mode.
5025 //
5026 // FIXME: Implement custom jobs for internal actions.
5027 CmdArgs.push_back("-cc1");
5028
5029 // Add the "effective" target triple.
5030 CmdArgs.push_back("-triple");
5031 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5032
5033 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5034 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5035 Args.ClaimAllArgs(options::OPT_MJ);
5036 } else if (const Arg *GenCDBFragment =
5037 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5038 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5039 TripleStr, Output, Input, Args);
5040 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5041 }
5042
5043 if (IsCuda || IsHIP) {
5044 // We have to pass the triple of the host if compiling for a CUDA/HIP device
5045 // and vice-versa.
5046 std::string NormalizedTriple;
5049 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
5050 ->getTriple()
5051 .normalize();
5052 else {
5053 // Host-side compilation.
5054 NormalizedTriple =
5055 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
5056 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
5057 ->getTriple()
5058 .normalize();
5059 if (IsCuda) {
5060 // We need to figure out which CUDA version we're compiling for, as that
5061 // determines how we load and launch GPU kernels.
5062 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5063 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5064 assert(CTC && "Expected valid CUDA Toolchain.");
5065 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5066 CmdArgs.push_back(Args.MakeArgString(
5067 Twine("-target-sdk-version=") +
5068 CudaVersionToString(CTC->CudaInstallation.version())));
5069 // Unsized function arguments used for variadics were introduced in
5070 // CUDA-9.0. We still do not support generating code that actually uses
5071 // variadic arguments yet, but we do need to allow parsing them as
5072 // recent CUDA headers rely on that.
5073 // https://github.com/llvm/llvm-project/issues/58410
5074 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
5075 CmdArgs.push_back("-fcuda-allow-variadic-functions");
5076 }
5077 }
5078 CmdArgs.push_back("-aux-triple");
5079 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5080
5082 (getToolChain().getTriple().isAMDGPU() ||
5083 (getToolChain().getTriple().isSPIRV() &&
5084 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5085 // Device side compilation printf
5086 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5087 CmdArgs.push_back(Args.MakeArgString(
5088 "-mprintf-kind=" +
5089 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5090 // Force compiler error on invalid conversion specifiers
5091 CmdArgs.push_back(
5092 Args.MakeArgString("-Werror=format-invalid-specifier"));
5093 }
5094 }
5095 }
5096
5097 // Unconditionally claim the printf option now to avoid unused diagnostic.
5098 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5099 PF->claim();
5100
5101 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
5102 CmdArgs.push_back("-fsycl-is-device");
5103
5104 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
5105 A->render(Args, CmdArgs);
5106 } else {
5107 // Ensure the default version in SYCL mode is 2020.
5108 CmdArgs.push_back("-sycl-std=2020");
5109 }
5110 }
5111
5112 if (IsOpenMPDevice) {
5113 // We have to pass the triple of the host if compiling for an OpenMP device.
5114 std::string NormalizedTriple =
5115 C.getSingleOffloadToolChain<Action::OFK_Host>()
5116 ->getTriple()
5117 .normalize();
5118 CmdArgs.push_back("-aux-triple");
5119 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5120 }
5121
5122 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5123 Triple.getArch() == llvm::Triple::thumb)) {
5124 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5125 unsigned Version = 0;
5126 bool Failure =
5127 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5128 if (Failure || Version < 7)
5129 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5130 << TripleStr;
5131 }
5132
5133 // Push all default warning arguments that are specific to
5134 // the given target. These come before user provided warning options
5135 // are provided.
5136 TC.addClangWarningOptions(CmdArgs);
5137
5138 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5139 if (Triple.isSPIR() || Triple.isSPIRV())
5140 CmdArgs.push_back("-Wspir-compat");
5141
5142 // Select the appropriate action.
5143 RewriteKind rewriteKind = RK_None;
5144
5145 bool UnifiedLTO = false;
5146 if (IsUsingLTO) {
5147 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5148 options::OPT_fno_unified_lto, Triple.isPS());
5149 if (UnifiedLTO)
5150 CmdArgs.push_back("-funified-lto");
5151 }
5152
5153 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5154 // it claims when not running an assembler. Otherwise, clang would emit
5155 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5156 // flags while debugging something. That'd be somewhat inconvenient, and it's
5157 // also inconsistent with most other flags -- we don't warn on
5158 // -ffunction-sections not being used in -E mode either for example, even
5159 // though it's not really used either.
5160 if (!isa<AssembleJobAction>(JA)) {
5161 // The args claimed here should match the args used in
5162 // CollectArgsForIntegratedAssembler().
5163 if (TC.useIntegratedAs()) {
5164 Args.ClaimAllArgs(options::OPT_mrelax_all);
5165 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5166 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5167 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5168 switch (C.getDefaultToolChain().getArch()) {
5169 case llvm::Triple::arm:
5170 case llvm::Triple::armeb:
5171 case llvm::Triple::thumb:
5172 case llvm::Triple::thumbeb:
5173 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5174 break;
5175 default:
5176 break;
5177 }
5178 }
5179 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5180 Args.ClaimAllArgs(options::OPT_Xassembler);
5181 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5182 }
5183
5184 if (isa<AnalyzeJobAction>(JA)) {
5185 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5186 CmdArgs.push_back("-analyze");
5187 } else if (isa<MigrateJobAction>(JA)) {
5188 CmdArgs.push_back("-migrate");
5189 } else if (isa<PreprocessJobAction>(JA)) {
5190 if (Output.getType() == types::TY_Dependencies)
5191 CmdArgs.push_back("-Eonly");
5192 else {
5193 CmdArgs.push_back("-E");
5194 if (Args.hasArg(options::OPT_rewrite_objc) &&
5195 !Args.hasArg(options::OPT_g_Group))
5196 CmdArgs.push_back("-P");
5197 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5198 CmdArgs.push_back("-fdirectives-only");
5199 }
5200 } else if (isa<AssembleJobAction>(JA)) {
5201 CmdArgs.push_back("-emit-obj");
5202
5203 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5204
5205 // Also ignore explicit -force_cpusubtype_ALL option.
5206 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5207 } else if (isa<PrecompileJobAction>(JA)) {
5208 if (JA.getType() == types::TY_Nothing)
5209 CmdArgs.push_back("-fsyntax-only");
5210 else if (JA.getType() == types::TY_ModuleFile)
5211 CmdArgs.push_back("-emit-module-interface");
5212 else if (JA.getType() == types::TY_HeaderUnit)
5213 CmdArgs.push_back("-emit-header-unit");
5214 else
5215 CmdArgs.push_back("-emit-pch");
5216 } else if (isa<VerifyPCHJobAction>(JA)) {
5217 CmdArgs.push_back("-verify-pch");
5218 } else if (isa<ExtractAPIJobAction>(JA)) {
5219 assert(JA.getType() == types::TY_API_INFO &&
5220 "Extract API actions must generate a API information.");
5221 CmdArgs.push_back("-extract-api");
5222
5223 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5224 PrettySGFArg->render(Args, CmdArgs);
5225
5226 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5227
5228 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5229 ProductNameArg->render(Args, CmdArgs);
5230 if (Arg *ExtractAPIIgnoresFileArg =
5231 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5232 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5233 if (Arg *EmitExtensionSymbolGraphs =
5234 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5235 if (!SymbolGraphDirArg)
5236 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5237
5238 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5239 }
5240 if (SymbolGraphDirArg)
5241 SymbolGraphDirArg->render(Args, CmdArgs);
5242 } else {
5243 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5244 "Invalid action for clang tool.");
5245 if (JA.getType() == types::TY_Nothing) {
5246 CmdArgs.push_back("-fsyntax-only");
5247 } else if (JA.getType() == types::TY_LLVM_IR ||
5248 JA.getType() == types::TY_LTO_IR) {
5249 CmdArgs.push_back("-emit-llvm");
5250 } else if (JA.getType() == types::TY_LLVM_BC ||
5251 JA.getType() == types::TY_LTO_BC) {
5252 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5253 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5254 Args.hasArg(options::OPT_emit_llvm)) {
5255 CmdArgs.push_back("-emit-llvm");
5256 } else {
5257 CmdArgs.push_back("-emit-llvm-bc");
5258 }
5259 } else if (JA.getType() == types::TY_IFS ||
5260 JA.getType() == types::TY_IFS_CPP) {
5261 StringRef ArgStr =
5262 Args.hasArg(options::OPT_interface_stub_version_EQ)
5263 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5264 : "ifs-v1";
5265 CmdArgs.push_back("-emit-interface-stubs");
5266 CmdArgs.push_back(
5267 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
5268 } else if (JA.getType() == types::TY_PP_Asm) {
5269 CmdArgs.push_back("-S");
5270 } else if (JA.getType() == types::TY_AST) {
5271 CmdArgs.push_back("-emit-pch");
5272 } else if (JA.getType() == types::TY_ModuleFile) {
5273 CmdArgs.push_back("-module-file-info");
5274 } else if (JA.getType() == types::TY_RewrittenObjC) {
5275 CmdArgs.push_back("-rewrite-objc");
5276 rewriteKind = RK_NonFragile;
5277 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5278 CmdArgs.push_back("-rewrite-objc");
5279 rewriteKind = RK_Fragile;
5280 } else {
5281 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5282 }
5283
5284 // Preserve use-list order by default when emitting bitcode, so that
5285 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5286 // same result as running passes here. For LTO, we don't need to preserve
5287 // the use-list order, since serialization to bitcode is part of the flow.
5288 if (JA.getType() == types::TY_LLVM_BC)
5289 CmdArgs.push_back("-emit-llvm-uselists");
5290
5291 if (IsUsingLTO) {
5292 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5293 !Args.hasFlag(options::OPT_offload_new_driver,
5294 options::OPT_no_offload_new_driver, false) &&
5295 !Triple.isAMDGPU()) {
5296 D.Diag(diag::err_drv_unsupported_opt_for_target)
5297 << Args.getLastArg(options::OPT_foffload_lto,
5298 options::OPT_foffload_lto_EQ)
5299 ->getAsString(Args)
5300 << Triple.getTriple();
5301 } else if (Triple.isNVPTX() && !IsRDCMode &&
5303 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5304 << Args.getLastArg(options::OPT_foffload_lto,
5305 options::OPT_foffload_lto_EQ)
5306 ->getAsString(Args)
5307 << "-fno-gpu-rdc";
5308 } else {
5309 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5310 CmdArgs.push_back(Args.MakeArgString(
5311 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5312 // PS4 uses the legacy LTO API, which does not support some of the
5313 // features enabled by -flto-unit.
5314 if (!RawTriple.isPS4() ||
5315 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5316 CmdArgs.push_back("-flto-unit");
5317 }
5318 }
5319 }
5320
5321 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5322
5323 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5324 if (!types::isLLVMIR(Input.getType()))
5325 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5326 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5327 }
5328
5329 if (Triple.isPPC())
5330 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5331 options::OPT_mno_regnames);
5332
5333 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5334 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5335
5336 if (Args.getLastArg(options::OPT_save_temps_EQ))
5337 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5338
5339 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5340 options::OPT_fmemory_profile_EQ,
5341 options::OPT_fno_memory_profile);
5342 if (MemProfArg &&
5343 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5344 MemProfArg->render(Args, CmdArgs);
5345
5346 if (auto *MemProfUseArg =
5347 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5348 if (MemProfArg)
5349 D.Diag(diag::err_drv_argument_not_allowed_with)
5350 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5351 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5352 options::OPT_fprofile_generate_EQ))
5353 D.Diag(diag::err_drv_argument_not_allowed_with)
5354 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5355 MemProfUseArg->render(Args, CmdArgs);
5356 }
5357
5358 // Embed-bitcode option.
5359 // Only white-listed flags below are allowed to be embedded.
5360 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5361 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5362 // Add flags implied by -fembed-bitcode.
5363 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5364 // Disable all llvm IR level optimizations.
5365 CmdArgs.push_back("-disable-llvm-passes");
5366
5367 // Render target options.
5368 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5369
5370 // reject options that shouldn't be supported in bitcode
5371 // also reject kernel/kext
5372 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5373 options::OPT_mkernel,
5374 options::OPT_fapple_kext,
5375 options::OPT_ffunction_sections,
5376 options::OPT_fno_function_sections,
5377 options::OPT_fdata_sections,
5378 options::OPT_fno_data_sections,
5379 options::OPT_fbasic_block_sections_EQ,
5380 options::OPT_funique_internal_linkage_names,
5381 options::OPT_fno_unique_internal_linkage_names,
5382 options::OPT_funique_section_names,
5383 options::OPT_fno_unique_section_names,
5384 options::OPT_funique_basic_block_section_names,
5385 options::OPT_fno_unique_basic_block_section_names,
5386 options::OPT_mrestrict_it,
5387 options::OPT_mno_restrict_it,
5388 options::OPT_mstackrealign,
5389 options::OPT_mno_stackrealign,
5390 options::OPT_mstack_alignment,
5391 options::OPT_mcmodel_EQ,
5392 options::OPT_mlong_calls,
5393 options::OPT_mno_long_calls,
5394 options::OPT_ggnu_pubnames,
5395 options::OPT_gdwarf_aranges,
5396 options::OPT_fdebug_types_section,
5397 options::OPT_fno_debug_types_section,
5398 options::OPT_fdwarf_directory_asm,
5399 options::OPT_fno_dwarf_directory_asm,
5400 options::OPT_mrelax_all,
5401 options::OPT_mno_relax_all,
5402 options::OPT_ftrap_function_EQ,
5403 options::OPT_ffixed_r9,
5404 options::OPT_mfix_cortex_a53_835769,
5405 options::OPT_mno_fix_cortex_a53_835769,
5406 options::OPT_ffixed_x18,
5407 options::OPT_mglobal_merge,
5408 options::OPT_mno_global_merge,
5409 options::OPT_mred_zone,
5410 options::OPT_mno_red_zone,
5411 options::OPT_Wa_COMMA,
5412 options::OPT_Xassembler,
5413 options::OPT_mllvm,
5414 };
5415 for (const auto &A : Args)
5416 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5417 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5418
5419 // Render the CodeGen options that need to be passed.
5420 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5421 options::OPT_fno_optimize_sibling_calls);
5422
5424 CmdArgs, JA);
5425
5426 // Render ABI arguments
5427 switch (TC.getArch()) {
5428 default: break;
5429 case llvm::Triple::arm:
5430 case llvm::Triple::armeb:
5431 case llvm::Triple::thumbeb:
5432 RenderARMABI(D, Triple, Args, CmdArgs);
5433 break;
5434 case llvm::Triple::aarch64:
5435 case llvm::Triple::aarch64_32:
5436 case llvm::Triple::aarch64_be:
5437 RenderAArch64ABI(Triple, Args, CmdArgs);
5438 break;
5439 }
5440
5441 // Optimization level for CodeGen.
5442 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5443 if (A->getOption().matches(options::OPT_O4)) {
5444 CmdArgs.push_back("-O3");
5445 D.Diag(diag::warn_O4_is_O3);
5446 } else {
5447 A->render(Args, CmdArgs);
5448 }
5449 }
5450
5451 // Input/Output file.
5452 if (Output.getType() == types::TY_Dependencies) {
5453 // Handled with other dependency code.
5454 } else if (Output.isFilename()) {
5455 CmdArgs.push_back("-o");
5456 CmdArgs.push_back(Output.getFilename());
5457 } else {
5458 assert(Output.isNothing() && "Input output.");
5459 }
5460
5461 for (const auto &II : Inputs) {
5462 addDashXForInput(Args, II, CmdArgs);
5463 if (II.isFilename())
5464 CmdArgs.push_back(II.getFilename());
5465 else
5466 II.getInputArg().renderAsInput(Args, CmdArgs);
5467 }
5468
5469 C.addCommand(std::make_unique<Command>(
5470 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5471 CmdArgs, Inputs, Output, D.getPrependArg()));
5472 return;
5473 }
5474
5475 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5476 CmdArgs.push_back("-fembed-bitcode=marker");
5477
5478 // We normally speed up the clang process a bit by skipping destructors at
5479 // exit, but when we're generating diagnostics we can rely on some of the
5480 // cleanup.
5481 if (!C.isForDiagnostics())
5482 CmdArgs.push_back("-disable-free");
5483 CmdArgs.push_back("-clear-ast-before-backend");
5484
5485#ifdef NDEBUG
5486 const bool IsAssertBuild = false;
5487#else
5488 const bool IsAssertBuild = true;
5489#endif
5490
5491 // Disable the verification pass in asserts builds unless otherwise specified.
5492 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5493 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5494 CmdArgs.push_back("-disable-llvm-verifier");
5495 }
5496
5497 // Discard value names in assert builds unless otherwise specified.
5498 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5499 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5500 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5501 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5502 return types::isLLVMIR(II.getType());
5503 })) {
5504 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5505 }
5506 CmdArgs.push_back("-discard-value-names");
5507 }
5508
5509 // Set the main file name, so that debug info works even with
5510 // -save-temps.
5511 CmdArgs.push_back("-main-file-name");
5512 CmdArgs.push_back(getBaseInputName(Args, Input));
5513
5514 // Some flags which affect the language (via preprocessor
5515 // defines).
5516 if (Args.hasArg(options::OPT_static))
5517 CmdArgs.push_back("-static-define");
5518
5519 if (Args.hasArg(options::OPT_municode))
5520 CmdArgs.push_back("-DUNICODE");
5521
5522 if (isa<AnalyzeJobAction>(JA))
5523 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5524
5525 if (isa<AnalyzeJobAction>(JA) ||
5526 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5527 CmdArgs.push_back("-setup-static-analyzer");
5528
5529 // Enable compatilibily mode to avoid analyzer-config related errors.
5530 // Since we can't access frontend flags through hasArg, let's manually iterate
5531 // through them.
5532 bool FoundAnalyzerConfig = false;
5533 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5534 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5535 FoundAnalyzerConfig = true;
5536 break;
5537 }
5538 if (!FoundAnalyzerConfig)
5539 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5540 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5541 FoundAnalyzerConfig = true;
5542 break;
5543 }
5544 if (FoundAnalyzerConfig)
5545 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5546
5548
5549 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5550 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5551 if (FunctionAlignment) {
5552 CmdArgs.push_back("-function-alignment");
5553 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5554 }
5555
5556 // We support -falign-loops=N where N is a power of 2. GCC supports more
5557 // forms.
5558 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5559 unsigned Value = 0;
5560 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5561 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5562 << A->getAsString(Args) << A->getValue();
5563 else if (Value & (Value - 1))
5564 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5565 << A->getAsString(Args) << A->getValue();
5566 // Treat =0 as unspecified (use the target preference).
5567 if (Value)
5568 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5569 Twine(std::min(Value, 65536u))));
5570 }
5571
5572 if (Triple.isOSzOS()) {
5573 // On z/OS some of the system header feature macros need to
5574 // be defined to enable most cross platform projects to build
5575 // successfully. Ths include the libc++ library. A
5576 // complicating factor is that users can define these
5577 // macros to the same or different values. We need to add
5578 // the definition for these macros to the compilation command
5579 // if the user hasn't already defined them.
5580
5581 auto findMacroDefinition = [&](const std::string &Macro) {
5582 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5583 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5584 return M == Macro || M.find(Macro + '=') != std::string::npos;
5585 });
5586 };
5587
5588 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5589 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5590 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5591 // _OPEN_DEFAULT is required for XL compat
5592 if (!findMacroDefinition("_OPEN_DEFAULT"))
5593 CmdArgs.push_back("-D_OPEN_DEFAULT");
5594 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5595 // _XOPEN_SOURCE=600 is required for libcxx.
5596 if (!findMacroDefinition("_XOPEN_SOURCE"))
5597 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5598 }
5599 }
5600
5601 llvm::Reloc::Model RelocationModel;
5602 unsigned PICLevel;
5603 bool IsPIE;
5604 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5605 Arg *LastPICDataRelArg =
5606 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5607 options::OPT_mpic_data_is_text_relative);
5608 bool NoPICDataIsTextRelative = false;
5609 if (LastPICDataRelArg) {
5610 if (LastPICDataRelArg->getOption().matches(
5611 options::OPT_mno_pic_data_is_text_relative)) {
5612 NoPICDataIsTextRelative = true;
5613 if (!PICLevel)
5614 D.Diag(diag::err_drv_argument_only_allowed_with)
5615 << "-mno-pic-data-is-text-relative"
5616 << "-fpic/-fpie";
5617 }
5618 if (!Triple.isSystemZ())
5619 D.Diag(diag::err_drv_unsupported_opt_for_target)
5620 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5621 : "-mpic-data-is-text-relative")
5622 << RawTriple.str();
5623 }
5624
5625 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5626 RelocationModel == llvm::Reloc::ROPI_RWPI;
5627 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5628 RelocationModel == llvm::Reloc::ROPI_RWPI;
5629
5630 if (Args.hasArg(options::OPT_mcmse) &&
5631 !Args.hasArg(options::OPT_fallow_unsupported)) {
5632 if (IsROPI)
5633 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5634 if (IsRWPI)
5635 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5636 }
5637
5638 if (IsROPI && types::isCXX(Input.getType()) &&
5639 !Args.hasArg(options::OPT_fallow_unsupported))
5640 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5641
5642 const char *RMName = RelocationModelName(RelocationModel);
5643 if (RMName) {
5644 CmdArgs.push_back("-mrelocation-model");
5645 CmdArgs.push_back(RMName);
5646 }
5647 if (PICLevel > 0) {
5648 CmdArgs.push_back("-pic-level");
5649 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5650 if (IsPIE)
5651 CmdArgs.push_back("-pic-is-pie");
5652 if (NoPICDataIsTextRelative)
5653 CmdArgs.push_back("-mcmodel=medium");
5654 }
5655
5656 if (RelocationModel == llvm::Reloc::ROPI ||
5657 RelocationModel == llvm::Reloc::ROPI_RWPI)
5658 CmdArgs.push_back("-fropi");
5659 if (RelocationModel == llvm::Reloc::RWPI ||
5660 RelocationModel == llvm::Reloc::ROPI_RWPI)
5661 CmdArgs.push_back("-frwpi");
5662
5663 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5664 CmdArgs.push_back("-meabi");
5665 CmdArgs.push_back(A->getValue());
5666 }
5667
5668 // -fsemantic-interposition is forwarded to CC1: set the
5669 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5670 // make default visibility external linkage definitions dso_preemptable.
5671 //
5672 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5673 // aliases (make default visibility external linkage definitions dso_local).
5674 // This is the CC1 default for ELF to match COFF/Mach-O.
5675 //
5676 // Otherwise use Clang's traditional behavior: like
5677 // -fno-semantic-interposition but local aliases are not used. So references
5678 // can be interposed if not optimized out.
5679 if (Triple.isOSBinFormatELF()) {
5680 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5681 options::OPT_fno_semantic_interposition);
5682 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5683 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5684 bool SupportsLocalAlias =
5685 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5686 if (!A)
5687 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5688 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5689 A->render(Args, CmdArgs);
5690 else if (!SupportsLocalAlias)
5691 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5692 }
5693 }
5694
5695 {
5696 std::string Model;
5697 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5698 if (!TC.isThreadModelSupported(A->getValue()))
5699 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5700 << A->getValue() << A->getAsString(Args);
5701 Model = A->getValue();
5702 } else
5703 Model = TC.getThreadModel();
5704 if (Model != "posix") {
5705 CmdArgs.push_back("-mthread-model");
5706 CmdArgs.push_back(Args.MakeArgString(Model));
5707 }
5708 }
5709
5710 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5711 StringRef Name = A->getValue();
5712 if (Name == "SVML") {
5713 if (Triple.getArch() != llvm::Triple::x86 &&
5714 Triple.getArch() != llvm::Triple::x86_64)
5715 D.Diag(diag::err_drv_unsupported_opt_for_target)
5716 << Name << Triple.getArchName();
5717 } else if (Name == "LIBMVEC-X86") {
5718 if (Triple.getArch() != llvm::Triple::x86 &&
5719 Triple.getArch() != llvm::Triple::x86_64)
5720 D.Diag(diag::err_drv_unsupported_opt_for_target)
5721 << Name << Triple.getArchName();
5722 } else if (Name == "SLEEF" || Name == "ArmPL") {
5723 if (Triple.getArch() != llvm::Triple::aarch64 &&
5724 Triple.getArch() != llvm::Triple::aarch64_be)
5725 D.Diag(diag::err_drv_unsupported_opt_for_target)
5726 << Name << Triple.getArchName();
5727 }
5728 A->render(Args, CmdArgs);
5729 }
5730
5731 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5732 options::OPT_fno_merge_all_constants, false))
5733 CmdArgs.push_back("-fmerge-all-constants");
5734
5735 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5736 options::OPT_fno_delete_null_pointer_checks);
5737
5738 // LLVM Code Generator Options.
5739
5740 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5741 if (!Triple.isOSAIX() || Triple.isPPC32())
5742 D.Diag(diag::err_drv_unsupported_opt_for_target)
5743 << A->getSpelling() << RawTriple.str();
5744 CmdArgs.push_back("-mabi=quadword-atomics");
5745 }
5746
5747 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5748 // Emit the unsupported option error until the Clang's library integration
5749 // support for 128-bit long double is available for AIX.
5750 if (Triple.isOSAIX())
5751 D.Diag(diag::err_drv_unsupported_opt_for_target)
5752 << A->getSpelling() << RawTriple.str();
5753 }
5754
5755 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5756 StringRef V = A->getValue(), V1 = V;
5757 unsigned Size;
5758 if (V1.consumeInteger(10, Size) || !V1.empty())
5759 D.Diag(diag::err_drv_invalid_argument_to_option)
5760 << V << A->getOption().getName();
5761 else
5762 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5763 }
5764
5765 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5766 options::OPT_fno_jump_tables);
5767 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5768 options::OPT_fno_profile_sample_accurate);
5769 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5770 options::OPT_fno_preserve_as_comments);
5771
5772 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5773 CmdArgs.push_back("-mregparm");
5774 CmdArgs.push_back(A->getValue());
5775 }
5776
5777 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5778 options::OPT_msvr4_struct_return)) {
5779 if (!TC.getTriple().isPPC32()) {
5780 D.Diag(diag::err_drv_unsupported_opt_for_target)
5781 << A->getSpelling() << RawTriple.str();
5782 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5783 CmdArgs.push_back("-maix-struct-return");
5784 } else {
5785 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5786 CmdArgs.push_back("-msvr4-struct-return");
5787 }
5788 }
5789
5790 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5791 options::OPT_freg_struct_return)) {
5792 if (TC.getArch() != llvm::Triple::x86) {
5793 D.Diag(diag::err_drv_unsupported_opt_for_target)
5794 << A->getSpelling() << RawTriple.str();
5795 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5796 CmdArgs.push_back("-fpcc-struct-return");
5797 } else {
5798 assert(A->getOption().matches(options::OPT_freg_struct_return));
5799 CmdArgs.push_back("-freg-struct-return");
5800 }
5801 }
5802
5803 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5804 if (Triple.getArch() == llvm::Triple::m68k)
5805 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5806 else
5807 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5808 }
5809
5810 if (Args.hasArg(options::OPT_fenable_matrix)) {
5811 // enable-matrix is needed by both the LangOpts and by LLVM.
5812 CmdArgs.push_back("-fenable-matrix");
5813 CmdArgs.push_back("-mllvm");
5814 CmdArgs.push_back("-enable-matrix");
5815 }
5816
5818 getFramePointerKind(Args, RawTriple);
5819 const char *FPKeepKindStr = nullptr;
5820 switch (FPKeepKind) {
5822 FPKeepKindStr = "-mframe-pointer=none";
5823 break;
5825 FPKeepKindStr = "-mframe-pointer=reserved";
5826 break;
5828 FPK