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