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