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