blob: a95080bbec6777411b6bbc88fd69747fb66e0eaa [file] [log] [blame]
David L. Jonesf561aba2017-03-08 01:02:16 +00001//===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Clang.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000015#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000019#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000020#include "CommonArgs.h"
21#include "Hexagon.h"
22#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000028#include "clang/Driver/DriverDiagnostic.h"
29#include "clang/Driver/Options.h"
30#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000031#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000033#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/Option/ArgList.h"
35#include "llvm/Support/CodeGen.h"
36#include "llvm/Support/Compression.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000040#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000041#include "llvm/Support/YAMLParser.h"
42
43#ifdef LLVM_ON_UNIX
44#include <unistd.h> // For getuid().
45#endif
46
47using namespace clang::driver;
48using namespace clang::driver::tools;
49using namespace clang;
50using namespace llvm::opt;
51
52static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
53 if (Arg *A =
54 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
55 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
56 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
57 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
58 << A->getBaseArg().getAsString(Args)
59 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
60 }
61 }
62}
63
64static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
65 // In gcc, only ARM checks this, but it seems reasonable to check universally.
66 if (Args.hasArg(options::OPT_static))
67 if (const Arg *A =
68 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
69 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
70 << "-static";
71}
72
73// Add backslashes to escape spaces and other backslashes.
74// This is used for the space-separated argument list specified with
75// the -dwarf-debug-flags option.
76static void EscapeSpacesAndBackslashes(const char *Arg,
77 SmallVectorImpl<char> &Res) {
78 for (; *Arg; ++Arg) {
79 switch (*Arg) {
80 default:
81 break;
82 case ' ':
83 case '\\':
84 Res.push_back('\\');
85 break;
86 }
87 Res.push_back(*Arg);
88 }
89}
90
91// Quote target names for inclusion in GNU Make dependency files.
92// Only the characters '$', '#', ' ', '\t' are quoted.
93static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
94 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
95 switch (Target[i]) {
96 case ' ':
97 case '\t':
98 // Escape the preceding backslashes
99 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
100 Res.push_back('\\');
101
102 // Escape the space/tab
103 Res.push_back('\\');
104 break;
105 case '$':
106 Res.push_back('$');
107 break;
108 case '#':
109 Res.push_back('\\');
110 break;
111 default:
112 break;
113 }
114
115 Res.push_back(Target[i]);
116 }
117}
118
119/// Apply \a Work on the current tool chain \a RegularToolChain and any other
120/// offloading tool chain that is associated with the current action \a JA.
121static void
122forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
123 const ToolChain &RegularToolChain,
124 llvm::function_ref<void(const ToolChain &)> Work) {
125 // Apply Work on the current/regular tool chain.
126 Work(RegularToolChain);
127
128 // Apply Work on all the offloading tool chains associated with the current
129 // action.
130 if (JA.isHostOffloading(Action::OFK_Cuda))
131 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
132 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000134 else if (JA.isHostOffloading(Action::OFK_HIP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
136 else if (JA.isDeviceOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000138
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000139 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
140 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
141 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
142 Work(*II->second);
143 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
144 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
145
David L. Jonesf561aba2017-03-08 01:02:16 +0000146 //
147 // TODO: Add support for other offloading programming models here.
148 //
149}
150
151/// This is a helper function for validating the optional refinement step
152/// parameter in reciprocal argument strings. Return false if there is an error
153/// parsing the refinement step. Otherwise, return true and set the Position
154/// of the refinement step in the input string.
155static bool getRefinementStep(StringRef In, const Driver &D,
156 const Arg &A, size_t &Position) {
157 const char RefinementStepToken = ':';
158 Position = In.find(RefinementStepToken);
159 if (Position != StringRef::npos) {
160 StringRef Option = A.getOption().getName();
161 StringRef RefStep = In.substr(Position + 1);
162 // Allow exactly one numeric character for the additional refinement
163 // step parameter. This is reasonable for all currently-supported
164 // operations and architectures because we would expect that a larger value
165 // of refinement steps would cause the estimate "optimization" to
166 // under-perform the native operation. Also, if the estimate does not
167 // converge quickly, it probably will not ever converge, so further
168 // refinement steps will not produce a better answer.
169 if (RefStep.size() != 1) {
170 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
171 return false;
172 }
173 char RefStepChar = RefStep[0];
174 if (RefStepChar < '0' || RefStepChar > '9') {
175 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
176 return false;
177 }
178 }
179 return true;
180}
181
182/// The -mrecip flag requires processing of many optional parameters.
183static void ParseMRecip(const Driver &D, const ArgList &Args,
184 ArgStringList &OutStrings) {
185 StringRef DisabledPrefixIn = "!";
186 StringRef DisabledPrefixOut = "!";
187 StringRef EnabledPrefixOut = "";
188 StringRef Out = "-mrecip=";
189
190 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
191 if (!A)
192 return;
193
194 unsigned NumOptions = A->getNumValues();
195 if (NumOptions == 0) {
196 // No option is the same as "all".
197 OutStrings.push_back(Args.MakeArgString(Out + "all"));
198 return;
199 }
200
201 // Pass through "all", "none", or "default" with an optional refinement step.
202 if (NumOptions == 1) {
203 StringRef Val = A->getValue(0);
204 size_t RefStepLoc;
205 if (!getRefinementStep(Val, D, *A, RefStepLoc))
206 return;
207 StringRef ValBase = Val.slice(0, RefStepLoc);
208 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
209 OutStrings.push_back(Args.MakeArgString(Out + Val));
210 return;
211 }
212 }
213
214 // Each reciprocal type may be enabled or disabled individually.
215 // Check each input value for validity, concatenate them all back together,
216 // and pass through.
217
218 llvm::StringMap<bool> OptionStrings;
219 OptionStrings.insert(std::make_pair("divd", false));
220 OptionStrings.insert(std::make_pair("divf", false));
221 OptionStrings.insert(std::make_pair("vec-divd", false));
222 OptionStrings.insert(std::make_pair("vec-divf", false));
223 OptionStrings.insert(std::make_pair("sqrtd", false));
224 OptionStrings.insert(std::make_pair("sqrtf", false));
225 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
227
228 for (unsigned i = 0; i != NumOptions; ++i) {
229 StringRef Val = A->getValue(i);
230
231 bool IsDisabled = Val.startswith(DisabledPrefixIn);
232 // Ignore the disablement token for string matching.
233 if (IsDisabled)
234 Val = Val.substr(1);
235
236 size_t RefStep;
237 if (!getRefinementStep(Val, D, *A, RefStep))
238 return;
239
240 StringRef ValBase = Val.slice(0, RefStep);
241 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
242 if (OptionIter == OptionStrings.end()) {
243 // Try again specifying float suffix.
244 OptionIter = OptionStrings.find(ValBase.str() + 'f');
245 if (OptionIter == OptionStrings.end()) {
246 // The input name did not match any known option string.
247 D.Diag(diag::err_drv_unknown_argument) << Val;
248 return;
249 }
250 // The option was specified without a float or double suffix.
251 // Make sure that the double entry was not already specified.
252 // The float entry will be checked below.
253 if (OptionStrings[ValBase.str() + 'd']) {
254 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
255 return;
256 }
257 }
258
259 if (OptionIter->second == true) {
260 // Duplicate option specified.
261 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
262 return;
263 }
264
265 // Mark the matched option as found. Do not allow duplicate specifiers.
266 OptionIter->second = true;
267
268 // If the precision was not specified, also mark the double entry as found.
269 if (ValBase.back() != 'f' && ValBase.back() != 'd')
270 OptionStrings[ValBase.str() + 'd'] = true;
271
272 // Build the output string.
273 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
274 Out = Args.MakeArgString(Out + Prefix + Val);
275 if (i != NumOptions - 1)
276 Out = Args.MakeArgString(Out + ",");
277 }
278
279 OutStrings.push_back(Args.MakeArgString(Out));
280}
281
Craig Topper9a724aa2017-12-11 21:09:19 +0000282/// The -mprefer-vector-width option accepts either a positive integer
283/// or the string "none".
284static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
285 ArgStringList &CmdArgs) {
286 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
287 if (!A)
288 return;
289
290 StringRef Value = A->getValue();
291 if (Value == "none") {
292 CmdArgs.push_back("-mprefer-vector-width=none");
293 } else {
294 unsigned Width;
295 if (Value.getAsInteger(10, Width)) {
296 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
297 return;
298 }
299 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
300 }
301}
302
David L. Jonesf561aba2017-03-08 01:02:16 +0000303static void getWebAssemblyTargetFeatures(const ArgList &Args,
304 std::vector<StringRef> &Features) {
305 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
306}
307
David L. Jonesf561aba2017-03-08 01:02:16 +0000308static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
309 const ArgList &Args, ArgStringList &CmdArgs,
310 bool ForAS) {
311 const Driver &D = TC.getDriver();
312 std::vector<StringRef> Features;
313 switch (Triple.getArch()) {
314 default:
315 break;
316 case llvm::Triple::mips:
317 case llvm::Triple::mipsel:
318 case llvm::Triple::mips64:
319 case llvm::Triple::mips64el:
320 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
321 break;
322
323 case llvm::Triple::arm:
324 case llvm::Triple::armeb:
325 case llvm::Triple::thumb:
326 case llvm::Triple::thumbeb:
327 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
328 break;
329
330 case llvm::Triple::ppc:
331 case llvm::Triple::ppc64:
332 case llvm::Triple::ppc64le:
333 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
334 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000335 case llvm::Triple::riscv32:
336 case llvm::Triple::riscv64:
337 riscv::getRISCVTargetFeatures(D, Args, Features);
338 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000339 case llvm::Triple::systemz:
340 systemz::getSystemZTargetFeatures(Args, Features);
341 break;
342 case llvm::Triple::aarch64:
343 case llvm::Triple::aarch64_be:
344 aarch64::getAArch64TargetFeatures(D, Args, Features);
345 break;
346 case llvm::Triple::x86:
347 case llvm::Triple::x86_64:
348 x86::getX86TargetFeatures(D, Triple, Args, Features);
349 break;
350 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000351 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000352 break;
353 case llvm::Triple::wasm32:
354 case llvm::Triple::wasm64:
355 getWebAssemblyTargetFeatures(Args, Features);
356 break;
357 case llvm::Triple::sparc:
358 case llvm::Triple::sparcel:
359 case llvm::Triple::sparcv9:
360 sparc::getSparcTargetFeatures(D, Args, Features);
361 break;
362 case llvm::Triple::r600:
363 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000364 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000365 break;
366 }
367
368 // Find the last of each feature.
369 llvm::StringMap<unsigned> LastOpt;
370 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
371 StringRef Name = Features[I];
372 assert(Name[0] == '-' || Name[0] == '+');
373 LastOpt[Name.drop_front(1)] = I;
374 }
375
376 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
377 // If this feature was overridden, ignore it.
378 StringRef Name = Features[I];
379 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
380 assert(LastI != LastOpt.end());
381 unsigned Last = LastI->second;
382 if (Last != I)
383 continue;
384
385 CmdArgs.push_back("-target-feature");
386 CmdArgs.push_back(Name.data());
387 }
388}
389
390static bool
391shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
392 const llvm::Triple &Triple) {
393 // We use the zero-cost exception tables for Objective-C if the non-fragile
394 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
395 // later.
396 if (runtime.isNonFragile())
397 return true;
398
399 if (!Triple.isMacOSX())
400 return false;
401
402 return (!Triple.isMacOSXVersionLT(10, 5) &&
403 (Triple.getArch() == llvm::Triple::x86_64 ||
404 Triple.getArch() == llvm::Triple::arm));
405}
406
407/// Adds exception related arguments to the driver command arguments. There's a
408/// master flag, -fexceptions and also language specific flags to enable/disable
409/// C++ and Objective-C exceptions. This makes it possible to for example
410/// disable C++ exceptions but enable Objective-C exceptions.
411static void addExceptionArgs(const ArgList &Args, types::ID InputType,
412 const ToolChain &TC, bool KernelOrKext,
413 const ObjCRuntime &objcRuntime,
414 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000415 const llvm::Triple &Triple = TC.getTriple();
416
417 if (KernelOrKext) {
418 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
419 // arguments now to avoid warnings about unused arguments.
420 Args.ClaimAllArgs(options::OPT_fexceptions);
421 Args.ClaimAllArgs(options::OPT_fno_exceptions);
422 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
423 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
424 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
425 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
426 return;
427 }
428
429 // See if the user explicitly enabled exceptions.
430 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
431 false);
432
433 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
434 // is not necessarily sensible, but follows GCC.
435 if (types::isObjC(InputType) &&
436 Args.hasFlag(options::OPT_fobjc_exceptions,
437 options::OPT_fno_objc_exceptions, true)) {
438 CmdArgs.push_back("-fobjc-exceptions");
439
440 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
441 }
442
443 if (types::isCXX(InputType)) {
444 // Disable C++ EH by default on XCore and PS4.
445 bool CXXExceptionsEnabled =
446 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
447 Arg *ExceptionArg = Args.getLastArg(
448 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
449 options::OPT_fexceptions, options::OPT_fno_exceptions);
450 if (ExceptionArg)
451 CXXExceptionsEnabled =
452 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
453 ExceptionArg->getOption().matches(options::OPT_fexceptions);
454
455 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000456 CmdArgs.push_back("-fcxx-exceptions");
457
458 EH = true;
459 }
460 }
461
462 if (EH)
463 CmdArgs.push_back("-fexceptions");
464}
465
466static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
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 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
474 Default);
475}
476
477static bool ShouldDisableDwarfDirectory(const ArgList &Args,
478 const ToolChain &TC) {
479 bool UseDwarfDirectory =
480 Args.hasFlag(options::OPT_fdwarf_directory_asm,
481 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
482 return !UseDwarfDirectory;
483}
484
485// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
486// to the corresponding DebugInfoKind.
487static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
488 assert(A.getOption().matches(options::OPT_gN_Group) &&
489 "Not a -g option that specifies a debug-info level");
490 if (A.getOption().matches(options::OPT_g0) ||
491 A.getOption().matches(options::OPT_ggdb0))
492 return codegenoptions::NoDebugInfo;
493 if (A.getOption().matches(options::OPT_gline_tables_only) ||
494 A.getOption().matches(options::OPT_ggdb1))
495 return codegenoptions::DebugLineTablesOnly;
496 return codegenoptions::LimitedDebugInfo;
497}
498
499static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
500 switch (Triple.getArch()){
501 default:
502 return false;
503 case llvm::Triple::arm:
504 case llvm::Triple::thumb:
505 // ARM Darwin targets require a frame pointer to be always present to aid
506 // offline debugging via backtraces.
507 return Triple.isOSDarwin();
508 }
509}
510
511static bool useFramePointerForTargetByDefault(const ArgList &Args,
512 const llvm::Triple &Triple) {
513 switch (Triple.getArch()) {
514 case llvm::Triple::xcore:
515 case llvm::Triple::wasm32:
516 case llvm::Triple::wasm64:
517 // XCore never wants frame pointers, regardless of OS.
518 // WebAssembly never wants frame pointers.
519 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000520 case llvm::Triple::riscv32:
521 case llvm::Triple::riscv64:
522 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000523 default:
524 break;
525 }
526
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000527 if (Triple.getOS() == llvm::Triple::NetBSD) {
528 return !areOptimizationsEnabled(Args);
529 }
530
David L. Jonesf561aba2017-03-08 01:02:16 +0000531 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
532 switch (Triple.getArch()) {
533 // Don't use a frame pointer on linux if optimizing for certain targets.
534 case llvm::Triple::mips64:
535 case llvm::Triple::mips64el:
536 case llvm::Triple::mips:
537 case llvm::Triple::mipsel:
538 case llvm::Triple::ppc:
539 case llvm::Triple::ppc64:
540 case llvm::Triple::ppc64le:
541 case llvm::Triple::systemz:
542 case llvm::Triple::x86:
543 case llvm::Triple::x86_64:
544 return !areOptimizationsEnabled(Args);
545 default:
546 return true;
547 }
548 }
549
550 if (Triple.isOSWindows()) {
551 switch (Triple.getArch()) {
552 case llvm::Triple::x86:
553 return !areOptimizationsEnabled(Args);
554 case llvm::Triple::x86_64:
555 return Triple.isOSBinFormatMachO();
556 case llvm::Triple::arm:
557 case llvm::Triple::thumb:
558 // Windows on ARM builds with FPO disabled to aid fast stack walking
559 return true;
560 default:
561 // All other supported Windows ISAs use xdata unwind information, so frame
562 // pointers are not generally useful.
563 return false;
564 }
565 }
566
567 return true;
568}
569
570static bool shouldUseFramePointer(const ArgList &Args,
571 const llvm::Triple &Triple) {
572 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
573 options::OPT_fomit_frame_pointer))
574 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
575 mustUseNonLeafFramePointerForTarget(Triple);
576
577 if (Args.hasArg(options::OPT_pg))
578 return true;
579
580 return useFramePointerForTargetByDefault(Args, Triple);
581}
582
583static bool shouldUseLeafFramePointer(const ArgList &Args,
584 const llvm::Triple &Triple) {
585 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
586 options::OPT_momit_leaf_frame_pointer))
587 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
588
589 if (Args.hasArg(options::OPT_pg))
590 return true;
591
592 if (Triple.isPS4CPU())
593 return false;
594
595 return useFramePointerForTargetByDefault(Args, Triple);
596}
597
598/// Add a CC1 option to specify the debug compilation directory.
599static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
600 SmallString<128> cwd;
601 if (!llvm::sys::fs::current_path(cwd)) {
602 CmdArgs.push_back("-fdebug-compilation-dir");
603 CmdArgs.push_back(Args.MakeArgString(cwd));
604 }
605}
606
Paul Robinson9b292b42018-07-10 15:15:24 +0000607/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
608static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
609 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
610 StringRef Map = A->getValue();
611 if (Map.find('=') == StringRef::npos)
612 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
613 else
614 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
615 A->claim();
616 }
617}
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000620/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
621static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
622 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
623 if (A->getOption().matches(options::OPT_O4) ||
624 A->getOption().matches(options::OPT_Ofast))
625 return true;
626
627 if (A->getOption().matches(options::OPT_O0))
628 return false;
629
630 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
631
632 // Vectorize -Os.
633 StringRef S(A->getValue());
634 if (S == "s")
635 return true;
636
637 // Don't vectorize -Oz, unless it's the slp vectorizer.
638 if (S == "z")
639 return isSlpVec;
640
641 unsigned OptLevel = 0;
642 if (S.getAsInteger(10, OptLevel))
643 return false;
644
645 return OptLevel > 1;
646 }
647
648 return false;
649}
650
651/// Add -x lang to \p CmdArgs for \p Input.
652static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
653 ArgStringList &CmdArgs) {
654 // When using -verify-pch, we don't want to provide the type
655 // 'precompiled-header' if it was inferred from the file extension
656 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
657 return;
658
659 CmdArgs.push_back("-x");
660 if (Args.hasArg(options::OPT_rewrite_objc))
661 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000662 else {
663 // Map the driver type to the frontend type. This is mostly an identity
664 // mapping, except that the distinction between module interface units
665 // and other source files does not exist at the frontend layer.
666 const char *ClangType;
667 switch (Input.getType()) {
668 case types::TY_CXXModule:
669 ClangType = "c++";
670 break;
671 case types::TY_PP_CXXModule:
672 ClangType = "c++-cpp-output";
673 break;
674 default:
675 ClangType = types::getTypeName(Input.getType());
676 break;
677 }
678 CmdArgs.push_back(ClangType);
679 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000680}
681
682static void appendUserToPath(SmallVectorImpl<char> &Result) {
683#ifdef LLVM_ON_UNIX
684 const char *Username = getenv("LOGNAME");
685#else
686 const char *Username = getenv("USERNAME");
687#endif
688 if (Username) {
689 // Validate that LoginName can be used in a path, and get its length.
690 size_t Len = 0;
691 for (const char *P = Username; *P; ++P, ++Len) {
692 if (!clang::isAlphanumeric(*P) && *P != '_') {
693 Username = nullptr;
694 break;
695 }
696 }
697
698 if (Username && Len > 0) {
699 Result.append(Username, Username + Len);
700 return;
701 }
702 }
703
704// Fallback to user id.
705#ifdef LLVM_ON_UNIX
706 std::string UID = llvm::utostr(getuid());
707#else
708 // FIXME: Windows seems to have an 'SID' that might work.
709 std::string UID = "9999";
710#endif
711 Result.append(UID.begin(), UID.end());
712}
713
714static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
715 const InputInfo &Output, const ArgList &Args,
716 ArgStringList &CmdArgs) {
717
718 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
719 options::OPT_fprofile_generate_EQ,
720 options::OPT_fno_profile_generate);
721 if (PGOGenerateArg &&
722 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
723 PGOGenerateArg = nullptr;
724
725 auto *ProfileGenerateArg = Args.getLastArg(
726 options::OPT_fprofile_instr_generate,
727 options::OPT_fprofile_instr_generate_EQ,
728 options::OPT_fno_profile_instr_generate);
729 if (ProfileGenerateArg &&
730 ProfileGenerateArg->getOption().matches(
731 options::OPT_fno_profile_instr_generate))
732 ProfileGenerateArg = nullptr;
733
734 if (PGOGenerateArg && ProfileGenerateArg)
735 D.Diag(diag::err_drv_argument_not_allowed_with)
736 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
737
738 auto *ProfileUseArg = getLastProfileUseArg(Args);
739
740 if (PGOGenerateArg && ProfileUseArg)
741 D.Diag(diag::err_drv_argument_not_allowed_with)
742 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
743
744 if (ProfileGenerateArg && ProfileUseArg)
745 D.Diag(diag::err_drv_argument_not_allowed_with)
746 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
747
748 if (ProfileGenerateArg) {
749 if (ProfileGenerateArg->getOption().matches(
750 options::OPT_fprofile_instr_generate_EQ))
751 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
752 ProfileGenerateArg->getValue()));
753 // The default is to use Clang Instrumentation.
754 CmdArgs.push_back("-fprofile-instrument=clang");
755 }
756
757 if (PGOGenerateArg) {
758 CmdArgs.push_back("-fprofile-instrument=llvm");
759 if (PGOGenerateArg->getOption().matches(
760 options::OPT_fprofile_generate_EQ)) {
761 SmallString<128> Path(PGOGenerateArg->getValue());
762 llvm::sys::path::append(Path, "default_%m.profraw");
763 CmdArgs.push_back(
764 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
765 }
766 }
767
768 if (ProfileUseArg) {
769 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
770 CmdArgs.push_back(Args.MakeArgString(
771 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
772 else if ((ProfileUseArg->getOption().matches(
773 options::OPT_fprofile_use_EQ) ||
774 ProfileUseArg->getOption().matches(
775 options::OPT_fprofile_instr_use))) {
776 SmallString<128> Path(
777 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
778 if (Path.empty() || llvm::sys::fs::is_directory(Path))
779 llvm::sys::path::append(Path, "default.profdata");
780 CmdArgs.push_back(
781 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
782 }
783 }
784
785 if (Args.hasArg(options::OPT_ftest_coverage) ||
786 Args.hasArg(options::OPT_coverage))
787 CmdArgs.push_back("-femit-coverage-notes");
788 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
789 false) ||
790 Args.hasArg(options::OPT_coverage))
791 CmdArgs.push_back("-femit-coverage-data");
792
793 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000794 options::OPT_fno_coverage_mapping, false)) {
795 if (!ProfileGenerateArg)
796 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
797 << "-fcoverage-mapping"
798 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000799
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000801 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000802
803 if (C.getArgs().hasArg(options::OPT_c) ||
804 C.getArgs().hasArg(options::OPT_S)) {
805 if (Output.isFilename()) {
806 CmdArgs.push_back("-coverage-notes-file");
807 SmallString<128> OutputFilename;
808 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
809 OutputFilename = FinalOutput->getValue();
810 else
811 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
812 SmallString<128> CoverageFilename = OutputFilename;
813 if (llvm::sys::path::is_relative(CoverageFilename)) {
814 SmallString<128> Pwd;
815 if (!llvm::sys::fs::current_path(Pwd)) {
816 llvm::sys::path::append(Pwd, CoverageFilename);
817 CoverageFilename.swap(Pwd);
818 }
819 }
820 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
821 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
822
823 // Leave -fprofile-dir= an unused argument unless .gcda emission is
824 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
825 // the flag used. There is no -fno-profile-dir, so the user has no
826 // targeted way to suppress the warning.
827 if (Args.hasArg(options::OPT_fprofile_arcs) ||
828 Args.hasArg(options::OPT_coverage)) {
829 CmdArgs.push_back("-coverage-data-file");
830 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
831 CoverageFilename = FProfileDir->getValue();
832 llvm::sys::path::append(CoverageFilename, OutputFilename);
833 }
834 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
835 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
836 }
837 }
838 }
839}
840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000841/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000842static bool ContainsCompileAction(const Action *A) {
843 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
844 return true;
845
846 for (const auto &AI : A->inputs())
847 if (ContainsCompileAction(AI))
848 return true;
849
850 return false;
851}
852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000853/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000854/// This is done by default when compiling non-assembler source with -O0.
855static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
856 bool RelaxDefault = true;
857
858 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
859 RelaxDefault = A->getOption().matches(options::OPT_O0);
860
861 if (RelaxDefault) {
862 RelaxDefault = false;
863 for (const auto &Act : C.getActions()) {
864 if (ContainsCompileAction(Act)) {
865 RelaxDefault = true;
866 break;
867 }
868 }
869 }
870
871 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
872 RelaxDefault);
873}
874
875// Extract the integer N from a string spelled "-dwarf-N", returning 0
876// on mismatch. The StringRef input (rather than an Arg) allows
877// for use by the "-Xassembler" option parser.
878static unsigned DwarfVersionNum(StringRef ArgValue) {
879 return llvm::StringSwitch<unsigned>(ArgValue)
880 .Case("-gdwarf-2", 2)
881 .Case("-gdwarf-3", 3)
882 .Case("-gdwarf-4", 4)
883 .Case("-gdwarf-5", 5)
884 .Default(0);
885}
886
887static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
888 codegenoptions::DebugInfoKind DebugInfoKind,
889 unsigned DwarfVersion,
890 llvm::DebuggerKind DebuggerTuning) {
891 switch (DebugInfoKind) {
892 case codegenoptions::DebugLineTablesOnly:
893 CmdArgs.push_back("-debug-info-kind=line-tables-only");
894 break;
895 case codegenoptions::LimitedDebugInfo:
896 CmdArgs.push_back("-debug-info-kind=limited");
897 break;
898 case codegenoptions::FullDebugInfo:
899 CmdArgs.push_back("-debug-info-kind=standalone");
900 break;
901 default:
902 break;
903 }
904 if (DwarfVersion > 0)
905 CmdArgs.push_back(
906 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
907 switch (DebuggerTuning) {
908 case llvm::DebuggerKind::GDB:
909 CmdArgs.push_back("-debugger-tuning=gdb");
910 break;
911 case llvm::DebuggerKind::LLDB:
912 CmdArgs.push_back("-debugger-tuning=lldb");
913 break;
914 case llvm::DebuggerKind::SCE:
915 CmdArgs.push_back("-debugger-tuning=sce");
916 break;
917 default:
918 break;
919 }
920}
921
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000922static void RenderDebugInfoCompressionArgs(const ArgList &Args,
923 ArgStringList &CmdArgs,
924 const Driver &D) {
925 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
926 if (!A)
927 return;
928
929 if (A->getOption().getID() == options::OPT_gz) {
930 if (llvm::zlib::isAvailable())
931 CmdArgs.push_back("-compress-debug-sections");
932 else
933 D.Diag(diag::warn_debug_compression_unavailable);
934 return;
935 }
936
937 StringRef Value = A->getValue();
938 if (Value == "none") {
939 CmdArgs.push_back("-compress-debug-sections=none");
940 } else if (Value == "zlib" || Value == "zlib-gnu") {
941 if (llvm::zlib::isAvailable()) {
942 CmdArgs.push_back(
943 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
944 } else {
945 D.Diag(diag::warn_debug_compression_unavailable);
946 }
947 } else {
948 D.Diag(diag::err_drv_unsupported_option_argument)
949 << A->getOption().getName() << Value;
950 }
951}
952
David L. Jonesf561aba2017-03-08 01:02:16 +0000953static const char *RelocationModelName(llvm::Reloc::Model Model) {
954 switch (Model) {
955 case llvm::Reloc::Static:
956 return "static";
957 case llvm::Reloc::PIC_:
958 return "pic";
959 case llvm::Reloc::DynamicNoPIC:
960 return "dynamic-no-pic";
961 case llvm::Reloc::ROPI:
962 return "ropi";
963 case llvm::Reloc::RWPI:
964 return "rwpi";
965 case llvm::Reloc::ROPI_RWPI:
966 return "ropi-rwpi";
967 }
968 llvm_unreachable("Unknown Reloc::Model kind");
969}
970
971void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
972 const Driver &D, const ArgList &Args,
973 ArgStringList &CmdArgs,
974 const InputInfo &Output,
975 const InputInfoList &Inputs) const {
976 Arg *A;
977 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
978
979 CheckPreprocessingOptions(D, Args);
980
981 Args.AddLastArg(CmdArgs, options::OPT_C);
982 Args.AddLastArg(CmdArgs, options::OPT_CC);
983
984 // Handle dependency file generation.
985 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
986 (A = Args.getLastArg(options::OPT_MD)) ||
987 (A = Args.getLastArg(options::OPT_MMD))) {
988 // Determine the output location.
989 const char *DepFile;
990 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
991 DepFile = MF->getValue();
992 C.addFailureResultFile(DepFile, &JA);
993 } else if (Output.getType() == types::TY_Dependencies) {
994 DepFile = Output.getFilename();
995 } else if (A->getOption().matches(options::OPT_M) ||
996 A->getOption().matches(options::OPT_MM)) {
997 DepFile = "-";
998 } else {
999 DepFile = getDependencyFileName(Args, Inputs);
1000 C.addFailureResultFile(DepFile, &JA);
1001 }
1002 CmdArgs.push_back("-dependency-file");
1003 CmdArgs.push_back(DepFile);
1004
1005 // Add a default target if one wasn't specified.
1006 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1007 const char *DepTarget;
1008
1009 // If user provided -o, that is the dependency target, except
1010 // when we are only generating a dependency file.
1011 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1012 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1013 DepTarget = OutputOpt->getValue();
1014 } else {
1015 // Otherwise derive from the base input.
1016 //
1017 // FIXME: This should use the computed output file location.
1018 SmallString<128> P(Inputs[0].getBaseInput());
1019 llvm::sys::path::replace_extension(P, "o");
1020 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1021 }
1022
Yuka Takahashicdb53482017-06-16 16:01:13 +00001023 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1024 CmdArgs.push_back("-w");
1025 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001026 CmdArgs.push_back("-MT");
1027 SmallString<128> Quoted;
1028 QuoteTarget(DepTarget, Quoted);
1029 CmdArgs.push_back(Args.MakeArgString(Quoted));
1030 }
1031
1032 if (A->getOption().matches(options::OPT_M) ||
1033 A->getOption().matches(options::OPT_MD))
1034 CmdArgs.push_back("-sys-header-deps");
1035 if ((isa<PrecompileJobAction>(JA) &&
1036 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1037 Args.hasArg(options::OPT_fmodule_file_deps))
1038 CmdArgs.push_back("-module-file-deps");
1039 }
1040
1041 if (Args.hasArg(options::OPT_MG)) {
1042 if (!A || A->getOption().matches(options::OPT_MD) ||
1043 A->getOption().matches(options::OPT_MMD))
1044 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1045 CmdArgs.push_back("-MG");
1046 }
1047
1048 Args.AddLastArg(CmdArgs, options::OPT_MP);
1049 Args.AddLastArg(CmdArgs, options::OPT_MV);
1050
1051 // Convert all -MQ <target> args to -MT <quoted target>
1052 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1053 A->claim();
1054
1055 if (A->getOption().matches(options::OPT_MQ)) {
1056 CmdArgs.push_back("-MT");
1057 SmallString<128> Quoted;
1058 QuoteTarget(A->getValue(), Quoted);
1059 CmdArgs.push_back(Args.MakeArgString(Quoted));
1060
1061 // -MT flag - no change
1062 } else {
1063 A->render(Args, CmdArgs);
1064 }
1065 }
1066
1067 // Add offload include arguments specific for CUDA. This must happen before
1068 // we -I or -include anything else, because we must pick up the CUDA headers
1069 // from the particular CUDA installation, rather than from e.g.
1070 // /usr/local/include.
1071 if (JA.isOffloading(Action::OFK_Cuda))
1072 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1073
1074 // Add -i* options, and automatically translate to
1075 // -include-pch/-include-pth for transparent PCH support. It's
1076 // wonky, but we include looking for .gch so we can support seamless
1077 // replacement into a build system already set up to be generating
1078 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001079
1080 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001081 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1082 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001083 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1084 JA.getKind() <= Action::AssembleJobClass) {
1085 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001086 }
Erich Keane76675de2018-07-05 17:22:13 +00001087 if (YcArg || YuArg) {
1088 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1089 if (!isa<PrecompileJobAction>(JA)) {
1090 CmdArgs.push_back("-include-pch");
1091 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(C, ThroughHeader)));
1092 }
1093 CmdArgs.push_back(
1094 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1095 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001096 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001097
1098 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001099 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001100 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001101 // Handling of gcc-style gch precompiled headers.
1102 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1103 RenderedImplicitInclude = true;
1104
1105 // Use PCH if the user requested it.
1106 bool UsePCH = D.CCCUsePCH;
1107
1108 bool FoundPTH = false;
1109 bool FoundPCH = false;
1110 SmallString<128> P(A->getValue());
1111 // We want the files to have a name like foo.h.pch. Add a dummy extension
1112 // so that replace_extension does the right thing.
1113 P += ".dummy";
1114 if (UsePCH) {
1115 llvm::sys::path::replace_extension(P, "pch");
1116 if (llvm::sys::fs::exists(P))
1117 FoundPCH = true;
1118 }
1119
1120 if (!FoundPCH) {
1121 llvm::sys::path::replace_extension(P, "pth");
1122 if (llvm::sys::fs::exists(P))
1123 FoundPTH = true;
1124 }
1125
1126 if (!FoundPCH && !FoundPTH) {
1127 llvm::sys::path::replace_extension(P, "gch");
1128 if (llvm::sys::fs::exists(P)) {
1129 FoundPCH = UsePCH;
1130 FoundPTH = !UsePCH;
1131 }
1132 }
1133
1134 if (FoundPCH || FoundPTH) {
1135 if (IsFirstImplicitInclude) {
1136 A->claim();
1137 if (UsePCH)
1138 CmdArgs.push_back("-include-pch");
1139 else
1140 CmdArgs.push_back("-include-pth");
1141 CmdArgs.push_back(Args.MakeArgString(P));
1142 continue;
1143 } else {
1144 // Ignore the PCH if not first on command line and emit warning.
1145 D.Diag(diag::warn_drv_pch_not_first_include) << P
1146 << A->getAsString(Args);
1147 }
1148 }
1149 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1150 // Handling of paths which must come late. These entries are handled by
1151 // the toolchain itself after the resource dir is inserted in the right
1152 // search order.
1153 // Do not claim the argument so that the use of the argument does not
1154 // silently go unnoticed on toolchains which do not honour the option.
1155 continue;
1156 }
1157
1158 // Not translated, render as usual.
1159 A->claim();
1160 A->render(Args, CmdArgs);
1161 }
1162
1163 Args.AddAllArgs(CmdArgs,
1164 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1165 options::OPT_F, options::OPT_index_header_map});
1166
1167 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1168
1169 // FIXME: There is a very unfortunate problem here, some troubled
1170 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1171 // really support that we would have to parse and then translate
1172 // those options. :(
1173 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1174 options::OPT_Xpreprocessor);
1175
1176 // -I- is a deprecated GCC feature, reject it.
1177 if (Arg *A = Args.getLastArg(options::OPT_I_))
1178 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1179
1180 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1181 // -isysroot to the CC1 invocation.
1182 StringRef sysroot = C.getSysRoot();
1183 if (sysroot != "") {
1184 if (!Args.hasArg(options::OPT_isysroot)) {
1185 CmdArgs.push_back("-isysroot");
1186 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1187 }
1188 }
1189
1190 // Parse additional include paths from environment variables.
1191 // FIXME: We should probably sink the logic for handling these from the
1192 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1193 // CPATH - included following the user specified includes (but prior to
1194 // builtin and standard includes).
1195 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1196 // C_INCLUDE_PATH - system includes enabled when compiling C.
1197 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1198 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1199 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1200 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1201 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1202 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1203 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1204
1205 // While adding the include arguments, we also attempt to retrieve the
1206 // arguments of related offloading toolchains or arguments that are specific
1207 // of an offloading programming model.
1208
1209 // Add C++ include arguments, if needed.
1210 if (types::isCXX(Inputs[0].getType()))
1211 forAllAssociatedToolChains(C, JA, getToolChain(),
1212 [&Args, &CmdArgs](const ToolChain &TC) {
1213 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1214 });
1215
1216 // Add system include arguments for all targets but IAMCU.
1217 if (!IsIAMCU)
1218 forAllAssociatedToolChains(C, JA, getToolChain(),
1219 [&Args, &CmdArgs](const ToolChain &TC) {
1220 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1221 });
1222 else {
1223 // For IAMCU add special include arguments.
1224 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1225 }
1226}
1227
1228// FIXME: Move to target hook.
1229static bool isSignedCharDefault(const llvm::Triple &Triple) {
1230 switch (Triple.getArch()) {
1231 default:
1232 return true;
1233
1234 case llvm::Triple::aarch64:
1235 case llvm::Triple::aarch64_be:
1236 case llvm::Triple::arm:
1237 case llvm::Triple::armeb:
1238 case llvm::Triple::thumb:
1239 case llvm::Triple::thumbeb:
1240 if (Triple.isOSDarwin() || Triple.isOSWindows())
1241 return true;
1242 return false;
1243
1244 case llvm::Triple::ppc:
1245 case llvm::Triple::ppc64:
1246 if (Triple.isOSDarwin())
1247 return true;
1248 return false;
1249
1250 case llvm::Triple::hexagon:
1251 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001252 case llvm::Triple::riscv32:
1253 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001254 case llvm::Triple::systemz:
1255 case llvm::Triple::xcore:
1256 return false;
1257 }
1258}
1259
1260static bool isNoCommonDefault(const llvm::Triple &Triple) {
1261 switch (Triple.getArch()) {
1262 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001263 if (Triple.isOSFuchsia())
1264 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001265 return false;
1266
1267 case llvm::Triple::xcore:
1268 case llvm::Triple::wasm32:
1269 case llvm::Triple::wasm64:
1270 return true;
1271 }
1272}
1273
1274void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1275 ArgStringList &CmdArgs, bool KernelOrKext) const {
1276 // Select the ABI to use.
1277 // FIXME: Support -meabi.
1278 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1279 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001280 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001281 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001282 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001283 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001284 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001285 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001286
David L. Jonesf561aba2017-03-08 01:02:16 +00001287 CmdArgs.push_back("-target-abi");
1288 CmdArgs.push_back(ABIName);
1289
1290 // Determine floating point ABI from the options & target defaults.
1291 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1292 if (ABI == arm::FloatABI::Soft) {
1293 // Floating point operations and argument passing are soft.
1294 // FIXME: This changes CPP defines, we need -target-soft-float.
1295 CmdArgs.push_back("-msoft-float");
1296 CmdArgs.push_back("-mfloat-abi");
1297 CmdArgs.push_back("soft");
1298 } else if (ABI == arm::FloatABI::SoftFP) {
1299 // Floating point operations are hard, but argument passing is soft.
1300 CmdArgs.push_back("-mfloat-abi");
1301 CmdArgs.push_back("soft");
1302 } else {
1303 // Floating point operations and argument passing are hard.
1304 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1305 CmdArgs.push_back("-mfloat-abi");
1306 CmdArgs.push_back("hard");
1307 }
1308
1309 // Forward the -mglobal-merge option for explicit control over the pass.
1310 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1311 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001312 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001313 if (A->getOption().matches(options::OPT_mno_global_merge))
1314 CmdArgs.push_back("-arm-global-merge=false");
1315 else
1316 CmdArgs.push_back("-arm-global-merge=true");
1317 }
1318
1319 if (!Args.hasFlag(options::OPT_mimplicit_float,
1320 options::OPT_mno_implicit_float, true))
1321 CmdArgs.push_back("-no-implicit-float");
1322}
1323
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001324void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1325 const ArgList &Args, bool KernelOrKext,
1326 ArgStringList &CmdArgs) const {
1327 const ToolChain &TC = getToolChain();
1328
1329 // Add the target features
1330 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1331
1332 // Add target specific flags.
1333 switch (TC.getArch()) {
1334 default:
1335 break;
1336
1337 case llvm::Triple::arm:
1338 case llvm::Triple::armeb:
1339 case llvm::Triple::thumb:
1340 case llvm::Triple::thumbeb:
1341 // Use the effective triple, which takes into account the deployment target.
1342 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1343 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1344 break;
1345
1346 case llvm::Triple::aarch64:
1347 case llvm::Triple::aarch64_be:
1348 AddAArch64TargetArgs(Args, CmdArgs);
1349 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1350 break;
1351
1352 case llvm::Triple::mips:
1353 case llvm::Triple::mipsel:
1354 case llvm::Triple::mips64:
1355 case llvm::Triple::mips64el:
1356 AddMIPSTargetArgs(Args, CmdArgs);
1357 break;
1358
1359 case llvm::Triple::ppc:
1360 case llvm::Triple::ppc64:
1361 case llvm::Triple::ppc64le:
1362 AddPPCTargetArgs(Args, CmdArgs);
1363 break;
1364
Alex Bradbury71f45452018-01-11 13:36:56 +00001365 case llvm::Triple::riscv32:
1366 case llvm::Triple::riscv64:
1367 AddRISCVTargetArgs(Args, CmdArgs);
1368 break;
1369
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001370 case llvm::Triple::sparc:
1371 case llvm::Triple::sparcel:
1372 case llvm::Triple::sparcv9:
1373 AddSparcTargetArgs(Args, CmdArgs);
1374 break;
1375
1376 case llvm::Triple::systemz:
1377 AddSystemZTargetArgs(Args, CmdArgs);
1378 break;
1379
1380 case llvm::Triple::x86:
1381 case llvm::Triple::x86_64:
1382 AddX86TargetArgs(Args, CmdArgs);
1383 break;
1384
1385 case llvm::Triple::lanai:
1386 AddLanaiTargetArgs(Args, CmdArgs);
1387 break;
1388
1389 case llvm::Triple::hexagon:
1390 AddHexagonTargetArgs(Args, CmdArgs);
1391 break;
1392
1393 case llvm::Triple::wasm32:
1394 case llvm::Triple::wasm64:
1395 AddWebAssemblyTargetArgs(Args, CmdArgs);
1396 break;
1397 }
1398}
1399
David L. Jonesf561aba2017-03-08 01:02:16 +00001400void Clang::AddAArch64TargetArgs(const ArgList &Args,
1401 ArgStringList &CmdArgs) const {
1402 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1403
1404 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1405 Args.hasArg(options::OPT_mkernel) ||
1406 Args.hasArg(options::OPT_fapple_kext))
1407 CmdArgs.push_back("-disable-red-zone");
1408
1409 if (!Args.hasFlag(options::OPT_mimplicit_float,
1410 options::OPT_mno_implicit_float, true))
1411 CmdArgs.push_back("-no-implicit-float");
1412
1413 const char *ABIName = nullptr;
1414 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1415 ABIName = A->getValue();
1416 else if (Triple.isOSDarwin())
1417 ABIName = "darwinpcs";
1418 else
1419 ABIName = "aapcs";
1420
1421 CmdArgs.push_back("-target-abi");
1422 CmdArgs.push_back(ABIName);
1423
1424 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1425 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001426 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001427 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1428 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1429 else
1430 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1431 } else if (Triple.isAndroid()) {
1432 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001433 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001434 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1435 }
1436
1437 // Forward the -mglobal-merge option for explicit control over the pass.
1438 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1439 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001440 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001441 if (A->getOption().matches(options::OPT_mno_global_merge))
1442 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1443 else
1444 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1445 }
1446}
1447
1448void Clang::AddMIPSTargetArgs(const ArgList &Args,
1449 ArgStringList &CmdArgs) const {
1450 const Driver &D = getToolChain().getDriver();
1451 StringRef CPUName;
1452 StringRef ABIName;
1453 const llvm::Triple &Triple = getToolChain().getTriple();
1454 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1455
1456 CmdArgs.push_back("-target-abi");
1457 CmdArgs.push_back(ABIName.data());
1458
1459 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1460 if (ABI == mips::FloatABI::Soft) {
1461 // Floating point operations and argument passing are soft.
1462 CmdArgs.push_back("-msoft-float");
1463 CmdArgs.push_back("-mfloat-abi");
1464 CmdArgs.push_back("soft");
1465 } else {
1466 // Floating point operations and argument passing are hard.
1467 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1468 CmdArgs.push_back("-mfloat-abi");
1469 CmdArgs.push_back("hard");
1470 }
1471
1472 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1473 if (A->getOption().matches(options::OPT_mxgot)) {
1474 CmdArgs.push_back("-mllvm");
1475 CmdArgs.push_back("-mxgot");
1476 }
1477 }
1478
1479 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1480 options::OPT_mno_ldc1_sdc1)) {
1481 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1482 CmdArgs.push_back("-mllvm");
1483 CmdArgs.push_back("-mno-ldc1-sdc1");
1484 }
1485 }
1486
1487 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1488 options::OPT_mno_check_zero_division)) {
1489 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1490 CmdArgs.push_back("-mllvm");
1491 CmdArgs.push_back("-mno-check-zero-division");
1492 }
1493 }
1494
1495 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1496 StringRef v = A->getValue();
1497 CmdArgs.push_back("-mllvm");
1498 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1499 A->claim();
1500 }
1501
Simon Dardis31636a12017-07-20 14:04:12 +00001502 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1503 Arg *ABICalls =
1504 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1505
1506 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1507 // -mgpopt is the default for static, -fno-pic environments but these two
1508 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1509 // the only case where -mllvm -mgpopt is passed.
1510 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1511 // passed explicitly when compiling something with -mabicalls
1512 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001513 //
1514 // When the ABI in use is N64, we also need to determine the PIC mode that
1515 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001516 bool NoABICalls =
1517 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001518
1519 llvm::Reloc::Model RelocationModel;
1520 unsigned PICLevel;
1521 bool IsPIE;
1522 std::tie(RelocationModel, PICLevel, IsPIE) =
1523 ParsePICArgs(getToolChain(), Args);
1524
1525 NoABICalls = NoABICalls ||
1526 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1527
Simon Dardis31636a12017-07-20 14:04:12 +00001528 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1529 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1530 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1531 CmdArgs.push_back("-mllvm");
1532 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001533
1534 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1535 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001536 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001537 options::OPT_mno_extern_sdata);
1538 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1539 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001540 if (LocalSData) {
1541 CmdArgs.push_back("-mllvm");
1542 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1543 CmdArgs.push_back("-mlocal-sdata=1");
1544 } else {
1545 CmdArgs.push_back("-mlocal-sdata=0");
1546 }
1547 LocalSData->claim();
1548 }
1549
Simon Dardis7d318782017-07-24 14:02:09 +00001550 if (ExternSData) {
1551 CmdArgs.push_back("-mllvm");
1552 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1553 CmdArgs.push_back("-mextern-sdata=1");
1554 } else {
1555 CmdArgs.push_back("-mextern-sdata=0");
1556 }
1557 ExternSData->claim();
1558 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001559
1560 if (EmbeddedData) {
1561 CmdArgs.push_back("-mllvm");
1562 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1563 CmdArgs.push_back("-membedded-data=1");
1564 } else {
1565 CmdArgs.push_back("-membedded-data=0");
1566 }
1567 EmbeddedData->claim();
1568 }
1569
Simon Dardis31636a12017-07-20 14:04:12 +00001570 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1571 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1572
1573 if (GPOpt)
1574 GPOpt->claim();
1575
David L. Jonesf561aba2017-03-08 01:02:16 +00001576 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1577 StringRef Val = StringRef(A->getValue());
1578 if (mips::hasCompactBranches(CPUName)) {
1579 if (Val == "never" || Val == "always" || Val == "optimal") {
1580 CmdArgs.push_back("-mllvm");
1581 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1582 } else
1583 D.Diag(diag::err_drv_unsupported_option_argument)
1584 << A->getOption().getName() << Val;
1585 } else
1586 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1587 }
1588}
1589
1590void Clang::AddPPCTargetArgs(const ArgList &Args,
1591 ArgStringList &CmdArgs) const {
1592 // Select the ABI to use.
1593 const char *ABIName = nullptr;
1594 if (getToolChain().getTriple().isOSLinux())
1595 switch (getToolChain().getArch()) {
1596 case llvm::Triple::ppc64: {
1597 // When targeting a processor that supports QPX, or if QPX is
1598 // specifically enabled, default to using the ABI that supports QPX (so
1599 // long as it is not specifically disabled).
1600 bool HasQPX = false;
1601 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1602 HasQPX = A->getValue() == StringRef("a2q");
1603 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1604 if (HasQPX) {
1605 ABIName = "elfv1-qpx";
1606 break;
1607 }
1608
1609 ABIName = "elfv1";
1610 break;
1611 }
1612 case llvm::Triple::ppc64le:
1613 ABIName = "elfv2";
1614 break;
1615 default:
1616 break;
1617 }
1618
1619 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1620 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1621 // the option if given as we don't have backend support for any targets
1622 // that don't use the altivec abi.
1623 if (StringRef(A->getValue()) != "altivec")
1624 ABIName = A->getValue();
1625
1626 ppc::FloatABI FloatABI =
1627 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1628
1629 if (FloatABI == ppc::FloatABI::Soft) {
1630 // Floating point operations and argument passing are soft.
1631 CmdArgs.push_back("-msoft-float");
1632 CmdArgs.push_back("-mfloat-abi");
1633 CmdArgs.push_back("soft");
1634 } else {
1635 // Floating point operations and argument passing are hard.
1636 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1637 CmdArgs.push_back("-mfloat-abi");
1638 CmdArgs.push_back("hard");
1639 }
1640
1641 if (ABIName) {
1642 CmdArgs.push_back("-target-abi");
1643 CmdArgs.push_back(ABIName);
1644 }
1645}
1646
Alex Bradbury71f45452018-01-11 13:36:56 +00001647void Clang::AddRISCVTargetArgs(const ArgList &Args,
1648 ArgStringList &CmdArgs) const {
1649 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001650 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001651 const char *ABIName = nullptr;
1652 const llvm::Triple &Triple = getToolChain().getTriple();
1653 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1654 ABIName = A->getValue();
1655 else if (Triple.getArch() == llvm::Triple::riscv32)
1656 ABIName = "ilp32";
1657 else if (Triple.getArch() == llvm::Triple::riscv64)
1658 ABIName = "lp64";
1659 else
1660 llvm_unreachable("Unexpected triple!");
1661
1662 CmdArgs.push_back("-target-abi");
1663 CmdArgs.push_back(ABIName);
1664}
1665
David L. Jonesf561aba2017-03-08 01:02:16 +00001666void Clang::AddSparcTargetArgs(const ArgList &Args,
1667 ArgStringList &CmdArgs) const {
1668 sparc::FloatABI FloatABI =
1669 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1670
1671 if (FloatABI == sparc::FloatABI::Soft) {
1672 // Floating point operations and argument passing are soft.
1673 CmdArgs.push_back("-msoft-float");
1674 CmdArgs.push_back("-mfloat-abi");
1675 CmdArgs.push_back("soft");
1676 } else {
1677 // Floating point operations and argument passing are hard.
1678 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1679 CmdArgs.push_back("-mfloat-abi");
1680 CmdArgs.push_back("hard");
1681 }
1682}
1683
1684void Clang::AddSystemZTargetArgs(const ArgList &Args,
1685 ArgStringList &CmdArgs) const {
1686 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1687 CmdArgs.push_back("-mbackchain");
1688}
1689
1690void Clang::AddX86TargetArgs(const ArgList &Args,
1691 ArgStringList &CmdArgs) const {
1692 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1693 Args.hasArg(options::OPT_mkernel) ||
1694 Args.hasArg(options::OPT_fapple_kext))
1695 CmdArgs.push_back("-disable-red-zone");
1696
1697 // Default to avoid implicit floating-point for kernel/kext code, but allow
1698 // that to be overridden with -mno-soft-float.
1699 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1700 Args.hasArg(options::OPT_fapple_kext));
1701 if (Arg *A = Args.getLastArg(
1702 options::OPT_msoft_float, options::OPT_mno_soft_float,
1703 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1704 const Option &O = A->getOption();
1705 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1706 O.matches(options::OPT_msoft_float));
1707 }
1708 if (NoImplicitFloat)
1709 CmdArgs.push_back("-no-implicit-float");
1710
1711 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1712 StringRef Value = A->getValue();
1713 if (Value == "intel" || Value == "att") {
1714 CmdArgs.push_back("-mllvm");
1715 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1716 } else {
1717 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1718 << A->getOption().getName() << Value;
1719 }
Nico Webere3712cf2018-01-17 13:34:20 +00001720 } else if (getToolChain().getDriver().IsCLMode()) {
1721 CmdArgs.push_back("-mllvm");
1722 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001723 }
1724
1725 // Set flags to support MCU ABI.
1726 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1727 CmdArgs.push_back("-mfloat-abi");
1728 CmdArgs.push_back("soft");
1729 CmdArgs.push_back("-mstack-alignment=4");
1730 }
1731}
1732
1733void Clang::AddHexagonTargetArgs(const ArgList &Args,
1734 ArgStringList &CmdArgs) const {
1735 CmdArgs.push_back("-mqdsp6-compat");
1736 CmdArgs.push_back("-Wreturn-type");
1737
1738 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001739 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001740 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1741 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001742 }
1743
1744 if (!Args.hasArg(options::OPT_fno_short_enums))
1745 CmdArgs.push_back("-fshort-enums");
1746 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1747 CmdArgs.push_back("-mllvm");
1748 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1749 }
1750 CmdArgs.push_back("-mllvm");
1751 CmdArgs.push_back("-machine-sink-split=0");
1752}
1753
1754void Clang::AddLanaiTargetArgs(const ArgList &Args,
1755 ArgStringList &CmdArgs) const {
1756 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1757 StringRef CPUName = A->getValue();
1758
1759 CmdArgs.push_back("-target-cpu");
1760 CmdArgs.push_back(Args.MakeArgString(CPUName));
1761 }
1762 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1763 StringRef Value = A->getValue();
1764 // Only support mregparm=4 to support old usage. Report error for all other
1765 // cases.
1766 int Mregparm;
1767 if (Value.getAsInteger(10, Mregparm)) {
1768 if (Mregparm != 4) {
1769 getToolChain().getDriver().Diag(
1770 diag::err_drv_unsupported_option_argument)
1771 << A->getOption().getName() << Value;
1772 }
1773 }
1774 }
1775}
1776
1777void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1778 ArgStringList &CmdArgs) const {
1779 // Default to "hidden" visibility.
1780 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1781 options::OPT_fvisibility_ms_compat)) {
1782 CmdArgs.push_back("-fvisibility");
1783 CmdArgs.push_back("hidden");
1784 }
1785}
1786
1787void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1788 StringRef Target, const InputInfo &Output,
1789 const InputInfo &Input, const ArgList &Args) const {
1790 // If this is a dry run, do not create the compilation database file.
1791 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1792 return;
1793
1794 using llvm::yaml::escape;
1795 const Driver &D = getToolChain().getDriver();
1796
1797 if (!CompilationDatabase) {
1798 std::error_code EC;
1799 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1800 if (EC) {
1801 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1802 << EC.message();
1803 return;
1804 }
1805 CompilationDatabase = std::move(File);
1806 }
1807 auto &CDB = *CompilationDatabase;
1808 SmallString<128> Buf;
1809 if (llvm::sys::fs::current_path(Buf))
1810 Buf = ".";
1811 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1812 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1813 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1814 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1815 Buf = "-x";
1816 Buf += types::getTypeName(Input.getType());
1817 CDB << ", \"" << escape(Buf) << "\"";
1818 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1819 Buf = "--sysroot=";
1820 Buf += D.SysRoot;
1821 CDB << ", \"" << escape(Buf) << "\"";
1822 }
1823 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1824 for (auto &A: Args) {
1825 auto &O = A->getOption();
1826 // Skip language selection, which is positional.
1827 if (O.getID() == options::OPT_x)
1828 continue;
1829 // Skip writing dependency output and the compilation database itself.
1830 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1831 continue;
1832 // Skip inputs.
1833 if (O.getKind() == Option::InputClass)
1834 continue;
1835 // All other arguments are quoted and appended.
1836 ArgStringList ASL;
1837 A->render(Args, ASL);
1838 for (auto &it: ASL)
1839 CDB << ", \"" << escape(it) << "\"";
1840 }
1841 Buf = "--target=";
1842 Buf += Target;
1843 CDB << ", \"" << escape(Buf) << "\"]},\n";
1844}
1845
1846static void CollectArgsForIntegratedAssembler(Compilation &C,
1847 const ArgList &Args,
1848 ArgStringList &CmdArgs,
1849 const Driver &D) {
1850 if (UseRelaxAll(C, Args))
1851 CmdArgs.push_back("-mrelax-all");
1852
1853 // Only default to -mincremental-linker-compatible if we think we are
1854 // targeting the MSVC linker.
1855 bool DefaultIncrementalLinkerCompatible =
1856 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1857 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1858 options::OPT_mno_incremental_linker_compatible,
1859 DefaultIncrementalLinkerCompatible))
1860 CmdArgs.push_back("-mincremental-linker-compatible");
1861
1862 switch (C.getDefaultToolChain().getArch()) {
1863 case llvm::Triple::arm:
1864 case llvm::Triple::armeb:
1865 case llvm::Triple::thumb:
1866 case llvm::Triple::thumbeb:
1867 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1868 StringRef Value = A->getValue();
1869 if (Value == "always" || Value == "never" || Value == "arm" ||
1870 Value == "thumb") {
1871 CmdArgs.push_back("-mllvm");
1872 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1873 } else {
1874 D.Diag(diag::err_drv_unsupported_option_argument)
1875 << A->getOption().getName() << Value;
1876 }
1877 }
1878 break;
1879 default:
1880 break;
1881 }
1882
1883 // When passing -I arguments to the assembler we sometimes need to
1884 // unconditionally take the next argument. For example, when parsing
1885 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1886 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1887 // arg after parsing the '-I' arg.
1888 bool TakeNextArg = false;
1889
Petr Hosek5668d832017-11-22 01:38:31 +00001890 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001891 const char *MipsTargetFeature = nullptr;
1892 for (const Arg *A :
1893 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1894 A->claim();
1895
1896 for (StringRef Value : A->getValues()) {
1897 if (TakeNextArg) {
1898 CmdArgs.push_back(Value.data());
1899 TakeNextArg = false;
1900 continue;
1901 }
1902
1903 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1904 Value == "-mbig-obj")
1905 continue; // LLVM handles bigobj automatically
1906
1907 switch (C.getDefaultToolChain().getArch()) {
1908 default:
1909 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001910 case llvm::Triple::thumb:
1911 case llvm::Triple::thumbeb:
1912 case llvm::Triple::arm:
1913 case llvm::Triple::armeb:
1914 if (Value == "-mthumb")
1915 // -mthumb has already been processed in ComputeLLVMTriple()
1916 // recognize but skip over here.
1917 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001918 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001919 case llvm::Triple::mips:
1920 case llvm::Triple::mipsel:
1921 case llvm::Triple::mips64:
1922 case llvm::Triple::mips64el:
1923 if (Value == "--trap") {
1924 CmdArgs.push_back("-target-feature");
1925 CmdArgs.push_back("+use-tcc-in-div");
1926 continue;
1927 }
1928 if (Value == "--break") {
1929 CmdArgs.push_back("-target-feature");
1930 CmdArgs.push_back("-use-tcc-in-div");
1931 continue;
1932 }
1933 if (Value.startswith("-msoft-float")) {
1934 CmdArgs.push_back("-target-feature");
1935 CmdArgs.push_back("+soft-float");
1936 continue;
1937 }
1938 if (Value.startswith("-mhard-float")) {
1939 CmdArgs.push_back("-target-feature");
1940 CmdArgs.push_back("-soft-float");
1941 continue;
1942 }
1943
1944 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1945 .Case("-mips1", "+mips1")
1946 .Case("-mips2", "+mips2")
1947 .Case("-mips3", "+mips3")
1948 .Case("-mips4", "+mips4")
1949 .Case("-mips5", "+mips5")
1950 .Case("-mips32", "+mips32")
1951 .Case("-mips32r2", "+mips32r2")
1952 .Case("-mips32r3", "+mips32r3")
1953 .Case("-mips32r5", "+mips32r5")
1954 .Case("-mips32r6", "+mips32r6")
1955 .Case("-mips64", "+mips64")
1956 .Case("-mips64r2", "+mips64r2")
1957 .Case("-mips64r3", "+mips64r3")
1958 .Case("-mips64r5", "+mips64r5")
1959 .Case("-mips64r6", "+mips64r6")
1960 .Default(nullptr);
1961 if (MipsTargetFeature)
1962 continue;
1963 }
1964
1965 if (Value == "-force_cpusubtype_ALL") {
1966 // Do nothing, this is the default and we don't support anything else.
1967 } else if (Value == "-L") {
1968 CmdArgs.push_back("-msave-temp-labels");
1969 } else if (Value == "--fatal-warnings") {
1970 CmdArgs.push_back("-massembler-fatal-warnings");
1971 } else if (Value == "--noexecstack") {
1972 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001973 } else if (Value.startswith("-compress-debug-sections") ||
1974 Value.startswith("--compress-debug-sections") ||
1975 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001976 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001977 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001978 } else if (Value == "-mrelax-relocations=yes" ||
1979 Value == "--mrelax-relocations=yes") {
1980 UseRelaxRelocations = true;
1981 } else if (Value == "-mrelax-relocations=no" ||
1982 Value == "--mrelax-relocations=no") {
1983 UseRelaxRelocations = false;
1984 } else if (Value.startswith("-I")) {
1985 CmdArgs.push_back(Value.data());
1986 // We need to consume the next argument if the current arg is a plain
1987 // -I. The next arg will be the include directory.
1988 if (Value == "-I")
1989 TakeNextArg = true;
1990 } else if (Value.startswith("-gdwarf-")) {
1991 // "-gdwarf-N" options are not cc1as options.
1992 unsigned DwarfVersion = DwarfVersionNum(Value);
1993 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
1994 CmdArgs.push_back(Value.data());
1995 } else {
1996 RenderDebugEnablingArgs(Args, CmdArgs,
1997 codegenoptions::LimitedDebugInfo,
1998 DwarfVersion, llvm::DebuggerKind::Default);
1999 }
2000 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2001 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2002 // Do nothing, we'll validate it later.
2003 } else if (Value == "-defsym") {
2004 if (A->getNumValues() != 2) {
2005 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2006 break;
2007 }
2008 const char *S = A->getValue(1);
2009 auto Pair = StringRef(S).split('=');
2010 auto Sym = Pair.first;
2011 auto SVal = Pair.second;
2012
2013 if (Sym.empty() || SVal.empty()) {
2014 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2015 break;
2016 }
2017 int64_t IVal;
2018 if (SVal.getAsInteger(0, IVal)) {
2019 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2020 break;
2021 }
2022 CmdArgs.push_back(Value.data());
2023 TakeNextArg = true;
2024 } else {
2025 D.Diag(diag::err_drv_unsupported_option_argument)
2026 << A->getOption().getName() << Value;
2027 }
2028 }
2029 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002030 if (UseRelaxRelocations)
2031 CmdArgs.push_back("--mrelax-relocations");
2032 if (MipsTargetFeature != nullptr) {
2033 CmdArgs.push_back("-target-feature");
2034 CmdArgs.push_back(MipsTargetFeature);
2035 }
2036}
2037
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002038static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2039 bool OFastEnabled, const ArgList &Args,
2040 ArgStringList &CmdArgs) {
2041 // Handle various floating point optimization flags, mapping them to the
2042 // appropriate LLVM code generation flags. This is complicated by several
2043 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002044 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002045 // LLVM flags based on the final state.
2046 bool HonorINFs = true;
2047 bool HonorNaNs = true;
2048 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2049 bool MathErrno = TC.IsMathErrnoDefault();
2050 bool AssociativeMath = false;
2051 bool ReciprocalMath = false;
2052 bool SignedZeros = true;
2053 bool TrappingMath = true;
2054 StringRef DenormalFPMath = "";
2055 StringRef FPContract = "";
2056
2057 for (const Arg *A : Args) {
2058 switch (A->getOption().getID()) {
2059 // If this isn't an FP option skip the claim below
2060 default: continue;
2061
2062 // Options controlling individual features
2063 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2064 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2065 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2066 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2067 case options::OPT_fmath_errno: MathErrno = true; break;
2068 case options::OPT_fno_math_errno: MathErrno = false; break;
2069 case options::OPT_fassociative_math: AssociativeMath = true; break;
2070 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2071 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2072 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2073 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2074 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2075 case options::OPT_ftrapping_math: TrappingMath = true; break;
2076 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2077
2078 case options::OPT_fdenormal_fp_math_EQ:
2079 DenormalFPMath = A->getValue();
2080 break;
2081
2082 // Validate and pass through -fp-contract option.
2083 case options::OPT_ffp_contract: {
2084 StringRef Val = A->getValue();
2085 if (Val == "fast" || Val == "on" || Val == "off")
2086 FPContract = Val;
2087 else
2088 D.Diag(diag::err_drv_unsupported_option_argument)
2089 << A->getOption().getName() << Val;
2090 break;
2091 }
2092
2093 case options::OPT_ffinite_math_only:
2094 HonorINFs = false;
2095 HonorNaNs = false;
2096 break;
2097 case options::OPT_fno_finite_math_only:
2098 HonorINFs = true;
2099 HonorNaNs = true;
2100 break;
2101
2102 case options::OPT_funsafe_math_optimizations:
2103 AssociativeMath = true;
2104 ReciprocalMath = true;
2105 SignedZeros = false;
2106 TrappingMath = false;
2107 break;
2108 case options::OPT_fno_unsafe_math_optimizations:
2109 AssociativeMath = false;
2110 ReciprocalMath = false;
2111 SignedZeros = true;
2112 TrappingMath = true;
2113 // -fno_unsafe_math_optimizations restores default denormal handling
2114 DenormalFPMath = "";
2115 break;
2116
2117 case options::OPT_Ofast:
2118 // If -Ofast is the optimization level, then -ffast-math should be enabled
2119 if (!OFastEnabled)
2120 continue;
2121 LLVM_FALLTHROUGH;
2122 case options::OPT_ffast_math:
2123 HonorINFs = false;
2124 HonorNaNs = false;
2125 MathErrno = false;
2126 AssociativeMath = true;
2127 ReciprocalMath = true;
2128 SignedZeros = false;
2129 TrappingMath = false;
2130 // If fast-math is set then set the fp-contract mode to fast.
2131 FPContract = "fast";
2132 break;
2133 case options::OPT_fno_fast_math:
2134 HonorINFs = true;
2135 HonorNaNs = true;
2136 // Turning on -ffast-math (with either flag) removes the need for
2137 // MathErrno. However, turning *off* -ffast-math merely restores the
2138 // toolchain default (which may be false).
2139 MathErrno = TC.IsMathErrnoDefault();
2140 AssociativeMath = false;
2141 ReciprocalMath = false;
2142 SignedZeros = true;
2143 TrappingMath = true;
2144 // -fno_fast_math restores default denormal and fpcontract handling
2145 DenormalFPMath = "";
2146 FPContract = "";
2147 break;
2148 }
2149
2150 // If we handled this option claim it
2151 A->claim();
2152 }
2153
2154 if (!HonorINFs)
2155 CmdArgs.push_back("-menable-no-infs");
2156
2157 if (!HonorNaNs)
2158 CmdArgs.push_back("-menable-no-nans");
2159
2160 if (MathErrno)
2161 CmdArgs.push_back("-fmath-errno");
2162
2163 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2164 !TrappingMath)
2165 CmdArgs.push_back("-menable-unsafe-fp-math");
2166
2167 if (!SignedZeros)
2168 CmdArgs.push_back("-fno-signed-zeros");
2169
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002170 if (AssociativeMath && !SignedZeros && !TrappingMath)
2171 CmdArgs.push_back("-mreassociate");
2172
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002173 if (ReciprocalMath)
2174 CmdArgs.push_back("-freciprocal-math");
2175
2176 if (!TrappingMath)
2177 CmdArgs.push_back("-fno-trapping-math");
2178
2179 if (!DenormalFPMath.empty())
2180 CmdArgs.push_back(
2181 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2182
2183 if (!FPContract.empty())
2184 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2185
2186 ParseMRecip(D, Args, CmdArgs);
2187
2188 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2189 // individual features enabled by -ffast-math instead of the option itself as
2190 // that's consistent with gcc's behaviour.
2191 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2192 ReciprocalMath && !SignedZeros && !TrappingMath)
2193 CmdArgs.push_back("-ffast-math");
2194
2195 // Handle __FINITE_MATH_ONLY__ similarly.
2196 if (!HonorINFs && !HonorNaNs)
2197 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002198
2199 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2200 CmdArgs.push_back("-mfpmath");
2201 CmdArgs.push_back(A->getValue());
2202 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002203
2204 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002205 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2206 options::OPT_fstrict_float_cast_overflow, false))
2207 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002208}
2209
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002210static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2211 const llvm::Triple &Triple,
2212 const InputInfo &Input) {
2213 // Enable region store model by default.
2214 CmdArgs.push_back("-analyzer-store=region");
2215
2216 // Treat blocks as analysis entry points.
2217 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2218
2219 CmdArgs.push_back("-analyzer-eagerly-assume");
2220
2221 // Add default argument set.
2222 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2223 CmdArgs.push_back("-analyzer-checker=core");
2224 CmdArgs.push_back("-analyzer-checker=apiModeling");
2225
2226 if (!Triple.isWindowsMSVCEnvironment()) {
2227 CmdArgs.push_back("-analyzer-checker=unix");
2228 } else {
2229 // Enable "unix" checkers that also work on Windows.
2230 CmdArgs.push_back("-analyzer-checker=unix.API");
2231 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2232 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2233 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2234 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2235 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2236 }
2237
2238 // Disable some unix checkers for PS4.
2239 if (Triple.isPS4CPU()) {
2240 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2241 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2242 }
2243
2244 if (Triple.isOSDarwin())
2245 CmdArgs.push_back("-analyzer-checker=osx");
2246
2247 CmdArgs.push_back("-analyzer-checker=deadcode");
2248
2249 if (types::isCXX(Input.getType()))
2250 CmdArgs.push_back("-analyzer-checker=cplusplus");
2251
2252 if (!Triple.isPS4CPU()) {
2253 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2254 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2255 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2256 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2257 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2258 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2259 }
2260
2261 // Default nullability checks.
2262 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2263 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2264 }
2265
2266 // Set the output format. The default is plist, for (lame) historical reasons.
2267 CmdArgs.push_back("-analyzer-output");
2268 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2269 CmdArgs.push_back(A->getValue());
2270 else
2271 CmdArgs.push_back("plist");
2272
2273 // Disable the presentation of standard compiler warnings when using
2274 // --analyze. We only want to show static analyzer diagnostics or frontend
2275 // errors.
2276 CmdArgs.push_back("-w");
2277
2278 // Add -Xanalyzer arguments when running as analyzer.
2279 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2280}
2281
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002282static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002283 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002284 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2285
2286 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2287 // doesn't even have a stack!
2288 if (EffectiveTriple.isNVPTX())
2289 return;
2290
2291 // -stack-protector=0 is default.
2292 unsigned StackProtectorLevel = 0;
2293 unsigned DefaultStackProtectorLevel =
2294 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2295
2296 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2297 options::OPT_fstack_protector_all,
2298 options::OPT_fstack_protector_strong,
2299 options::OPT_fstack_protector)) {
2300 if (A->getOption().matches(options::OPT_fstack_protector))
2301 StackProtectorLevel =
2302 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2303 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2304 StackProtectorLevel = LangOptions::SSPStrong;
2305 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2306 StackProtectorLevel = LangOptions::SSPReq;
2307 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002308 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002309 }
2310
2311 if (StackProtectorLevel) {
2312 CmdArgs.push_back("-stack-protector");
2313 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2314 }
2315
2316 // --param ssp-buffer-size=
2317 for (const Arg *A : Args.filtered(options::OPT__param)) {
2318 StringRef Str(A->getValue());
2319 if (Str.startswith("ssp-buffer-size=")) {
2320 if (StackProtectorLevel) {
2321 CmdArgs.push_back("-stack-protector-buffer-size");
2322 // FIXME: Verify the argument is a valid integer.
2323 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2324 }
2325 A->claim();
2326 }
2327 }
2328}
2329
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002330static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2331 const unsigned ForwardedArguments[] = {
2332 options::OPT_cl_opt_disable,
2333 options::OPT_cl_strict_aliasing,
2334 options::OPT_cl_single_precision_constant,
2335 options::OPT_cl_finite_math_only,
2336 options::OPT_cl_kernel_arg_info,
2337 options::OPT_cl_unsafe_math_optimizations,
2338 options::OPT_cl_fast_relaxed_math,
2339 options::OPT_cl_mad_enable,
2340 options::OPT_cl_no_signed_zeros,
2341 options::OPT_cl_denorms_are_zero,
2342 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002343 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002344 };
2345
2346 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2347 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2348 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2349 }
2350
2351 for (const auto &Arg : ForwardedArguments)
2352 if (const auto *A = Args.getLastArg(Arg))
2353 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2354}
2355
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002356static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2357 ArgStringList &CmdArgs) {
2358 bool ARCMTEnabled = false;
2359 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2360 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2361 options::OPT_ccc_arcmt_modify,
2362 options::OPT_ccc_arcmt_migrate)) {
2363 ARCMTEnabled = true;
2364 switch (A->getOption().getID()) {
2365 default: llvm_unreachable("missed a case");
2366 case options::OPT_ccc_arcmt_check:
2367 CmdArgs.push_back("-arcmt-check");
2368 break;
2369 case options::OPT_ccc_arcmt_modify:
2370 CmdArgs.push_back("-arcmt-modify");
2371 break;
2372 case options::OPT_ccc_arcmt_migrate:
2373 CmdArgs.push_back("-arcmt-migrate");
2374 CmdArgs.push_back("-mt-migrate-directory");
2375 CmdArgs.push_back(A->getValue());
2376
2377 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2378 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2379 break;
2380 }
2381 }
2382 } else {
2383 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2384 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2385 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2386 }
2387
2388 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2389 if (ARCMTEnabled)
2390 D.Diag(diag::err_drv_argument_not_allowed_with)
2391 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2392
2393 CmdArgs.push_back("-mt-migrate-directory");
2394 CmdArgs.push_back(A->getValue());
2395
2396 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2397 options::OPT_objcmt_migrate_subscripting,
2398 options::OPT_objcmt_migrate_property)) {
2399 // None specified, means enable them all.
2400 CmdArgs.push_back("-objcmt-migrate-literals");
2401 CmdArgs.push_back("-objcmt-migrate-subscripting");
2402 CmdArgs.push_back("-objcmt-migrate-property");
2403 } else {
2404 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2405 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2406 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2407 }
2408 } else {
2409 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2410 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2411 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2412 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2413 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2414 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2415 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2416 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2417 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2418 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2419 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2420 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2421 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2422 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2423 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2424 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2425 }
2426}
2427
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002428static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2429 const ArgList &Args, ArgStringList &CmdArgs) {
2430 // -fbuiltin is default unless -mkernel is used.
2431 bool UseBuiltins =
2432 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2433 !Args.hasArg(options::OPT_mkernel));
2434 if (!UseBuiltins)
2435 CmdArgs.push_back("-fno-builtin");
2436
2437 // -ffreestanding implies -fno-builtin.
2438 if (Args.hasArg(options::OPT_ffreestanding))
2439 UseBuiltins = false;
2440
2441 // Process the -fno-builtin-* options.
2442 for (const auto &Arg : Args) {
2443 const Option &O = Arg->getOption();
2444 if (!O.matches(options::OPT_fno_builtin_))
2445 continue;
2446
2447 Arg->claim();
2448
2449 // If -fno-builtin is specified, then there's no need to pass the option to
2450 // the frontend.
2451 if (!UseBuiltins)
2452 continue;
2453
2454 StringRef FuncName = Arg->getValue();
2455 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2456 }
2457
2458 // le32-specific flags:
2459 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2460 // by default.
2461 if (TC.getArch() == llvm::Triple::le32)
2462 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002463}
2464
Adrian Prantl70599032018-02-09 18:43:10 +00002465void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2466 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2467 llvm::sys::path::append(Result, "org.llvm.clang.");
2468 appendUserToPath(Result);
2469 llvm::sys::path::append(Result, "ModuleCache");
2470}
2471
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002472static void RenderModulesOptions(Compilation &C, const Driver &D,
2473 const ArgList &Args, const InputInfo &Input,
2474 const InputInfo &Output,
2475 ArgStringList &CmdArgs, bool &HaveModules) {
2476 // -fmodules enables the use of precompiled modules (off by default).
2477 // Users can pass -fno-cxx-modules to turn off modules support for
2478 // C++/Objective-C++ programs.
2479 bool HaveClangModules = false;
2480 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2481 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2482 options::OPT_fno_cxx_modules, true);
2483 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2484 CmdArgs.push_back("-fmodules");
2485 HaveClangModules = true;
2486 }
2487 }
2488
2489 HaveModules = HaveClangModules;
2490 if (Args.hasArg(options::OPT_fmodules_ts)) {
2491 CmdArgs.push_back("-fmodules-ts");
2492 HaveModules = true;
2493 }
2494
2495 // -fmodule-maps enables implicit reading of module map files. By default,
2496 // this is enabled if we are using Clang's flavor of precompiled modules.
2497 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2498 options::OPT_fno_implicit_module_maps, HaveClangModules))
2499 CmdArgs.push_back("-fimplicit-module-maps");
2500
2501 // -fmodules-decluse checks that modules used are declared so (off by default)
2502 if (Args.hasFlag(options::OPT_fmodules_decluse,
2503 options::OPT_fno_modules_decluse, false))
2504 CmdArgs.push_back("-fmodules-decluse");
2505
2506 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2507 // all #included headers are part of modules.
2508 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2509 options::OPT_fno_modules_strict_decluse, false))
2510 CmdArgs.push_back("-fmodules-strict-decluse");
2511
2512 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002513 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002514 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2515 options::OPT_fno_implicit_modules, HaveClangModules)) {
2516 if (HaveModules)
2517 CmdArgs.push_back("-fno-implicit-modules");
2518 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002519 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002520 // -fmodule-cache-path specifies where our implicitly-built module files
2521 // should be written.
2522 SmallString<128> Path;
2523 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2524 Path = A->getValue();
2525
2526 if (C.isForDiagnostics()) {
2527 // When generating crash reports, we want to emit the modules along with
2528 // the reproduction sources, so we ignore any provided module path.
2529 Path = Output.getFilename();
2530 llvm::sys::path::replace_extension(Path, ".cache");
2531 llvm::sys::path::append(Path, "modules");
2532 } else if (Path.empty()) {
2533 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002534 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002535 }
2536
2537 const char Arg[] = "-fmodules-cache-path=";
2538 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2539 CmdArgs.push_back(Args.MakeArgString(Path));
2540 }
2541
2542 if (HaveModules) {
2543 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2544 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2545 CmdArgs.push_back(Args.MakeArgString(
2546 std::string("-fprebuilt-module-path=") + A->getValue()));
2547 A->claim();
2548 }
2549 }
2550
2551 // -fmodule-name specifies the module that is currently being built (or
2552 // used for header checking by -fmodule-maps).
2553 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2554
2555 // -fmodule-map-file can be used to specify files containing module
2556 // definitions.
2557 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2558
2559 // -fbuiltin-module-map can be used to load the clang
2560 // builtin headers modulemap file.
2561 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2562 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2563 llvm::sys::path::append(BuiltinModuleMap, "include");
2564 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2565 if (llvm::sys::fs::exists(BuiltinModuleMap))
2566 CmdArgs.push_back(
2567 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2568 }
2569
2570 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2571 // names to precompiled module files (the module is loaded only if used).
2572 // The -fmodule-file=<file> form can be used to unconditionally load
2573 // precompiled module files (whether used or not).
2574 if (HaveModules)
2575 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2576 else
2577 Args.ClaimAllArgs(options::OPT_fmodule_file);
2578
2579 // When building modules and generating crashdumps, we need to dump a module
2580 // dependency VFS alongside the output.
2581 if (HaveClangModules && C.isForDiagnostics()) {
2582 SmallString<128> VFSDir(Output.getFilename());
2583 llvm::sys::path::replace_extension(VFSDir, ".cache");
2584 // Add the cache directory as a temp so the crash diagnostics pick it up.
2585 C.addTempFile(Args.MakeArgString(VFSDir));
2586
2587 llvm::sys::path::append(VFSDir, "vfs");
2588 CmdArgs.push_back("-module-dependency-dir");
2589 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2590 }
2591
2592 if (HaveClangModules)
2593 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2594
2595 // Pass through all -fmodules-ignore-macro arguments.
2596 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2597 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2598 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2599
2600 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2601
2602 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2603 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2604 D.Diag(diag::err_drv_argument_not_allowed_with)
2605 << A->getAsString(Args) << "-fbuild-session-timestamp";
2606
2607 llvm::sys::fs::file_status Status;
2608 if (llvm::sys::fs::status(A->getValue(), Status))
2609 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2610 CmdArgs.push_back(
2611 Args.MakeArgString("-fbuild-session-timestamp=" +
2612 Twine((uint64_t)Status.getLastModificationTime()
2613 .time_since_epoch()
2614 .count())));
2615 }
2616
2617 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2618 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2619 options::OPT_fbuild_session_file))
2620 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2621
2622 Args.AddLastArg(CmdArgs,
2623 options::OPT_fmodules_validate_once_per_build_session);
2624 }
2625
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002626 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2627 options::OPT_fno_modules_validate_system_headers,
2628 ImplicitModules))
2629 CmdArgs.push_back("-fmodules-validate-system-headers");
2630
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002631 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2632}
2633
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002634static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2635 ArgStringList &CmdArgs) {
2636 // -fsigned-char is default.
2637 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2638 options::OPT_fno_signed_char,
2639 options::OPT_funsigned_char,
2640 options::OPT_fno_unsigned_char)) {
2641 if (A->getOption().matches(options::OPT_funsigned_char) ||
2642 A->getOption().matches(options::OPT_fno_signed_char)) {
2643 CmdArgs.push_back("-fno-signed-char");
2644 }
2645 } else if (!isSignedCharDefault(T)) {
2646 CmdArgs.push_back("-fno-signed-char");
2647 }
2648
Richard Smith3a8244d2018-05-01 05:02:45 +00002649 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2650 CmdArgs.push_back("-fchar8_t");
2651
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002652 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2653 options::OPT_fno_short_wchar)) {
2654 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2655 CmdArgs.push_back("-fwchar-type=short");
2656 CmdArgs.push_back("-fno-signed-wchar");
2657 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002658 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002659 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002660 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2661 T.getOS() == llvm::Triple::OpenBSD))
2662 CmdArgs.push_back("-fno-signed-wchar");
2663 else
2664 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002665 }
2666 }
2667}
2668
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002669static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2670 const llvm::Triple &T, const ArgList &Args,
2671 ObjCRuntime &Runtime, bool InferCovariantReturns,
2672 const InputInfo &Input, ArgStringList &CmdArgs) {
2673 const llvm::Triple::ArchType Arch = TC.getArch();
2674
2675 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2676 // is the default. Except for deployment target of 10.5, next runtime is
2677 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2678 if (Runtime.isNonFragile()) {
2679 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2680 options::OPT_fno_objc_legacy_dispatch,
2681 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2682 if (TC.UseObjCMixedDispatch())
2683 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2684 else
2685 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2686 }
2687 }
2688
2689 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2690 // to do Array/Dictionary subscripting by default.
2691 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2692 !T.isMacOSXVersionLT(10, 7) &&
2693 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2694 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2695
2696 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2697 // NOTE: This logic is duplicated in ToolChains.cpp.
2698 if (isObjCAutoRefCount(Args)) {
2699 TC.CheckObjCARC();
2700
2701 CmdArgs.push_back("-fobjc-arc");
2702
2703 // FIXME: It seems like this entire block, and several around it should be
2704 // wrapped in isObjC, but for now we just use it here as this is where it
2705 // was being used previously.
2706 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2707 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2708 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2709 else
2710 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2711 }
2712
2713 // Allow the user to enable full exceptions code emission.
2714 // We default off for Objective-C, on for Objective-C++.
2715 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2716 options::OPT_fno_objc_arc_exceptions,
2717 /*default=*/types::isCXX(Input.getType())))
2718 CmdArgs.push_back("-fobjc-arc-exceptions");
2719 }
2720
2721 // Silence warning for full exception code emission options when explicitly
2722 // set to use no ARC.
2723 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2724 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2725 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2726 }
2727
2728 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2729 // rewriter.
2730 if (InferCovariantReturns)
2731 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2732
2733 // Pass down -fobjc-weak or -fno-objc-weak if present.
2734 if (types::isObjC(Input.getType())) {
2735 auto WeakArg =
2736 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2737 if (!WeakArg) {
2738 // nothing to do
2739 } else if (!Runtime.allowsWeak()) {
2740 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2741 D.Diag(diag::err_objc_weak_unsupported);
2742 } else {
2743 WeakArg->render(Args, CmdArgs);
2744 }
2745 }
2746}
2747
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002748static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2749 ArgStringList &CmdArgs) {
2750 bool CaretDefault = true;
2751 bool ColumnDefault = true;
2752
2753 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2754 options::OPT__SLASH_diagnostics_column,
2755 options::OPT__SLASH_diagnostics_caret)) {
2756 switch (A->getOption().getID()) {
2757 case options::OPT__SLASH_diagnostics_caret:
2758 CaretDefault = true;
2759 ColumnDefault = true;
2760 break;
2761 case options::OPT__SLASH_diagnostics_column:
2762 CaretDefault = false;
2763 ColumnDefault = true;
2764 break;
2765 case options::OPT__SLASH_diagnostics_classic:
2766 CaretDefault = false;
2767 ColumnDefault = false;
2768 break;
2769 }
2770 }
2771
2772 // -fcaret-diagnostics is default.
2773 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2774 options::OPT_fno_caret_diagnostics, CaretDefault))
2775 CmdArgs.push_back("-fno-caret-diagnostics");
2776
2777 // -fdiagnostics-fixit-info is default, only pass non-default.
2778 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2779 options::OPT_fno_diagnostics_fixit_info))
2780 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2781
2782 // Enable -fdiagnostics-show-option by default.
2783 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2784 options::OPT_fno_diagnostics_show_option))
2785 CmdArgs.push_back("-fdiagnostics-show-option");
2786
2787 if (const Arg *A =
2788 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2789 CmdArgs.push_back("-fdiagnostics-show-category");
2790 CmdArgs.push_back(A->getValue());
2791 }
2792
2793 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2794 options::OPT_fno_diagnostics_show_hotness, false))
2795 CmdArgs.push_back("-fdiagnostics-show-hotness");
2796
2797 if (const Arg *A =
2798 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2799 std::string Opt =
2800 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2801 CmdArgs.push_back(Args.MakeArgString(Opt));
2802 }
2803
2804 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2805 CmdArgs.push_back("-fdiagnostics-format");
2806 CmdArgs.push_back(A->getValue());
2807 }
2808
2809 if (const Arg *A = Args.getLastArg(
2810 options::OPT_fdiagnostics_show_note_include_stack,
2811 options::OPT_fno_diagnostics_show_note_include_stack)) {
2812 const Option &O = A->getOption();
2813 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2814 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2815 else
2816 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2817 }
2818
2819 // Color diagnostics are parsed by the driver directly from argv and later
2820 // re-parsed to construct this job; claim any possible color diagnostic here
2821 // to avoid warn_drv_unused_argument and diagnose bad
2822 // OPT_fdiagnostics_color_EQ values.
2823 for (const Arg *A : Args) {
2824 const Option &O = A->getOption();
2825 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2826 !O.matches(options::OPT_fdiagnostics_color) &&
2827 !O.matches(options::OPT_fno_color_diagnostics) &&
2828 !O.matches(options::OPT_fno_diagnostics_color) &&
2829 !O.matches(options::OPT_fdiagnostics_color_EQ))
2830 continue;
2831
2832 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2833 StringRef Value(A->getValue());
2834 if (Value != "always" && Value != "never" && Value != "auto")
2835 D.Diag(diag::err_drv_clang_unsupported)
2836 << ("-fdiagnostics-color=" + Value).str();
2837 }
2838 A->claim();
2839 }
2840
2841 if (D.getDiags().getDiagnosticOptions().ShowColors)
2842 CmdArgs.push_back("-fcolor-diagnostics");
2843
2844 if (Args.hasArg(options::OPT_fansi_escape_codes))
2845 CmdArgs.push_back("-fansi-escape-codes");
2846
2847 if (!Args.hasFlag(options::OPT_fshow_source_location,
2848 options::OPT_fno_show_source_location))
2849 CmdArgs.push_back("-fno-show-source-location");
2850
2851 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2852 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2853
2854 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2855 ColumnDefault))
2856 CmdArgs.push_back("-fno-show-column");
2857
2858 if (!Args.hasFlag(options::OPT_fspell_checking,
2859 options::OPT_fno_spell_checking))
2860 CmdArgs.push_back("-fno-spell-checking");
2861}
2862
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002863static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2864 const llvm::Triple &T, const ArgList &Args,
2865 bool EmitCodeView, bool IsWindowsMSVC,
2866 ArgStringList &CmdArgs,
2867 codegenoptions::DebugInfoKind &DebugInfoKind,
2868 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002869 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2870 options::OPT_fno_debug_info_for_profiling, false))
2871 CmdArgs.push_back("-fdebug-info-for-profiling");
2872
2873 // The 'g' groups options involve a somewhat intricate sequence of decisions
2874 // about what to pass from the driver to the frontend, but by the time they
2875 // reach cc1 they've been factored into three well-defined orthogonal choices:
2876 // * what level of debug info to generate
2877 // * what dwarf version to write
2878 // * what debugger tuning to use
2879 // This avoids having to monkey around further in cc1 other than to disable
2880 // codeview if not running in a Windows environment. Perhaps even that
2881 // decision should be made in the driver as well though.
2882 unsigned DWARFVersion = 0;
2883 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2884
2885 bool SplitDWARFInlining =
2886 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2887 options::OPT_fno_split_dwarf_inlining, true);
2888
2889 Args.ClaimAllArgs(options::OPT_g_Group);
2890
2891 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2892
2893 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2894 // If the last option explicitly specified a debug-info level, use it.
2895 if (A->getOption().matches(options::OPT_gN_Group)) {
2896 DebugInfoKind = DebugLevelToInfoKind(*A);
2897 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2898 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2899 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2900 // This gets a bit more complicated if you've disabled inline info in the
2901 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2902 // split-dwarf and line-tables-only, so let those compose naturally in
2903 // that case.
2904 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2905 if (SplitDWARFArg) {
2906 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2907 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2908 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2909 SplitDWARFInlining))
2910 SplitDWARFArg = nullptr;
2911 } else if (SplitDWARFInlining)
2912 DebugInfoKind = codegenoptions::NoDebugInfo;
2913 }
2914 } else {
2915 // For any other 'g' option, use Limited.
2916 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2917 }
2918 }
2919
2920 // If a debugger tuning argument appeared, remember it.
2921 if (const Arg *A =
2922 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2923 if (A->getOption().matches(options::OPT_glldb))
2924 DebuggerTuning = llvm::DebuggerKind::LLDB;
2925 else if (A->getOption().matches(options::OPT_gsce))
2926 DebuggerTuning = llvm::DebuggerKind::SCE;
2927 else
2928 DebuggerTuning = llvm::DebuggerKind::GDB;
2929 }
2930
2931 // If a -gdwarf argument appeared, remember it.
2932 if (const Arg *A =
2933 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2934 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2935 DWARFVersion = DwarfVersionNum(A->getSpelling());
2936
2937 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2938 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002939 if (EmitCodeView) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002940 // DWARFVersion remains at 0 if no explicit choice was made.
2941 CmdArgs.push_back("-gcodeview");
2942 } else if (DWARFVersion == 0 &&
2943 DebugInfoKind != codegenoptions::NoDebugInfo) {
2944 DWARFVersion = TC.GetDefaultDwarfVersion();
2945 }
2946
2947 // We ignore flag -gstrict-dwarf for now.
2948 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2949 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2950
Paul Robinsona8280812017-09-29 21:25:07 +00002951 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002952 // Clang doesn't track end columns, just starting columns, which, in theory,
2953 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2954 // debuggers don't handle missing end columns well, so it's better not to
2955 // include any column info.
2956 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002957 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002958 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002959 CmdArgs.push_back("-dwarf-column-info");
2960
2961 // FIXME: Move backend command line options to the module.
2962 // If -gline-tables-only is the last option it wins.
2963 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2964 Args.hasArg(options::OPT_gmodules)) {
2965 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2966 CmdArgs.push_back("-dwarf-ext-refs");
2967 CmdArgs.push_back("-fmodule-format=obj");
2968 }
2969
2970 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2971 // splitting and extraction.
2972 // FIXME: Currently only works on Linux.
2973 if (T.isOSLinux()) {
2974 if (!SplitDWARFInlining)
2975 CmdArgs.push_back("-fno-split-dwarf-inlining");
2976
2977 if (SplitDWARFArg) {
2978 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2979 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2980 CmdArgs.push_back("-enable-split-dwarf");
2981 }
2982 }
2983
2984 // After we've dealt with all combinations of things that could
2985 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2986 // figure out if we need to "upgrade" it to standalone debug info.
2987 // We parse these two '-f' options whether or not they will be used,
2988 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2989 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2990 options::OPT_fno_standalone_debug,
2991 TC.GetDefaultStandaloneDebug());
2992 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2993 DebugInfoKind = codegenoptions::FullDebugInfo;
2994
Scott Lindera2fbcef2018-02-26 17:32:31 +00002995 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) {
2996 // Source embedding is a vendor extension to DWARF v5. By now we have
2997 // checked if a DWARF version was stated explicitly, and have otherwise
2998 // fallen back to the target default, so if this is still not at least 5 we
2999 // emit an error.
3000 if (DWARFVersion < 5)
3001 D.Diag(diag::err_drv_argument_only_allowed_with)
3002 << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args)
3003 << "-gdwarf-5";
3004 CmdArgs.push_back("-gembed-source");
3005 }
3006
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003007 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3008 DebuggerTuning);
3009
3010 // -fdebug-macro turns on macro debug info generation.
3011 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3012 false))
3013 CmdArgs.push_back("-debug-info-macro");
3014
3015 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikiecb7b6af2018-06-28 22:58:04 +00003016 if (Args.hasFlag(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3017 false))
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003018 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003019
3020 // -gdwarf-aranges turns on the emission of the aranges section in the
3021 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003022 // Always enabled for SCE tuning.
3023 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3024 DebuggerTuning == llvm::DebuggerKind::SCE) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003025 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003026 CmdArgs.push_back("-generate-arange-section");
3027 }
3028
3029 if (Args.hasFlag(options::OPT_fdebug_types_section,
3030 options::OPT_fno_debug_types_section, false)) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003031 if (!T.isOSBinFormatELF())
3032 D.Diag(diag::err_drv_unsupported_opt_for_target)
3033 << Args.getLastArg(options::OPT_fdebug_types_section)
3034 ->getAsString(Args)
3035 << T.getTriple();
Eli Friedman01d349b2018-04-12 22:21:36 +00003036 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003037 CmdArgs.push_back("-generate-type-units");
3038 }
3039
Paul Robinson1787f812017-09-28 18:37:02 +00003040 // Decide how to render forward declarations of template instantiations.
3041 // SCE wants full descriptions, others just get them in the name.
3042 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3043 CmdArgs.push_back("-debug-forward-template-params");
3044
Paul Robinsona8280812017-09-29 21:25:07 +00003045 // Do we need to explicitly import anonymous namespaces into the parent scope?
3046 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3047 CmdArgs.push_back("-dwarf-explicit-import");
3048
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003049 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3050}
3051
David L. Jonesf561aba2017-03-08 01:02:16 +00003052void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3053 const InputInfo &Output, const InputInfoList &Inputs,
3054 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003055 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003056 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3057 const std::string &TripleStr = Triple.getTriple();
3058
3059 bool KernelOrKext =
3060 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3061 const Driver &D = getToolChain().getDriver();
3062 ArgStringList CmdArgs;
3063
3064 // Check number of inputs for sanity. We need at least one input.
3065 assert(Inputs.size() >= 1 && "Must have at least one input.");
3066 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003067 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003068 // device-side compilations). OpenMP device jobs also take the host IR as a
3069 // second input. All other jobs are expected to have exactly one
3070 // input.
3071 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003072 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003073 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003074 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003075 Inputs.size() == 1) &&
3076 "Unable to handle multiple inputs.");
3077
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003078 const llvm::Triple *AuxTriple =
3079 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3080
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003081 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3082 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3083 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003084 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003085
Yaxun Liu398612b2018-05-08 21:02:12 +00003086 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3087 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3088 // Windows), we need to pass Windows-specific flags to cc1.
3089 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003090 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3091 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3092 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3093 }
3094
3095 // C++ is not supported for IAMCU.
3096 if (IsIAMCU && types::isCXX(Input.getType()))
3097 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3098
3099 // Invoke ourselves in -cc1 mode.
3100 //
3101 // FIXME: Implement custom jobs for internal actions.
3102 CmdArgs.push_back("-cc1");
3103
3104 // Add the "effective" target triple.
3105 CmdArgs.push_back("-triple");
3106 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3107
3108 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3109 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3110 Args.ClaimAllArgs(options::OPT_MJ);
3111 }
3112
Yaxun Liu398612b2018-05-08 21:02:12 +00003113 if (IsCuda || IsHIP) {
3114 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3115 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003116 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003117 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3118 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003119 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3120 ->getTriple()
3121 .normalize();
3122 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003123 NormalizedTriple =
3124 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3125 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3126 ->getTriple()
3127 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003128
3129 CmdArgs.push_back("-aux-triple");
3130 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3131 }
3132
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003133 if (IsOpenMPDevice) {
3134 // We have to pass the triple of the host if compiling for an OpenMP device.
3135 std::string NormalizedTriple =
3136 C.getSingleOffloadToolChain<Action::OFK_Host>()
3137 ->getTriple()
3138 .normalize();
3139 CmdArgs.push_back("-aux-triple");
3140 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3141 }
3142
David L. Jonesf561aba2017-03-08 01:02:16 +00003143 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3144 Triple.getArch() == llvm::Triple::thumb)) {
3145 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3146 unsigned Version;
3147 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3148 if (Version < 7)
3149 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3150 << TripleStr;
3151 }
3152
3153 // Push all default warning arguments that are specific to
3154 // the given target. These come before user provided warning options
3155 // are provided.
3156 getToolChain().addClangWarningOptions(CmdArgs);
3157
3158 // Select the appropriate action.
3159 RewriteKind rewriteKind = RK_None;
3160
3161 if (isa<AnalyzeJobAction>(JA)) {
3162 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3163 CmdArgs.push_back("-analyze");
3164 } else if (isa<MigrateJobAction>(JA)) {
3165 CmdArgs.push_back("-migrate");
3166 } else if (isa<PreprocessJobAction>(JA)) {
3167 if (Output.getType() == types::TY_Dependencies)
3168 CmdArgs.push_back("-Eonly");
3169 else {
3170 CmdArgs.push_back("-E");
3171 if (Args.hasArg(options::OPT_rewrite_objc) &&
3172 !Args.hasArg(options::OPT_g_Group))
3173 CmdArgs.push_back("-P");
3174 }
3175 } else if (isa<AssembleJobAction>(JA)) {
3176 CmdArgs.push_back("-emit-obj");
3177
3178 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3179
3180 // Also ignore explicit -force_cpusubtype_ALL option.
3181 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3182 } else if (isa<PrecompileJobAction>(JA)) {
3183 // Use PCH if the user requested it.
3184 bool UsePCH = D.CCCUsePCH;
3185
3186 if (JA.getType() == types::TY_Nothing)
3187 CmdArgs.push_back("-fsyntax-only");
3188 else if (JA.getType() == types::TY_ModuleFile)
3189 CmdArgs.push_back("-emit-module-interface");
3190 else if (UsePCH)
3191 CmdArgs.push_back("-emit-pch");
3192 else
3193 CmdArgs.push_back("-emit-pth");
3194 } else if (isa<VerifyPCHJobAction>(JA)) {
3195 CmdArgs.push_back("-verify-pch");
3196 } else {
3197 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3198 "Invalid action for clang tool.");
3199 if (JA.getType() == types::TY_Nothing) {
3200 CmdArgs.push_back("-fsyntax-only");
3201 } else if (JA.getType() == types::TY_LLVM_IR ||
3202 JA.getType() == types::TY_LTO_IR) {
3203 CmdArgs.push_back("-emit-llvm");
3204 } else if (JA.getType() == types::TY_LLVM_BC ||
3205 JA.getType() == types::TY_LTO_BC) {
3206 CmdArgs.push_back("-emit-llvm-bc");
3207 } else if (JA.getType() == types::TY_PP_Asm) {
3208 CmdArgs.push_back("-S");
3209 } else if (JA.getType() == types::TY_AST) {
3210 CmdArgs.push_back("-emit-pch");
3211 } else if (JA.getType() == types::TY_ModuleFile) {
3212 CmdArgs.push_back("-module-file-info");
3213 } else if (JA.getType() == types::TY_RewrittenObjC) {
3214 CmdArgs.push_back("-rewrite-objc");
3215 rewriteKind = RK_NonFragile;
3216 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3217 CmdArgs.push_back("-rewrite-objc");
3218 rewriteKind = RK_Fragile;
3219 } else {
3220 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3221 }
3222
3223 // Preserve use-list order by default when emitting bitcode, so that
3224 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3225 // same result as running passes here. For LTO, we don't need to preserve
3226 // the use-list order, since serialization to bitcode is part of the flow.
3227 if (JA.getType() == types::TY_LLVM_BC)
3228 CmdArgs.push_back("-emit-llvm-uselists");
3229
Artem Belevichecb178b2018-03-21 22:22:59 +00003230 // Device-side jobs do not support LTO.
3231 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3232 JA.isDeviceOffloading(Action::OFK_Host));
3233
3234 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003235 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3236
Paul Robinsond23f2a82017-07-13 21:25:47 +00003237 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3238 // does not support LTO unit features (CFI, whole program vtable opt)
3239 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003240 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003241 D.getLTOMode() == LTOK_Full)
3242 CmdArgs.push_back("-flto-unit");
3243 }
3244 }
3245
3246 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3247 if (!types::isLLVMIR(Input.getType()))
3248 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3249 << "-x ir";
3250 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3251 }
3252
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003253 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003254 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3255
David L. Jonesf561aba2017-03-08 01:02:16 +00003256 // Embed-bitcode option.
3257 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3258 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3259 // Add flags implied by -fembed-bitcode.
3260 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3261 // Disable all llvm IR level optimizations.
3262 CmdArgs.push_back("-disable-llvm-passes");
3263 }
3264 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3265 CmdArgs.push_back("-fembed-bitcode=marker");
3266
3267 // We normally speed up the clang process a bit by skipping destructors at
3268 // exit, but when we're generating diagnostics we can rely on some of the
3269 // cleanup.
3270 if (!C.isForDiagnostics())
3271 CmdArgs.push_back("-disable-free");
3272
David L. Jonesf561aba2017-03-08 01:02:16 +00003273#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003274 const bool IsAssertBuild = false;
3275#else
3276 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003277#endif
3278
Eric Fiselier123c7492018-02-07 18:36:51 +00003279 // Disable the verification pass in -asserts builds.
3280 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003281 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003282
3283 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003284 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3285 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003286 CmdArgs.push_back("-discard-value-names");
3287
David L. Jonesf561aba2017-03-08 01:02:16 +00003288 // Set the main file name, so that debug info works even with
3289 // -save-temps.
3290 CmdArgs.push_back("-main-file-name");
3291 CmdArgs.push_back(getBaseInputName(Args, Input));
3292
3293 // Some flags which affect the language (via preprocessor
3294 // defines).
3295 if (Args.hasArg(options::OPT_static))
3296 CmdArgs.push_back("-static-define");
3297
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003298 if (isa<AnalyzeJobAction>(JA))
3299 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003300
3301 CheckCodeGenerationOptions(D, Args);
3302
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003303 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3304 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3305 if (FunctionAlignment) {
3306 CmdArgs.push_back("-function-alignment");
3307 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3308 }
3309
David L. Jonesf561aba2017-03-08 01:02:16 +00003310 llvm::Reloc::Model RelocationModel;
3311 unsigned PICLevel;
3312 bool IsPIE;
3313 std::tie(RelocationModel, PICLevel, IsPIE) =
3314 ParsePICArgs(getToolChain(), Args);
3315
3316 const char *RMName = RelocationModelName(RelocationModel);
3317
3318 if ((RelocationModel == llvm::Reloc::ROPI ||
3319 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3320 types::isCXX(Input.getType()) &&
3321 !Args.hasArg(options::OPT_fallow_unsupported))
3322 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3323
3324 if (RMName) {
3325 CmdArgs.push_back("-mrelocation-model");
3326 CmdArgs.push_back(RMName);
3327 }
3328 if (PICLevel > 0) {
3329 CmdArgs.push_back("-pic-level");
3330 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3331 if (IsPIE)
3332 CmdArgs.push_back("-pic-is-pie");
3333 }
3334
3335 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3336 CmdArgs.push_back("-meabi");
3337 CmdArgs.push_back(A->getValue());
3338 }
3339
3340 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003341 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3342 if (!getToolChain().isThreadModelSupported(A->getValue()))
3343 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3344 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003345 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003346 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003347 else
3348 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3349
3350 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3351
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003352 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3353 options::OPT_fno_merge_all_constants, false))
3354 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003355
Manoj Guptada08f6a2018-07-19 00:44:52 +00003356 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3357 options::OPT_fdelete_null_pointer_checks, false))
3358 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3359
David L. Jonesf561aba2017-03-08 01:02:16 +00003360 // LLVM Code Generator Options.
3361
3362 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3363 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3364 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3365 options::OPT_frewrite_map_file_EQ)) {
3366 StringRef Map = A->getValue();
3367 if (!llvm::sys::fs::exists(Map)) {
3368 D.Diag(diag::err_drv_no_such_file) << Map;
3369 } else {
3370 CmdArgs.push_back("-frewrite-map-file");
3371 CmdArgs.push_back(A->getValue());
3372 A->claim();
3373 }
3374 }
3375 }
3376
3377 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3378 StringRef v = A->getValue();
3379 CmdArgs.push_back("-mllvm");
3380 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3381 A->claim();
3382 }
3383
3384 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3385 true))
3386 CmdArgs.push_back("-fno-jump-tables");
3387
Dehao Chen5e97f232017-08-24 21:37:33 +00003388 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3389 options::OPT_fno_profile_sample_accurate, false))
3390 CmdArgs.push_back("-fprofile-sample-accurate");
3391
David L. Jonesf561aba2017-03-08 01:02:16 +00003392 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3393 options::OPT_fno_preserve_as_comments, true))
3394 CmdArgs.push_back("-fno-preserve-as-comments");
3395
3396 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3397 CmdArgs.push_back("-mregparm");
3398 CmdArgs.push_back(A->getValue());
3399 }
3400
3401 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3402 options::OPT_freg_struct_return)) {
3403 if (getToolChain().getArch() != llvm::Triple::x86) {
3404 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003405 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003406 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3407 CmdArgs.push_back("-fpcc-struct-return");
3408 } else {
3409 assert(A->getOption().matches(options::OPT_freg_struct_return));
3410 CmdArgs.push_back("-freg-struct-return");
3411 }
3412 }
3413
3414 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3415 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3416
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003417 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003418 CmdArgs.push_back("-mdisable-fp-elim");
3419 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3420 options::OPT_fno_zero_initialized_in_bss))
3421 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3422
3423 bool OFastEnabled = isOptimizationLevelFast(Args);
3424 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3425 // enabled. This alias option is being used to simplify the hasFlag logic.
3426 OptSpecifier StrictAliasingAliasOption =
3427 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3428 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3429 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003430 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3432 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3433 CmdArgs.push_back("-relaxed-aliasing");
3434 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3435 options::OPT_fno_struct_path_tbaa))
3436 CmdArgs.push_back("-no-struct-path-tbaa");
3437 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3438 false))
3439 CmdArgs.push_back("-fstrict-enums");
3440 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3441 true))
3442 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003443 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3444 options::OPT_fno_allow_editor_placeholders, false))
3445 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003446 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3447 options::OPT_fno_strict_vtable_pointers,
3448 false))
3449 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003450 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3451 options::OPT_fno_force_emit_vtables,
3452 false))
3453 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003454 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3455 options::OPT_fno_optimize_sibling_calls))
3456 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003457 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003458 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003459 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003460
Wei Mi9b3d6272017-10-16 16:50:27 +00003461 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3462 options::OPT_fno_fine_grained_bitfield_accesses);
3463
David L. Jonesf561aba2017-03-08 01:02:16 +00003464 // Handle segmented stacks.
3465 if (Args.hasArg(options::OPT_fsplit_stack))
3466 CmdArgs.push_back("-split-stacks");
3467
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003468 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003469
3470 // Decide whether to use verbose asm. Verbose assembly is the default on
3471 // toolchains which have the integrated assembler on by default.
3472 bool IsIntegratedAssemblerDefault =
3473 getToolChain().IsIntegratedAssemblerDefault();
3474 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3475 IsIntegratedAssemblerDefault) ||
3476 Args.hasArg(options::OPT_dA))
3477 CmdArgs.push_back("-masm-verbose");
3478
Peter Collingbourned86ca942018-06-14 00:03:41 +00003479 if (!getToolChain().useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003480 CmdArgs.push_back("-no-integrated-as");
3481
3482 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3483 CmdArgs.push_back("-mdebug-pass");
3484 CmdArgs.push_back("Structure");
3485 }
3486 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3487 CmdArgs.push_back("-mdebug-pass");
3488 CmdArgs.push_back("Arguments");
3489 }
3490
3491 // Enable -mconstructor-aliases except on darwin, where we have to work around
3492 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3493 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003494 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003495 CmdArgs.push_back("-mconstructor-aliases");
3496
3497 // Darwin's kernel doesn't support guard variables; just die if we
3498 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003499 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003500 CmdArgs.push_back("-fforbid-guard-variables");
3501
3502 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3503 false)) {
3504 CmdArgs.push_back("-mms-bitfields");
3505 }
3506
3507 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3508 options::OPT_mno_pie_copy_relocations,
3509 false)) {
3510 CmdArgs.push_back("-mpie-copy-relocations");
3511 }
3512
Sriraman Tallam5c651482017-11-07 19:37:51 +00003513 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3514 CmdArgs.push_back("-fno-plt");
3515 }
3516
Vedant Kumardf502592017-09-12 22:51:53 +00003517 // -fhosted is default.
3518 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3519 // use Freestanding.
3520 bool Freestanding =
3521 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3522 KernelOrKext;
3523 if (Freestanding)
3524 CmdArgs.push_back("-ffreestanding");
3525
David L. Jonesf561aba2017-03-08 01:02:16 +00003526 // This is a coarse approximation of what llvm-gcc actually does, both
3527 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3528 // complicated ways.
3529 bool AsynchronousUnwindTables =
3530 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3531 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003532 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003533 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003534 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003535 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3536 AsynchronousUnwindTables))
3537 CmdArgs.push_back("-munwind-tables");
3538
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003539 getToolChain().addClangTargetOptions(Args, CmdArgs,
3540 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003541
3542 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3543 CmdArgs.push_back("-mlimit-float-precision");
3544 CmdArgs.push_back(A->getValue());
3545 }
3546
3547 // FIXME: Handle -mtune=.
3548 (void)Args.hasArg(options::OPT_mtune_EQ);
3549
3550 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3551 CmdArgs.push_back("-mcode-model");
3552 CmdArgs.push_back(A->getValue());
3553 }
3554
3555 // Add the target cpu
3556 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3557 if (!CPU.empty()) {
3558 CmdArgs.push_back("-target-cpu");
3559 CmdArgs.push_back(Args.MakeArgString(CPU));
3560 }
3561
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003562 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003563
David L. Jonesf561aba2017-03-08 01:02:16 +00003564 // These two are potentially updated by AddClangCLArgs.
3565 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3566 bool EmitCodeView = false;
3567
3568 // Add clang-cl arguments.
3569 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003570 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003571 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003572 else
3573 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003574
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003575 const Arg *SplitDWARFArg = nullptr;
3576 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3577 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3578
3579 // Add the split debug info name to the command lines here so we
3580 // can propagate it to the backend.
3581 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3582 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3583 isa<BackendJobAction>(JA));
3584 const char *SplitDWARFOut;
3585 if (SplitDWARF) {
3586 CmdArgs.push_back("-split-dwarf-file");
3587 SplitDWARFOut = SplitDebugName(Args, Input);
3588 CmdArgs.push_back(SplitDWARFOut);
3589 }
3590
David L. Jonesf561aba2017-03-08 01:02:16 +00003591 // Pass the linker version in use.
3592 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3593 CmdArgs.push_back("-target-linker-version");
3594 CmdArgs.push_back(A->getValue());
3595 }
3596
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003597 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003598 CmdArgs.push_back("-momit-leaf-frame-pointer");
3599
3600 // Explicitly error on some things we know we don't support and can't just
3601 // ignore.
3602 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3603 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003604 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003605 getToolChain().getArch() == llvm::Triple::x86) {
3606 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3607 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3608 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3609 << Unsupported->getOption().getName();
3610 }
Eric Christopher758aad72017-03-21 22:06:18 +00003611 // The faltivec option has been superseded by the maltivec option.
3612 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3613 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3614 << Unsupported->getOption().getName()
3615 << "please use -maltivec and include altivec.h explicitly";
3616 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3617 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3618 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003619 }
3620
3621 Args.AddAllArgs(CmdArgs, options::OPT_v);
3622 Args.AddLastArg(CmdArgs, options::OPT_H);
3623 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3624 CmdArgs.push_back("-header-include-file");
3625 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3626 : "-");
3627 }
3628 Args.AddLastArg(CmdArgs, options::OPT_P);
3629 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3630
3631 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3632 CmdArgs.push_back("-diagnostic-log-file");
3633 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3634 : "-");
3635 }
3636
David L. Jonesf561aba2017-03-08 01:02:16 +00003637 bool UseSeparateSections = isUseSeparateSections(Triple);
3638
3639 if (Args.hasFlag(options::OPT_ffunction_sections,
3640 options::OPT_fno_function_sections, UseSeparateSections)) {
3641 CmdArgs.push_back("-ffunction-sections");
3642 }
3643
3644 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3645 UseSeparateSections)) {
3646 CmdArgs.push_back("-fdata-sections");
3647 }
3648
3649 if (!Args.hasFlag(options::OPT_funique_section_names,
3650 options::OPT_fno_unique_section_names, true))
3651 CmdArgs.push_back("-fno-unique-section-names");
3652
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003653 if (auto *A = Args.getLastArg(
3654 options::OPT_finstrument_functions,
3655 options::OPT_finstrument_functions_after_inlining,
3656 options::OPT_finstrument_function_entry_bare))
3657 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003658
Artem Belevichc30bcad2018-01-24 17:41:02 +00003659 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3660 // sampling, overhead of call arc collection is way too high and there's no
3661 // way to collect the output.
3662 if (!Triple.isNVPTX())
3663 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003664
Richard Smithf667ad52017-08-26 01:04:35 +00003665 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3666 ABICompatArg->render(Args, CmdArgs);
3667
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003668 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3669 if (RawTriple.isPS4CPU()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003670 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003671 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3672 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003673
3674 // Pass options for controlling the default header search paths.
3675 if (Args.hasArg(options::OPT_nostdinc)) {
3676 CmdArgs.push_back("-nostdsysteminc");
3677 CmdArgs.push_back("-nobuiltininc");
3678 } else {
3679 if (Args.hasArg(options::OPT_nostdlibinc))
3680 CmdArgs.push_back("-nostdsysteminc");
3681 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3682 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3683 }
3684
3685 // Pass the path to compiler resource files.
3686 CmdArgs.push_back("-resource-dir");
3687 CmdArgs.push_back(D.ResourceDir.c_str());
3688
3689 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3690
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003691 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003692
3693 // Add preprocessing options like -I, -D, etc. if we are using the
3694 // preprocessor.
3695 //
3696 // FIXME: Support -fpreprocessed
3697 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3698 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3699
3700 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3701 // that "The compiler can only warn and ignore the option if not recognized".
3702 // When building with ccache, it will pass -D options to clang even on
3703 // preprocessed inputs and configure concludes that -fPIC is not supported.
3704 Args.ClaimAllArgs(options::OPT_D);
3705
3706 // Manually translate -O4 to -O3; let clang reject others.
3707 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3708 if (A->getOption().matches(options::OPT_O4)) {
3709 CmdArgs.push_back("-O3");
3710 D.Diag(diag::warn_O4_is_O3);
3711 } else {
3712 A->render(Args, CmdArgs);
3713 }
3714 }
3715
3716 // Warn about ignored options to clang.
3717 for (const Arg *A :
3718 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3719 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3720 A->claim();
3721 }
3722
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003723 for (const Arg *A :
3724 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3725 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3726 A->claim();
3727 }
3728
David L. Jonesf561aba2017-03-08 01:02:16 +00003729 claimNoWarnArgs(Args);
3730
3731 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3732
3733 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3734 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3735 CmdArgs.push_back("-pedantic");
3736 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3737 Args.AddLastArg(CmdArgs, options::OPT_w);
3738
Leonard Chanf921d852018-06-04 16:07:52 +00003739 // Fixed point flags
3740 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3741 /*Default=*/false))
3742 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3743
David L. Jonesf561aba2017-03-08 01:02:16 +00003744 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3745 // (-ansi is equivalent to -std=c89 or -std=c++98).
3746 //
3747 // If a std is supplied, only add -trigraphs if it follows the
3748 // option.
3749 bool ImplyVCPPCXXVer = false;
3750 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3751 if (Std->getOption().matches(options::OPT_ansi))
3752 if (types::isCXX(InputType))
3753 CmdArgs.push_back("-std=c++98");
3754 else
3755 CmdArgs.push_back("-std=c89");
3756 else
3757 Std->render(Args, CmdArgs);
3758
3759 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3760 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3761 options::OPT_ftrigraphs,
3762 options::OPT_fno_trigraphs))
3763 if (A != Std)
3764 A->render(Args, CmdArgs);
3765 } else {
3766 // Honor -std-default.
3767 //
3768 // FIXME: Clang doesn't correctly handle -std= when the input language
3769 // doesn't match. For the time being just ignore this for C++ inputs;
3770 // eventually we want to do all the standard defaulting here instead of
3771 // splitting it between the driver and clang -cc1.
3772 if (!types::isCXX(InputType))
3773 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3774 /*Joined=*/true);
3775 else if (IsWindowsMSVC)
3776 ImplyVCPPCXXVer = true;
3777
3778 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3779 options::OPT_fno_trigraphs);
3780 }
3781
3782 // GCC's behavior for -Wwrite-strings is a bit strange:
3783 // * In C, this "warning flag" changes the types of string literals from
3784 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3785 // for the discarded qualifier.
3786 // * In C++, this is just a normal warning flag.
3787 //
3788 // Implementing this warning correctly in C is hard, so we follow GCC's
3789 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3790 // a non-const char* in C, rather than using this crude hack.
3791 if (!types::isCXX(InputType)) {
3792 // FIXME: This should behave just like a warning flag, and thus should also
3793 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3794 Arg *WriteStrings =
3795 Args.getLastArg(options::OPT_Wwrite_strings,
3796 options::OPT_Wno_write_strings, options::OPT_w);
3797 if (WriteStrings &&
3798 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3799 CmdArgs.push_back("-fconst-strings");
3800 }
3801
3802 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3803 // during C++ compilation, which it is by default. GCC keeps this define even
3804 // in the presence of '-w', match this behavior bug-for-bug.
3805 if (types::isCXX(InputType) &&
3806 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3807 true)) {
3808 CmdArgs.push_back("-fdeprecated-macro");
3809 }
3810
3811 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3812 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3813 if (Asm->getOption().matches(options::OPT_fasm))
3814 CmdArgs.push_back("-fgnu-keywords");
3815 else
3816 CmdArgs.push_back("-fno-gnu-keywords");
3817 }
3818
3819 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3820 CmdArgs.push_back("-fno-dwarf-directory-asm");
3821
3822 if (ShouldDisableAutolink(Args, getToolChain()))
3823 CmdArgs.push_back("-fno-autolink");
3824
3825 // Add in -fdebug-compilation-dir if necessary.
3826 addDebugCompDirArg(Args, CmdArgs);
3827
Paul Robinson9b292b42018-07-10 15:15:24 +00003828 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003829
3830 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3831 options::OPT_ftemplate_depth_EQ)) {
3832 CmdArgs.push_back("-ftemplate-depth");
3833 CmdArgs.push_back(A->getValue());
3834 }
3835
3836 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3837 CmdArgs.push_back("-foperator-arrow-depth");
3838 CmdArgs.push_back(A->getValue());
3839 }
3840
3841 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3842 CmdArgs.push_back("-fconstexpr-depth");
3843 CmdArgs.push_back(A->getValue());
3844 }
3845
3846 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3847 CmdArgs.push_back("-fconstexpr-steps");
3848 CmdArgs.push_back(A->getValue());
3849 }
3850
3851 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3852 CmdArgs.push_back("-fbracket-depth");
3853 CmdArgs.push_back(A->getValue());
3854 }
3855
3856 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3857 options::OPT_Wlarge_by_value_copy_def)) {
3858 if (A->getNumValues()) {
3859 StringRef bytes = A->getValue();
3860 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3861 } else
3862 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3863 }
3864
3865 if (Args.hasArg(options::OPT_relocatable_pch))
3866 CmdArgs.push_back("-relocatable-pch");
3867
3868 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3869 CmdArgs.push_back("-fconstant-string-class");
3870 CmdArgs.push_back(A->getValue());
3871 }
3872
3873 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3874 CmdArgs.push_back("-ftabstop");
3875 CmdArgs.push_back(A->getValue());
3876 }
3877
Sean Eveson5110d4f2018-01-08 13:42:26 +00003878 if (Args.hasFlag(options::OPT_fstack_size_section,
3879 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3880 CmdArgs.push_back("-fstack-size-section");
3881
David L. Jonesf561aba2017-03-08 01:02:16 +00003882 CmdArgs.push_back("-ferror-limit");
3883 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3884 CmdArgs.push_back(A->getValue());
3885 else
3886 CmdArgs.push_back("19");
3887
3888 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3889 CmdArgs.push_back("-fmacro-backtrace-limit");
3890 CmdArgs.push_back(A->getValue());
3891 }
3892
3893 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3894 CmdArgs.push_back("-ftemplate-backtrace-limit");
3895 CmdArgs.push_back(A->getValue());
3896 }
3897
3898 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3899 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3900 CmdArgs.push_back(A->getValue());
3901 }
3902
3903 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3904 CmdArgs.push_back("-fspell-checking-limit");
3905 CmdArgs.push_back(A->getValue());
3906 }
3907
3908 // Pass -fmessage-length=.
3909 CmdArgs.push_back("-fmessage-length");
3910 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3911 CmdArgs.push_back(A->getValue());
3912 } else {
3913 // If -fmessage-length=N was not specified, determine whether this is a
3914 // terminal and, if so, implicitly define -fmessage-length appropriately.
3915 unsigned N = llvm::sys::Process::StandardErrColumns();
3916 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3917 }
3918
3919 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3920 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3921 options::OPT_fvisibility_ms_compat)) {
3922 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3923 CmdArgs.push_back("-fvisibility");
3924 CmdArgs.push_back(A->getValue());
3925 } else {
3926 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3927 CmdArgs.push_back("-fvisibility");
3928 CmdArgs.push_back("hidden");
3929 CmdArgs.push_back("-ftype-visibility");
3930 CmdArgs.push_back("default");
3931 }
3932 }
3933
3934 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3935
3936 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3937
David L. Jonesf561aba2017-03-08 01:02:16 +00003938 // Forward -f (flag) options which we can pass directly.
3939 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3940 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00003941 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003942 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00003943 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3944 options::OPT_fno_emulated_tls);
3945
David L. Jonesf561aba2017-03-08 01:02:16 +00003946 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003947 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003948 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003949
David L. Jonesf561aba2017-03-08 01:02:16 +00003950 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3951 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3952
3953 // Forward flags for OpenMP. We don't do this if the current action is an
3954 // device offloading action other than OpenMP.
3955 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3956 options::OPT_fno_openmp, false) &&
3957 (JA.isDeviceOffloading(Action::OFK_None) ||
3958 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003959 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003960 case Driver::OMPRT_OMP:
3961 case Driver::OMPRT_IOMP5:
3962 // Clang can generate useful OpenMP code for these two runtime libraries.
3963 CmdArgs.push_back("-fopenmp");
3964
3965 // If no option regarding the use of TLS in OpenMP codegeneration is
3966 // given, decide a default based on the target. Otherwise rely on the
3967 // options and pass the right information to the frontend.
3968 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3969 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3970 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00003971 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3972 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00003973 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00003974
3975 // When in OpenMP offloading mode with NVPTX target, forward
3976 // cuda-mode flag
3977 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
3978 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00003979 break;
3980 default:
3981 // By default, if Clang doesn't know how to generate useful OpenMP code
3982 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3983 // down to the actual compilation.
3984 // FIXME: It would be better to have a mode which *only* omits IR
3985 // generation based on the OpenMP support so that we get consistent
3986 // semantic analysis, etc.
3987 break;
3988 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00003989 } else {
3990 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3991 options::OPT_fno_openmp_simd);
3992 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00003993 }
3994
3995 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3996 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3997
Dean Michael Berris835832d2017-03-30 00:29:36 +00003998 const XRayArgs &XRay = getToolChain().getXRayArgs();
3999 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4000
David L. Jonesf561aba2017-03-08 01:02:16 +00004001 if (getToolChain().SupportsProfiling())
4002 Args.AddLastArg(CmdArgs, options::OPT_pg);
4003
4004 if (getToolChain().SupportsProfiling())
4005 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4006
4007 // -flax-vector-conversions is default.
4008 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4009 options::OPT_fno_lax_vector_conversions))
4010 CmdArgs.push_back("-fno-lax-vector-conversions");
4011
4012 if (Args.getLastArg(options::OPT_fapple_kext) ||
4013 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4014 CmdArgs.push_back("-fapple-kext");
4015
4016 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4017 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4018 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4019 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4020 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4021
4022 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4023 CmdArgs.push_back("-ftrapv-handler");
4024 CmdArgs.push_back(A->getValue());
4025 }
4026
4027 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4028
4029 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4030 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4031 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4032 if (A->getOption().matches(options::OPT_fwrapv))
4033 CmdArgs.push_back("-fwrapv");
4034 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4035 options::OPT_fno_strict_overflow)) {
4036 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4037 CmdArgs.push_back("-fwrapv");
4038 }
4039
4040 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4041 options::OPT_fno_reroll_loops))
4042 if (A->getOption().matches(options::OPT_freroll_loops))
4043 CmdArgs.push_back("-freroll-loops");
4044
4045 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4046 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4047 options::OPT_fno_unroll_loops);
4048
4049 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4050
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004051 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004052
4053 // Translate -mstackrealign
4054 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4055 false))
4056 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4057
4058 if (Args.hasArg(options::OPT_mstack_alignment)) {
4059 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4060 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4061 }
4062
4063 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4064 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4065
4066 if (!Size.empty())
4067 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4068 else
4069 CmdArgs.push_back("-mstack-probe-size=0");
4070 }
4071
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004072 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4073 options::OPT_mno_stack_arg_probe, true))
4074 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4075
David L. Jonesf561aba2017-03-08 01:02:16 +00004076 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4077 options::OPT_mno_restrict_it)) {
4078 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004079 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004080 CmdArgs.push_back("-arm-restrict-it");
4081 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004082 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004083 CmdArgs.push_back("-arm-no-restrict-it");
4084 }
4085 } else if (Triple.isOSWindows() &&
4086 (Triple.getArch() == llvm::Triple::arm ||
4087 Triple.getArch() == llvm::Triple::thumb)) {
4088 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004089 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004090 CmdArgs.push_back("-arm-restrict-it");
4091 }
4092
4093 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004094 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004095
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004096 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4097 CmdArgs.push_back(
4098 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4099 }
4100
David L. Jonesf561aba2017-03-08 01:02:16 +00004101 // Forward -f options with positive and negative forms; we translate
4102 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004103 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004104 StringRef fname = A->getValue();
4105 if (!llvm::sys::fs::exists(fname))
4106 D.Diag(diag::err_drv_no_such_file) << fname;
4107 else
4108 A->render(Args, CmdArgs);
4109 }
4110
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004111 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004112
4113 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4114 options::OPT_fno_assume_sane_operator_new))
4115 CmdArgs.push_back("-fno-assume-sane-operator-new");
4116
4117 // -fblocks=0 is default.
4118 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4119 getToolChain().IsBlocksDefault()) ||
4120 (Args.hasArg(options::OPT_fgnu_runtime) &&
4121 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4122 !Args.hasArg(options::OPT_fno_blocks))) {
4123 CmdArgs.push_back("-fblocks");
4124
4125 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4126 !getToolChain().hasBlocksRuntime())
4127 CmdArgs.push_back("-fblocks-runtime-optional");
4128 }
4129
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004130 // -fencode-extended-block-signature=1 is default.
4131 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4132 CmdArgs.push_back("-fencode-extended-block-signature");
4133
David L. Jonesf561aba2017-03-08 01:02:16 +00004134 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4135 false) &&
4136 types::isCXX(InputType)) {
4137 CmdArgs.push_back("-fcoroutines-ts");
4138 }
4139
Aaron Ballman61736552017-10-21 20:28:58 +00004140 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4141 options::OPT_fno_double_square_bracket_attributes);
4142
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004143 bool HaveModules = false;
4144 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004145
4146 // -faccess-control is default.
4147 if (Args.hasFlag(options::OPT_fno_access_control,
4148 options::OPT_faccess_control, false))
4149 CmdArgs.push_back("-fno-access-control");
4150
4151 // -felide-constructors is the default.
4152 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4153 options::OPT_felide_constructors, false))
4154 CmdArgs.push_back("-fno-elide-constructors");
4155
4156 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4157
4158 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004159 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004160 CmdArgs.push_back("-fno-rtti");
4161
4162 // -fshort-enums=0 is default for all architectures except Hexagon.
4163 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4164 getToolChain().getArch() == llvm::Triple::hexagon))
4165 CmdArgs.push_back("-fshort-enums");
4166
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004167 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004168
4169 // -fuse-cxa-atexit is default.
4170 if (!Args.hasFlag(
4171 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004172 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004173 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004174 getToolChain().getArch() != llvm::Triple::hexagon &&
4175 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004176 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4177 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004178 KernelOrKext)
4179 CmdArgs.push_back("-fno-use-cxa-atexit");
4180
Akira Hatanaka617e2612018-04-17 18:41:52 +00004181 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4182 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004183 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004184 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4185
David L. Jonesf561aba2017-03-08 01:02:16 +00004186 // -fms-extensions=0 is default.
4187 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4188 IsWindowsMSVC))
4189 CmdArgs.push_back("-fms-extensions");
4190
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004191 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004192 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004193 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004194 CmdArgs.push_back("-fuse-line-directives");
4195
4196 // -fms-compatibility=0 is default.
4197 if (Args.hasFlag(options::OPT_fms_compatibility,
4198 options::OPT_fno_ms_compatibility,
4199 (IsWindowsMSVC &&
4200 Args.hasFlag(options::OPT_fms_extensions,
4201 options::OPT_fno_ms_extensions, true))))
4202 CmdArgs.push_back("-fms-compatibility");
4203
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004204 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004205 if (!MSVT.empty())
4206 CmdArgs.push_back(
4207 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4208
4209 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4210 if (ImplyVCPPCXXVer) {
4211 StringRef LanguageStandard;
4212 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4213 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4214 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004215 .Case("c++17", "-std=c++17")
4216 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004217 .Default("");
4218 if (LanguageStandard.empty())
4219 D.Diag(clang::diag::warn_drv_unused_argument)
4220 << StdArg->getAsString(Args);
4221 }
4222
4223 if (LanguageStandard.empty()) {
4224 if (IsMSVC2015Compatible)
4225 LanguageStandard = "-std=c++14";
4226 else
4227 LanguageStandard = "-std=c++11";
4228 }
4229
4230 CmdArgs.push_back(LanguageStandard.data());
4231 }
4232
4233 // -fno-borland-extensions is default.
4234 if (Args.hasFlag(options::OPT_fborland_extensions,
4235 options::OPT_fno_borland_extensions, false))
4236 CmdArgs.push_back("-fborland-extensions");
4237
4238 // -fno-declspec is default, except for PS4.
4239 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004240 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004241 CmdArgs.push_back("-fdeclspec");
4242 else if (Args.hasArg(options::OPT_fno_declspec))
4243 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4244
4245 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4246 // than 19.
4247 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4248 options::OPT_fno_threadsafe_statics,
4249 !IsWindowsMSVC || IsMSVC2015Compatible))
4250 CmdArgs.push_back("-fno-threadsafe-statics");
4251
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004252 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004253 // Many old Windows SDK versions require this to parse.
4254 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4255 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004256 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4257 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4258 CmdArgs.push_back("-fdelayed-template-parsing");
4259
4260 // -fgnu-keywords default varies depending on language; only pass if
4261 // specified.
4262 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4263 options::OPT_fno_gnu_keywords))
4264 A->render(Args, CmdArgs);
4265
4266 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4267 false))
4268 CmdArgs.push_back("-fgnu89-inline");
4269
4270 if (Args.hasArg(options::OPT_fno_inline))
4271 CmdArgs.push_back("-fno-inline");
4272
4273 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4274 options::OPT_finline_hint_functions,
4275 options::OPT_fno_inline_functions))
4276 InlineArg->render(Args, CmdArgs);
4277
4278 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4279 options::OPT_fno_experimental_new_pass_manager);
4280
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004281 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4282 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4283 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004284
4285 if (Args.hasFlag(options::OPT_fapplication_extension,
4286 options::OPT_fno_application_extension, false))
4287 CmdArgs.push_back("-fapplication-extension");
4288
4289 // Handle GCC-style exception args.
4290 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004291 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004292 CmdArgs);
4293
Martell Malonec950c652017-11-29 07:25:12 +00004294 // Handle exception personalities
4295 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4296 options::OPT_fseh_exceptions,
4297 options::OPT_fdwarf_exceptions);
4298 if (A) {
4299 const Option &Opt = A->getOption();
4300 if (Opt.matches(options::OPT_fsjlj_exceptions))
4301 CmdArgs.push_back("-fsjlj-exceptions");
4302 if (Opt.matches(options::OPT_fseh_exceptions))
4303 CmdArgs.push_back("-fseh-exceptions");
4304 if (Opt.matches(options::OPT_fdwarf_exceptions))
4305 CmdArgs.push_back("-fdwarf-exceptions");
4306 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004307 switch (getToolChain().GetExceptionModel(Args)) {
4308 default:
4309 break;
4310 case llvm::ExceptionHandling::DwarfCFI:
4311 CmdArgs.push_back("-fdwarf-exceptions");
4312 break;
4313 case llvm::ExceptionHandling::SjLj:
4314 CmdArgs.push_back("-fsjlj-exceptions");
4315 break;
4316 case llvm::ExceptionHandling::WinEH:
4317 CmdArgs.push_back("-fseh-exceptions");
4318 break;
Martell Malonec950c652017-11-29 07:25:12 +00004319 }
4320 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004321
4322 // C++ "sane" operator new.
4323 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4324 options::OPT_fno_assume_sane_operator_new))
4325 CmdArgs.push_back("-fno-assume-sane-operator-new");
4326
4327 // -frelaxed-template-template-args is off by default, as it is a severe
4328 // breaking change until a corresponding change to template partial ordering
4329 // is provided.
4330 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4331 options::OPT_fno_relaxed_template_template_args, false))
4332 CmdArgs.push_back("-frelaxed-template-template-args");
4333
4334 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4335 // most platforms.
4336 if (Args.hasFlag(options::OPT_fsized_deallocation,
4337 options::OPT_fno_sized_deallocation, false))
4338 CmdArgs.push_back("-fsized-deallocation");
4339
4340 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4341 // by default.
4342 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4343 options::OPT_fno_aligned_allocation,
4344 options::OPT_faligned_new_EQ)) {
4345 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4346 CmdArgs.push_back("-fno-aligned-allocation");
4347 else
4348 CmdArgs.push_back("-faligned-allocation");
4349 }
4350
4351 // The default new alignment can be specified using a dedicated option or via
4352 // a GCC-compatible option that also turns on aligned allocation.
4353 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4354 options::OPT_faligned_new_EQ))
4355 CmdArgs.push_back(
4356 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4357
4358 // -fconstant-cfstrings is default, and may be subject to argument translation
4359 // on Darwin.
4360 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4361 options::OPT_fno_constant_cfstrings) ||
4362 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4363 options::OPT_mno_constant_cfstrings))
4364 CmdArgs.push_back("-fno-constant-cfstrings");
4365
David L. Jonesf561aba2017-03-08 01:02:16 +00004366 // -fno-pascal-strings is default, only pass non-default.
4367 if (Args.hasFlag(options::OPT_fpascal_strings,
4368 options::OPT_fno_pascal_strings, false))
4369 CmdArgs.push_back("-fpascal-strings");
4370
4371 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4372 // -fno-pack-struct doesn't apply to -fpack-struct=.
4373 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4374 std::string PackStructStr = "-fpack-struct=";
4375 PackStructStr += A->getValue();
4376 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4377 } else if (Args.hasFlag(options::OPT_fpack_struct,
4378 options::OPT_fno_pack_struct, false)) {
4379 CmdArgs.push_back("-fpack-struct=1");
4380 }
4381
4382 // Handle -fmax-type-align=N and -fno-type-align
4383 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4384 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4385 if (!SkipMaxTypeAlign) {
4386 std::string MaxTypeAlignStr = "-fmax-type-align=";
4387 MaxTypeAlignStr += A->getValue();
4388 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4389 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004390 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004391 if (!SkipMaxTypeAlign) {
4392 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4393 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4394 }
4395 }
4396
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004397 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4398 CmdArgs.push_back("-Qn");
4399
David L. Jonesf561aba2017-03-08 01:02:16 +00004400 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004401 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004402 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4403 !NoCommonDefault))
4404 CmdArgs.push_back("-fno-common");
4405
4406 // -fsigned-bitfields is default, and clang doesn't yet support
4407 // -funsigned-bitfields.
4408 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4409 options::OPT_funsigned_bitfields))
4410 D.Diag(diag::warn_drv_clang_unsupported)
4411 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4412
4413 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4414 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4415 D.Diag(diag::err_drv_clang_unsupported)
4416 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4417
4418 // -finput_charset=UTF-8 is default. Reject others
4419 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4420 StringRef value = inputCharset->getValue();
4421 if (!value.equals_lower("utf-8"))
4422 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4423 << value;
4424 }
4425
4426 // -fexec_charset=UTF-8 is default. Reject others
4427 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4428 StringRef value = execCharset->getValue();
4429 if (!value.equals_lower("utf-8"))
4430 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4431 << value;
4432 }
4433
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004434 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004435
4436 // -fno-asm-blocks is default.
4437 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4438 false))
4439 CmdArgs.push_back("-fasm-blocks");
4440
4441 // -fgnu-inline-asm is default.
4442 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4443 options::OPT_fno_gnu_inline_asm, true))
4444 CmdArgs.push_back("-fno-gnu-inline-asm");
4445
4446 // Enable vectorization per default according to the optimization level
4447 // selected. For optimization levels that want vectorization we use the alias
4448 // option to simplify the hasFlag logic.
4449 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4450 OptSpecifier VectorizeAliasOption =
4451 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4452 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4453 options::OPT_fno_vectorize, EnableVec))
4454 CmdArgs.push_back("-vectorize-loops");
4455
4456 // -fslp-vectorize is enabled based on the optimization level selected.
4457 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4458 OptSpecifier SLPVectAliasOption =
4459 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4460 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4461 options::OPT_fno_slp_vectorize, EnableSLPVec))
4462 CmdArgs.push_back("-vectorize-slp");
4463
Craig Topper9a724aa2017-12-11 21:09:19 +00004464 ParseMPreferVectorWidth(D, Args, CmdArgs);
4465
David L. Jonesf561aba2017-03-08 01:02:16 +00004466 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4467 A->render(Args, CmdArgs);
4468
4469 if (Arg *A = Args.getLastArg(
4470 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4471 A->render(Args, CmdArgs);
4472
4473 // -fdollars-in-identifiers default varies depending on platform and
4474 // language; only pass if specified.
4475 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4476 options::OPT_fno_dollars_in_identifiers)) {
4477 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4478 CmdArgs.push_back("-fdollars-in-identifiers");
4479 else
4480 CmdArgs.push_back("-fno-dollars-in-identifiers");
4481 }
4482
4483 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4484 // practical purposes.
4485 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4486 options::OPT_fno_unit_at_a_time)) {
4487 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4488 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4489 }
4490
4491 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4492 options::OPT_fno_apple_pragma_pack, false))
4493 CmdArgs.push_back("-fapple-pragma-pack");
4494
David L. Jonesf561aba2017-03-08 01:02:16 +00004495 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004496 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004497 options::OPT_fno_save_optimization_record, false)) {
4498 CmdArgs.push_back("-opt-record-file");
4499
4500 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4501 if (A) {
4502 CmdArgs.push_back(A->getValue());
4503 } else {
4504 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004505
4506 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4507 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4508 F = FinalOutput->getValue();
4509 }
4510
4511 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004512 // Use the input filename.
4513 F = llvm::sys::path::stem(Input.getBaseInput());
4514
4515 // If we're compiling for an offload architecture (i.e. a CUDA device),
4516 // we need to make the file name for the device compilation different
4517 // from the host compilation.
4518 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4519 !JA.isDeviceOffloading(Action::OFK_Host)) {
4520 llvm::sys::path::replace_extension(F, "");
4521 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4522 Triple.normalize());
4523 F += "-";
4524 F += JA.getOffloadingArch();
4525 }
4526 }
4527
4528 llvm::sys::path::replace_extension(F, "opt.yaml");
4529 CmdArgs.push_back(Args.MakeArgString(F));
4530 }
4531 }
4532
Richard Smith86a3ef52017-06-09 21:24:02 +00004533 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4534 options::OPT_fno_rewrite_imports, false);
4535 if (RewriteImports)
4536 CmdArgs.push_back("-frewrite-imports");
4537
David L. Jonesf561aba2017-03-08 01:02:16 +00004538 // Enable rewrite includes if the user's asked for it or if we're generating
4539 // diagnostics.
4540 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4541 // nice to enable this when doing a crashdump for modules as well.
4542 if (Args.hasFlag(options::OPT_frewrite_includes,
4543 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004544 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004545 CmdArgs.push_back("-frewrite-includes");
4546
4547 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4548 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4549 options::OPT_traditional_cpp)) {
4550 if (isa<PreprocessJobAction>(JA))
4551 CmdArgs.push_back("-traditional-cpp");
4552 else
4553 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4554 }
4555
4556 Args.AddLastArg(CmdArgs, options::OPT_dM);
4557 Args.AddLastArg(CmdArgs, options::OPT_dD);
4558
4559 // Handle serialized diagnostics.
4560 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4561 CmdArgs.push_back("-serialize-diagnostic-file");
4562 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4563 }
4564
4565 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4566 CmdArgs.push_back("-fretain-comments-from-system-headers");
4567
4568 // Forward -fcomment-block-commands to -cc1.
4569 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4570 // Forward -fparse-all-comments to -cc1.
4571 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4572
4573 // Turn -fplugin=name.so into -load name.so
4574 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4575 CmdArgs.push_back("-load");
4576 CmdArgs.push_back(A->getValue());
4577 A->claim();
4578 }
4579
4580 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004581 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4582 if (!StatsFile.empty())
4583 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004584
4585 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4586 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004587 // -finclude-default-header flag is for preprocessor,
4588 // do not pass it to other cc1 commands when save-temps is enabled
4589 if (C.getDriver().isSaveTempsEnabled() &&
4590 !isa<PreprocessJobAction>(JA)) {
4591 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4592 Arg->claim();
4593 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4594 CmdArgs.push_back(Arg->getValue());
4595 }
4596 }
4597 else {
4598 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4599 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004600 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4601 A->claim();
4602
4603 // We translate this by hand to the -cc1 argument, since nightly test uses
4604 // it and developers have been trained to spell it with -mllvm. Both
4605 // spellings are now deprecated and should be removed.
4606 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4607 CmdArgs.push_back("-disable-llvm-optzns");
4608 } else {
4609 A->render(Args, CmdArgs);
4610 }
4611 }
4612
4613 // With -save-temps, we want to save the unoptimized bitcode output from the
4614 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4615 // by the frontend.
4616 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4617 // has slightly different breakdown between stages.
4618 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4619 // pristine IR generated by the frontend. Ideally, a new compile action should
4620 // be added so both IR can be captured.
4621 if (C.getDriver().isSaveTempsEnabled() &&
4622 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4623 isa<CompileJobAction>(JA))
4624 CmdArgs.push_back("-disable-llvm-passes");
4625
4626 if (Output.getType() == types::TY_Dependencies) {
4627 // Handled with other dependency code.
4628 } else if (Output.isFilename()) {
4629 CmdArgs.push_back("-o");
4630 CmdArgs.push_back(Output.getFilename());
4631 } else {
4632 assert(Output.isNothing() && "Invalid output.");
4633 }
4634
4635 addDashXForInput(Args, Input, CmdArgs);
4636
4637 if (Input.isFilename())
4638 CmdArgs.push_back(Input.getFilename());
4639 else
4640 Input.getInputArg().renderAsInput(Args, CmdArgs);
4641
4642 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4643
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004644 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004645
4646 // Optionally embed the -cc1 level arguments into the debug info, for build
4647 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004648 // Also record command line arguments into the debug info if
4649 // -grecord-gcc-switches options is set on.
4650 // By default, -gno-record-gcc-switches is set on and no recording.
4651 if (getToolChain().UseDwarfDebugFlags() ||
4652 Args.hasFlag(options::OPT_grecord_gcc_switches,
4653 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004654 ArgStringList OriginalArgs;
4655 for (const auto &Arg : Args)
4656 Arg->render(Args, OriginalArgs);
4657
4658 SmallString<256> Flags;
4659 Flags += Exec;
4660 for (const char *OriginalArg : OriginalArgs) {
4661 SmallString<128> EscapedArg;
4662 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4663 Flags += " ";
4664 Flags += EscapedArg;
4665 }
4666 CmdArgs.push_back("-dwarf-debug-flags");
4667 CmdArgs.push_back(Args.MakeArgString(Flags));
4668 }
4669
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004670 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004671 // Host-side cuda compilation receives all device-side outputs in a single
4672 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004673 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004674 assert(Inputs.size() == 2 && "More than one GPU binary!");
4675 CmdArgs.push_back("-fcuda-include-gpubinary");
4676 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004677 }
4678
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004679 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4680 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004681 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4682 options::OPT_fno_cuda_short_ptr, false))
4683 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004684 }
4685
David L. Jonesf561aba2017-03-08 01:02:16 +00004686 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4687 // to specify the result of the compile phase on the host, so the meaningful
4688 // device declarations can be identified. Also, -fopenmp-is-device is passed
4689 // along to tell the frontend that it is generating code for a device, so that
4690 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004691 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004692 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004693 if (Inputs.size() == 2) {
4694 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4695 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4696 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004697 }
4698
4699 // For all the host OpenMP offloading compile jobs we need to pass the targets
4700 // information using -fopenmp-targets= option.
4701 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4702 SmallString<128> TargetInfo("-fopenmp-targets=");
4703
4704 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4705 assert(Tgts && Tgts->getNumValues() &&
4706 "OpenMP offloading has to have targets specified.");
4707 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4708 if (i)
4709 TargetInfo += ',';
4710 // We need to get the string from the triple because it may be not exactly
4711 // the same as the one we get directly from the arguments.
4712 llvm::Triple T(Tgts->getValue(i));
4713 TargetInfo += T.getTriple();
4714 }
4715 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4716 }
4717
4718 bool WholeProgramVTables =
4719 Args.hasFlag(options::OPT_fwhole_program_vtables,
4720 options::OPT_fno_whole_program_vtables, false);
4721 if (WholeProgramVTables) {
4722 if (!D.isUsingLTO())
4723 D.Diag(diag::err_drv_argument_only_allowed_with)
4724 << "-fwhole-program-vtables"
4725 << "-flto";
4726 CmdArgs.push_back("-fwhole-program-vtables");
4727 }
4728
Amara Emerson4ee9f822018-01-26 00:27:22 +00004729 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4730 options::OPT_fno_experimental_isel)) {
4731 CmdArgs.push_back("-mllvm");
4732 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4733 CmdArgs.push_back("-global-isel=1");
4734
4735 // GISel is on by default on AArch64 -O0, so don't bother adding
4736 // the fallback remarks for it. Other combinations will add a warning of
4737 // some kind.
4738 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4739 bool IsOptLevelSupported = false;
4740
4741 Arg *A = Args.getLastArg(options::OPT_O_Group);
4742 if (Triple.getArch() == llvm::Triple::aarch64) {
4743 if (!A || A->getOption().matches(options::OPT_O0))
4744 IsOptLevelSupported = true;
4745 }
4746 if (!IsArchSupported || !IsOptLevelSupported) {
4747 CmdArgs.push_back("-mllvm");
4748 CmdArgs.push_back("-global-isel-abort=2");
4749
4750 if (!IsArchSupported)
4751 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4752 else
4753 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4754 }
4755 } else {
4756 CmdArgs.push_back("-global-isel=0");
4757 }
4758 }
4759
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004760 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4761 options::OPT_fno_force_enable_int128)) {
4762 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4763 CmdArgs.push_back("-fforce-enable-int128");
4764 }
4765
Peter Collingbourne54d13b42018-05-30 03:40:04 +00004766 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4767 options::OPT_fno_complete_member_pointers, false))
4768 CmdArgs.push_back("-fcomplete-member-pointers");
4769
Jessica Paquette36a25672018-06-29 18:06:10 +00004770 if (Arg *A = Args.getLastArg(options::OPT_moutline,
4771 options::OPT_mno_outline)) {
4772 if (A->getOption().matches(options::OPT_moutline)) {
4773 // We only support -moutline in AArch64 right now. If we're not compiling
4774 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
4775 // proper mllvm flags.
4776 if (Triple.getArch() != llvm::Triple::aarch64) {
4777 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
4778 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00004779 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00004780 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004781 }
Jessica Paquette36a25672018-06-29 18:06:10 +00004782 } else {
4783 // Disable all outlining behaviour.
4784 CmdArgs.push_back("-mllvm");
4785 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004786 }
4787 }
4788
Peter Collingbourne14b468b2018-07-18 00:27:07 +00004789 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
4790 getToolChain().getTriple().isOSBinFormatELF() &&
4791 getToolChain().useIntegratedAs()))
4792 CmdArgs.push_back("-faddrsig");
4793
David L. Jonesf561aba2017-03-08 01:02:16 +00004794 // Finally add the compile command to the compilation.
4795 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4796 Output.getType() == types::TY_Object &&
4797 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4798 auto CLCommand =
4799 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4800 C.addCommand(llvm::make_unique<FallbackCommand>(
4801 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4802 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4803 isa<PrecompileJobAction>(JA)) {
4804 // In /fallback builds, run the main compilation even if the pch generation
4805 // fails, so that the main compilation's fallback to cl.exe runs.
4806 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4807 CmdArgs, Inputs));
4808 } else {
4809 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4810 }
4811
David L. Jonesf561aba2017-03-08 01:02:16 +00004812 if (Arg *A = Args.getLastArg(options::OPT_pg))
4813 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4814 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4815 << A->getAsString(Args);
4816
4817 // Claim some arguments which clang supports automatically.
4818
4819 // -fpch-preprocess is used with gcc to add a special marker in the output to
4820 // include the PCH file. Clang's PTH solution is completely transparent, so we
4821 // do not need to deal with it at all.
4822 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4823
4824 // Claim some arguments which clang doesn't support, but we don't
4825 // care to warn the user about.
4826 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4827 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4828
4829 // Disable warnings for clang -E -emit-llvm foo.c
4830 Args.ClaimAllArgs(options::OPT_emit_llvm);
4831}
4832
4833Clang::Clang(const ToolChain &TC)
4834 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4835 // as it is for other tools. Some operations on a Tool actually test
4836 // whether that tool is Clang based on the Tool's Name as a string.
4837 : Tool("clang", "clang frontend", TC, RF_Full) {}
4838
4839Clang::~Clang() {}
4840
4841/// Add options related to the Objective-C runtime/ABI.
4842///
4843/// Returns true if the runtime is non-fragile.
4844ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4845 ArgStringList &cmdArgs,
4846 RewriteKind rewriteKind) const {
4847 // Look for the controlling runtime option.
4848 Arg *runtimeArg =
4849 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4850 options::OPT_fobjc_runtime_EQ);
4851
4852 // Just forward -fobjc-runtime= to the frontend. This supercedes
4853 // options about fragility.
4854 if (runtimeArg &&
4855 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4856 ObjCRuntime runtime;
4857 StringRef value = runtimeArg->getValue();
4858 if (runtime.tryParse(value)) {
4859 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4860 << value;
4861 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004862 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4863 (runtime.getVersion() >= VersionTuple(2, 0)))
4864 if (!getToolChain().getTriple().isOSBinFormatELF()) {
4865 getToolChain().getDriver().Diag(
4866 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4867 << runtime.getVersion().getMajor();
4868 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004869
4870 runtimeArg->render(args, cmdArgs);
4871 return runtime;
4872 }
4873
4874 // Otherwise, we'll need the ABI "version". Version numbers are
4875 // slightly confusing for historical reasons:
4876 // 1 - Traditional "fragile" ABI
4877 // 2 - Non-fragile ABI, version 1
4878 // 3 - Non-fragile ABI, version 2
4879 unsigned objcABIVersion = 1;
4880 // If -fobjc-abi-version= is present, use that to set the version.
4881 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4882 StringRef value = abiArg->getValue();
4883 if (value == "1")
4884 objcABIVersion = 1;
4885 else if (value == "2")
4886 objcABIVersion = 2;
4887 else if (value == "3")
4888 objcABIVersion = 3;
4889 else
4890 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4891 } else {
4892 // Otherwise, determine if we are using the non-fragile ABI.
4893 bool nonFragileABIIsDefault =
4894 (rewriteKind == RK_NonFragile ||
4895 (rewriteKind == RK_None &&
4896 getToolChain().IsObjCNonFragileABIDefault()));
4897 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4898 options::OPT_fno_objc_nonfragile_abi,
4899 nonFragileABIIsDefault)) {
4900// Determine the non-fragile ABI version to use.
4901#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4902 unsigned nonFragileABIVersion = 1;
4903#else
4904 unsigned nonFragileABIVersion = 2;
4905#endif
4906
4907 if (Arg *abiArg =
4908 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4909 StringRef value = abiArg->getValue();
4910 if (value == "1")
4911 nonFragileABIVersion = 1;
4912 else if (value == "2")
4913 nonFragileABIVersion = 2;
4914 else
4915 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4916 << value;
4917 }
4918
4919 objcABIVersion = 1 + nonFragileABIVersion;
4920 } else {
4921 objcABIVersion = 1;
4922 }
4923 }
4924
4925 // We don't actually care about the ABI version other than whether
4926 // it's non-fragile.
4927 bool isNonFragile = objcABIVersion != 1;
4928
4929 // If we have no runtime argument, ask the toolchain for its default runtime.
4930 // However, the rewriter only really supports the Mac runtime, so assume that.
4931 ObjCRuntime runtime;
4932 if (!runtimeArg) {
4933 switch (rewriteKind) {
4934 case RK_None:
4935 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4936 break;
4937 case RK_Fragile:
4938 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4939 break;
4940 case RK_NonFragile:
4941 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4942 break;
4943 }
4944
4945 // -fnext-runtime
4946 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4947 // On Darwin, make this use the default behavior for the toolchain.
4948 if (getToolChain().getTriple().isOSDarwin()) {
4949 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4950
4951 // Otherwise, build for a generic macosx port.
4952 } else {
4953 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4954 }
4955
4956 // -fgnu-runtime
4957 } else {
4958 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4959 // Legacy behaviour is to target the gnustep runtime if we are in
4960 // non-fragile mode or the GCC runtime in fragile mode.
4961 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00004962 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00004963 else
4964 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4965 }
4966
4967 cmdArgs.push_back(
4968 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4969 return runtime;
4970}
4971
4972static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4973 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4974 I += HaveDash;
4975 return !HaveDash;
4976}
4977
4978namespace {
4979struct EHFlags {
4980 bool Synch = false;
4981 bool Asynch = false;
4982 bool NoUnwindC = false;
4983};
4984} // end anonymous namespace
4985
4986/// /EH controls whether to run destructor cleanups when exceptions are
4987/// thrown. There are three modifiers:
4988/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4989/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4990/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4991/// - c: Assume that extern "C" functions are implicitly nounwind.
4992/// The default is /EHs-c-, meaning cleanups are disabled.
4993static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4994 EHFlags EH;
4995
4996 std::vector<std::string> EHArgs =
4997 Args.getAllArgValues(options::OPT__SLASH_EH);
4998 for (auto EHVal : EHArgs) {
4999 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5000 switch (EHVal[I]) {
5001 case 'a':
5002 EH.Asynch = maybeConsumeDash(EHVal, I);
5003 if (EH.Asynch)
5004 EH.Synch = false;
5005 continue;
5006 case 'c':
5007 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5008 continue;
5009 case 's':
5010 EH.Synch = maybeConsumeDash(EHVal, I);
5011 if (EH.Synch)
5012 EH.Asynch = false;
5013 continue;
5014 default:
5015 break;
5016 }
5017 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5018 break;
5019 }
5020 }
5021 // The /GX, /GX- flags are only processed if there are not /EH flags.
5022 // The default is that /GX is not specified.
5023 if (EHArgs.empty() &&
5024 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5025 /*default=*/false)) {
5026 EH.Synch = true;
5027 EH.NoUnwindC = true;
5028 }
5029
5030 return EH;
5031}
5032
5033void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5034 ArgStringList &CmdArgs,
5035 codegenoptions::DebugInfoKind *DebugInfoKind,
5036 bool *EmitCodeView) const {
5037 unsigned RTOptionID = options::OPT__SLASH_MT;
5038
5039 if (Args.hasArg(options::OPT__SLASH_LDd))
5040 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5041 // but defining _DEBUG is sticky.
5042 RTOptionID = options::OPT__SLASH_MTd;
5043
5044 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5045 RTOptionID = A->getOption().getID();
5046
5047 StringRef FlagForCRT;
5048 switch (RTOptionID) {
5049 case options::OPT__SLASH_MD:
5050 if (Args.hasArg(options::OPT__SLASH_LDd))
5051 CmdArgs.push_back("-D_DEBUG");
5052 CmdArgs.push_back("-D_MT");
5053 CmdArgs.push_back("-D_DLL");
5054 FlagForCRT = "--dependent-lib=msvcrt";
5055 break;
5056 case options::OPT__SLASH_MDd:
5057 CmdArgs.push_back("-D_DEBUG");
5058 CmdArgs.push_back("-D_MT");
5059 CmdArgs.push_back("-D_DLL");
5060 FlagForCRT = "--dependent-lib=msvcrtd";
5061 break;
5062 case options::OPT__SLASH_MT:
5063 if (Args.hasArg(options::OPT__SLASH_LDd))
5064 CmdArgs.push_back("-D_DEBUG");
5065 CmdArgs.push_back("-D_MT");
5066 CmdArgs.push_back("-flto-visibility-public-std");
5067 FlagForCRT = "--dependent-lib=libcmt";
5068 break;
5069 case options::OPT__SLASH_MTd:
5070 CmdArgs.push_back("-D_DEBUG");
5071 CmdArgs.push_back("-D_MT");
5072 CmdArgs.push_back("-flto-visibility-public-std");
5073 FlagForCRT = "--dependent-lib=libcmtd";
5074 break;
5075 default:
5076 llvm_unreachable("Unexpected option ID.");
5077 }
5078
5079 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5080 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5081 } else {
5082 CmdArgs.push_back(FlagForCRT.data());
5083
5084 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5085 // users want. The /Za flag to cl.exe turns this off, but it's not
5086 // implemented in clang.
5087 CmdArgs.push_back("--dependent-lib=oldnames");
5088 }
5089
Erich Keane425f48d2018-05-04 15:58:31 +00005090 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5091 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005092
5093 // This controls whether or not we emit RTTI data for polymorphic types.
5094 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5095 /*default=*/false))
5096 CmdArgs.push_back("-fno-rtti-data");
5097
5098 // This controls whether or not we emit stack-protector instrumentation.
5099 // In MSVC, Buffer Security Check (/GS) is on by default.
5100 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5101 /*default=*/true)) {
5102 CmdArgs.push_back("-stack-protector");
5103 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5104 }
5105
5106 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5107 if (Arg *DebugInfoArg =
5108 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5109 options::OPT_gline_tables_only)) {
5110 *EmitCodeView = true;
5111 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5112 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5113 else
5114 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5115 CmdArgs.push_back("-gcodeview");
5116 } else {
5117 *EmitCodeView = false;
5118 }
5119
5120 const Driver &D = getToolChain().getDriver();
5121 EHFlags EH = parseClangCLEHFlags(D, Args);
5122 if (EH.Synch || EH.Asynch) {
5123 if (types::isCXX(InputType))
5124 CmdArgs.push_back("-fcxx-exceptions");
5125 CmdArgs.push_back("-fexceptions");
5126 }
5127 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5128 CmdArgs.push_back("-fexternc-nounwind");
5129
5130 // /EP should expand to -E -P.
5131 if (Args.hasArg(options::OPT__SLASH_EP)) {
5132 CmdArgs.push_back("-E");
5133 CmdArgs.push_back("-P");
5134 }
5135
5136 unsigned VolatileOptionID;
5137 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5138 getToolChain().getArch() == llvm::Triple::x86)
5139 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5140 else
5141 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5142
5143 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5144 VolatileOptionID = A->getOption().getID();
5145
5146 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5147 CmdArgs.push_back("-fms-volatile");
5148
5149 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5150 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5151 if (MostGeneralArg && BestCaseArg)
5152 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5153 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5154
5155 if (MostGeneralArg) {
5156 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5157 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5158 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5159
5160 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5161 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5162 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5163 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5164 << FirstConflict->getAsString(Args)
5165 << SecondConflict->getAsString(Args);
5166
5167 if (SingleArg)
5168 CmdArgs.push_back("-fms-memptr-rep=single");
5169 else if (MultipleArg)
5170 CmdArgs.push_back("-fms-memptr-rep=multiple");
5171 else
5172 CmdArgs.push_back("-fms-memptr-rep=virtual");
5173 }
5174
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005175 // Parse the default calling convention options.
5176 if (Arg *CCArg =
5177 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005178 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5179 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005180 unsigned DCCOptId = CCArg->getOption().getID();
5181 const char *DCCFlag = nullptr;
5182 bool ArchSupported = true;
5183 llvm::Triple::ArchType Arch = getToolChain().getArch();
5184 switch (DCCOptId) {
5185 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005186 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005187 break;
5188 case options::OPT__SLASH_Gr:
5189 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005190 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005191 break;
5192 case options::OPT__SLASH_Gz:
5193 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005194 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005195 break;
5196 case options::OPT__SLASH_Gv:
5197 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005198 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005199 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005200 case options::OPT__SLASH_Gregcall:
5201 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5202 DCCFlag = "-fdefault-calling-conv=regcall";
5203 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005204 }
5205
5206 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5207 if (ArchSupported && DCCFlag)
5208 CmdArgs.push_back(DCCFlag);
5209 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005210
5211 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5212 A->render(Args, CmdArgs);
5213
5214 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5215 CmdArgs.push_back("-fdiagnostics-format");
5216 if (Args.hasArg(options::OPT__SLASH_fallback))
5217 CmdArgs.push_back("msvc-fallback");
5218 else
5219 CmdArgs.push_back("msvc");
5220 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005221
5222 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5223 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5224 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005225}
5226
5227visualstudio::Compiler *Clang::getCLFallback() const {
5228 if (!CLFallback)
5229 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5230 return CLFallback.get();
5231}
5232
5233
5234const char *Clang::getBaseInputName(const ArgList &Args,
5235 const InputInfo &Input) {
5236 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5237}
5238
5239const char *Clang::getBaseInputStem(const ArgList &Args,
5240 const InputInfoList &Inputs) {
5241 const char *Str = getBaseInputName(Args, Inputs[0]);
5242
5243 if (const char *End = strrchr(Str, '.'))
5244 return Args.MakeArgString(std::string(Str, End));
5245
5246 return Str;
5247}
5248
5249const char *Clang::getDependencyFileName(const ArgList &Args,
5250 const InputInfoList &Inputs) {
5251 // FIXME: Think about this more.
5252 std::string Res;
5253
5254 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5255 std::string Str(OutputOpt->getValue());
5256 Res = Str.substr(0, Str.rfind('.'));
5257 } else {
5258 Res = getBaseInputStem(Args, Inputs);
5259 }
5260 return Args.MakeArgString(Res + ".d");
5261}
5262
5263// Begin ClangAs
5264
5265void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5266 ArgStringList &CmdArgs) const {
5267 StringRef CPUName;
5268 StringRef ABIName;
5269 const llvm::Triple &Triple = getToolChain().getTriple();
5270 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5271
5272 CmdArgs.push_back("-target-abi");
5273 CmdArgs.push_back(ABIName.data());
5274}
5275
5276void ClangAs::AddX86TargetArgs(const ArgList &Args,
5277 ArgStringList &CmdArgs) const {
5278 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5279 StringRef Value = A->getValue();
5280 if (Value == "intel" || Value == "att") {
5281 CmdArgs.push_back("-mllvm");
5282 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5283 } else {
5284 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5285 << A->getOption().getName() << Value;
5286 }
5287 }
5288}
5289
5290void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5291 const InputInfo &Output, const InputInfoList &Inputs,
5292 const ArgList &Args,
5293 const char *LinkingOutput) const {
5294 ArgStringList CmdArgs;
5295
5296 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5297 const InputInfo &Input = Inputs[0];
5298
5299 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5300 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005301 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005302
5303 // Don't warn about "clang -w -c foo.s"
5304 Args.ClaimAllArgs(options::OPT_w);
5305 // and "clang -emit-llvm -c foo.s"
5306 Args.ClaimAllArgs(options::OPT_emit_llvm);
5307
5308 claimNoWarnArgs(Args);
5309
5310 // Invoke ourselves in -cc1as mode.
5311 //
5312 // FIXME: Implement custom jobs for internal actions.
5313 CmdArgs.push_back("-cc1as");
5314
5315 // Add the "effective" target triple.
5316 CmdArgs.push_back("-triple");
5317 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5318
5319 // Set the output mode, we currently only expect to be used as a real
5320 // assembler.
5321 CmdArgs.push_back("-filetype");
5322 CmdArgs.push_back("obj");
5323
5324 // Set the main file name, so that debug info works even with
5325 // -save-temps or preprocessed assembly.
5326 CmdArgs.push_back("-main-file-name");
5327 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5328
5329 // Add the target cpu
5330 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5331 if (!CPU.empty()) {
5332 CmdArgs.push_back("-target-cpu");
5333 CmdArgs.push_back(Args.MakeArgString(CPU));
5334 }
5335
5336 // Add the target features
5337 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5338
5339 // Ignore explicit -force_cpusubtype_ALL option.
5340 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5341
5342 // Pass along any -I options so we get proper .include search paths.
5343 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5344
5345 // Determine the original source input.
5346 const Action *SourceAction = &JA;
5347 while (SourceAction->getKind() != Action::InputClass) {
5348 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5349 SourceAction = SourceAction->getInputs()[0];
5350 }
5351
5352 // Forward -g and handle debug info related flags, assuming we are dealing
5353 // with an actual assembly file.
5354 bool WantDebug = false;
5355 unsigned DwarfVersion = 0;
5356 Args.ClaimAllArgs(options::OPT_g_Group);
5357 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5358 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5359 !A->getOption().matches(options::OPT_ggdb0);
5360 if (WantDebug)
5361 DwarfVersion = DwarfVersionNum(A->getSpelling());
5362 }
5363 if (DwarfVersion == 0)
5364 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5365
5366 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5367
5368 if (SourceAction->getType() == types::TY_Asm ||
5369 SourceAction->getType() == types::TY_PP_Asm) {
5370 // You might think that it would be ok to set DebugInfoKind outside of
5371 // the guard for source type, however there is a test which asserts
5372 // that some assembler invocation receives no -debug-info-kind,
5373 // and it's not clear whether that test is just overly restrictive.
5374 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5375 : codegenoptions::NoDebugInfo);
5376 // Add the -fdebug-compilation-dir flag if needed.
5377 addDebugCompDirArg(Args, CmdArgs);
5378
Paul Robinson9b292b42018-07-10 15:15:24 +00005379 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5380
David L. Jonesf561aba2017-03-08 01:02:16 +00005381 // Set the AT_producer to the clang version when using the integrated
5382 // assembler on assembly source files.
5383 CmdArgs.push_back("-dwarf-debug-producer");
5384 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5385
5386 // And pass along -I options
5387 Args.AddAllArgs(CmdArgs, options::OPT_I);
5388 }
5389 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5390 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005391 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5392
David L. Jonesf561aba2017-03-08 01:02:16 +00005393
5394 // Handle -fPIC et al -- the relocation-model affects the assembler
5395 // for some targets.
5396 llvm::Reloc::Model RelocationModel;
5397 unsigned PICLevel;
5398 bool IsPIE;
5399 std::tie(RelocationModel, PICLevel, IsPIE) =
5400 ParsePICArgs(getToolChain(), Args);
5401
5402 const char *RMName = RelocationModelName(RelocationModel);
5403 if (RMName) {
5404 CmdArgs.push_back("-mrelocation-model");
5405 CmdArgs.push_back(RMName);
5406 }
5407
5408 // Optionally embed the -cc1as level arguments into the debug info, for build
5409 // analysis.
5410 if (getToolChain().UseDwarfDebugFlags()) {
5411 ArgStringList OriginalArgs;
5412 for (const auto &Arg : Args)
5413 Arg->render(Args, OriginalArgs);
5414
5415 SmallString<256> Flags;
5416 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5417 Flags += Exec;
5418 for (const char *OriginalArg : OriginalArgs) {
5419 SmallString<128> EscapedArg;
5420 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5421 Flags += " ";
5422 Flags += EscapedArg;
5423 }
5424 CmdArgs.push_back("-dwarf-debug-flags");
5425 CmdArgs.push_back(Args.MakeArgString(Flags));
5426 }
5427
5428 // FIXME: Add -static support, once we have it.
5429
5430 // Add target specific flags.
5431 switch (getToolChain().getArch()) {
5432 default:
5433 break;
5434
5435 case llvm::Triple::mips:
5436 case llvm::Triple::mipsel:
5437 case llvm::Triple::mips64:
5438 case llvm::Triple::mips64el:
5439 AddMIPSTargetArgs(Args, CmdArgs);
5440 break;
5441
5442 case llvm::Triple::x86:
5443 case llvm::Triple::x86_64:
5444 AddX86TargetArgs(Args, CmdArgs);
5445 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005446
5447 case llvm::Triple::arm:
5448 case llvm::Triple::armeb:
5449 case llvm::Triple::thumb:
5450 case llvm::Triple::thumbeb:
5451 // This isn't in AddARMTargetArgs because we want to do this for assembly
5452 // only, not C/C++.
5453 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5454 options::OPT_mno_default_build_attributes, true)) {
5455 CmdArgs.push_back("-mllvm");
5456 CmdArgs.push_back("-arm-add-build-attributes");
5457 }
5458 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005459 }
5460
5461 // Consume all the warning flags. Usually this would be handled more
5462 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5463 // doesn't handle that so rather than warning about unused flags that are
5464 // actually used, we'll lie by omission instead.
5465 // FIXME: Stop lying and consume only the appropriate driver flags
5466 Args.ClaimAllArgs(options::OPT_W_Group);
5467
5468 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5469 getToolChain().getDriver());
5470
5471 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5472
5473 assert(Output.isFilename() && "Unexpected lipo output.");
5474 CmdArgs.push_back("-o");
5475 CmdArgs.push_back(Output.getFilename());
5476
Peter Collingbourne91d02842018-05-22 18:52:37 +00005477 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5478 getToolChain().getTriple().isOSLinux()) {
5479 CmdArgs.push_back("-split-dwarf-file");
5480 CmdArgs.push_back(SplitDebugName(Args, Input));
5481 }
5482
David L. Jonesf561aba2017-03-08 01:02:16 +00005483 assert(Input.isFilename() && "Invalid input.");
5484 CmdArgs.push_back(Input.getFilename());
5485
5486 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5487 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005488}
5489
5490// Begin OffloadBundler
5491
5492void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5493 const InputInfo &Output,
5494 const InputInfoList &Inputs,
5495 const llvm::opt::ArgList &TCArgs,
5496 const char *LinkingOutput) const {
5497 // The version with only one output is expected to refer to a bundling job.
5498 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5499
5500 // The bundling command looks like this:
5501 // clang-offload-bundler -type=bc
5502 // -targets=host-triple,openmp-triple1,openmp-triple2
5503 // -outputs=input_file
5504 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5505
5506 ArgStringList CmdArgs;
5507
5508 // Get the type.
5509 CmdArgs.push_back(TCArgs.MakeArgString(
5510 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5511
5512 assert(JA.getInputs().size() == Inputs.size() &&
5513 "Not have inputs for all dependence actions??");
5514
5515 // Get the targets.
5516 SmallString<128> Triples;
5517 Triples += "-targets=";
5518 for (unsigned I = 0; I < Inputs.size(); ++I) {
5519 if (I)
5520 Triples += ',';
5521
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005522 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005523 Action::OffloadKind CurKind = Action::OFK_Host;
5524 const ToolChain *CurTC = &getToolChain();
5525 const Action *CurDep = JA.getInputs()[I];
5526
5527 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005528 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005529 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005530 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005531 CurKind = A->getOffloadingDeviceKind();
5532 CurTC = TC;
5533 });
5534 }
5535 Triples += Action::GetOffloadKindName(CurKind);
5536 Triples += '-';
5537 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005538 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5539 Triples += '-';
5540 Triples += CurDep->getOffloadingArch();
5541 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005542 }
5543 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5544
5545 // Get bundled file command.
5546 CmdArgs.push_back(
5547 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5548
5549 // Get unbundled files command.
5550 SmallString<128> UB;
5551 UB += "-inputs=";
5552 for (unsigned I = 0; I < Inputs.size(); ++I) {
5553 if (I)
5554 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005555
5556 // Find ToolChain for this input.
5557 const ToolChain *CurTC = &getToolChain();
5558 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5559 CurTC = nullptr;
5560 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5561 assert(CurTC == nullptr && "Expected one dependence!");
5562 CurTC = TC;
5563 });
5564 }
5565 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005566 }
5567 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5568
5569 // All the inputs are encoded as commands.
5570 C.addCommand(llvm::make_unique<Command>(
5571 JA, *this,
5572 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5573 CmdArgs, None));
5574}
5575
5576void OffloadBundler::ConstructJobMultipleOutputs(
5577 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5578 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5579 const char *LinkingOutput) const {
5580 // The version with multiple outputs is expected to refer to a unbundling job.
5581 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5582
5583 // The unbundling command looks like this:
5584 // clang-offload-bundler -type=bc
5585 // -targets=host-triple,openmp-triple1,openmp-triple2
5586 // -inputs=input_file
5587 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5588 // -unbundle
5589
5590 ArgStringList CmdArgs;
5591
5592 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5593 InputInfo Input = Inputs.front();
5594
5595 // Get the type.
5596 CmdArgs.push_back(TCArgs.MakeArgString(
5597 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5598
5599 // Get the targets.
5600 SmallString<128> Triples;
5601 Triples += "-targets=";
5602 auto DepInfo = UA.getDependentActionsInfo();
5603 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5604 if (I)
5605 Triples += ',';
5606
5607 auto &Dep = DepInfo[I];
5608 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5609 Triples += '-';
5610 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005611 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5612 !Dep.DependentBoundArch.empty()) {
5613 Triples += '-';
5614 Triples += Dep.DependentBoundArch;
5615 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005616 }
5617
5618 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5619
5620 // Get bundled file command.
5621 CmdArgs.push_back(
5622 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5623
5624 // Get unbundled files command.
5625 SmallString<128> UB;
5626 UB += "-outputs=";
5627 for (unsigned I = 0; I < Outputs.size(); ++I) {
5628 if (I)
5629 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005630 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005631 }
5632 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5633 CmdArgs.push_back("-unbundle");
5634
5635 // All the inputs are encoded as commands.
5636 C.addCommand(llvm::make_unique<Command>(
5637 JA, *this,
5638 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5639 CmdArgs, None));
5640}