blob: 2c0fc4e7e3d4b1580dabaf929dd0e46032a3aea1 [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
527 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI) {
528 switch (Triple.getArch()) {
529 // Don't use a frame pointer on linux if optimizing for certain targets.
530 case llvm::Triple::mips64:
531 case llvm::Triple::mips64el:
532 case llvm::Triple::mips:
533 case llvm::Triple::mipsel:
534 case llvm::Triple::ppc:
535 case llvm::Triple::ppc64:
536 case llvm::Triple::ppc64le:
537 case llvm::Triple::systemz:
538 case llvm::Triple::x86:
539 case llvm::Triple::x86_64:
540 return !areOptimizationsEnabled(Args);
541 default:
542 return true;
543 }
544 }
545
546 if (Triple.isOSWindows()) {
547 switch (Triple.getArch()) {
548 case llvm::Triple::x86:
549 return !areOptimizationsEnabled(Args);
550 case llvm::Triple::x86_64:
551 return Triple.isOSBinFormatMachO();
552 case llvm::Triple::arm:
553 case llvm::Triple::thumb:
554 // Windows on ARM builds with FPO disabled to aid fast stack walking
555 return true;
556 default:
557 // All other supported Windows ISAs use xdata unwind information, so frame
558 // pointers are not generally useful.
559 return false;
560 }
561 }
562
563 return true;
564}
565
566static bool shouldUseFramePointer(const ArgList &Args,
567 const llvm::Triple &Triple) {
568 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
569 options::OPT_fomit_frame_pointer))
570 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
571 mustUseNonLeafFramePointerForTarget(Triple);
572
573 if (Args.hasArg(options::OPT_pg))
574 return true;
575
576 return useFramePointerForTargetByDefault(Args, Triple);
577}
578
579static bool shouldUseLeafFramePointer(const ArgList &Args,
580 const llvm::Triple &Triple) {
581 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
582 options::OPT_momit_leaf_frame_pointer))
583 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
584
585 if (Args.hasArg(options::OPT_pg))
586 return true;
587
588 if (Triple.isPS4CPU())
589 return false;
590
591 return useFramePointerForTargetByDefault(Args, Triple);
592}
593
594/// Add a CC1 option to specify the debug compilation directory.
595static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
596 SmallString<128> cwd;
597 if (!llvm::sys::fs::current_path(cwd)) {
598 CmdArgs.push_back("-fdebug-compilation-dir");
599 CmdArgs.push_back(Args.MakeArgString(cwd));
600 }
601}
602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000603/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000604/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
605static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
606 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
607 if (A->getOption().matches(options::OPT_O4) ||
608 A->getOption().matches(options::OPT_Ofast))
609 return true;
610
611 if (A->getOption().matches(options::OPT_O0))
612 return false;
613
614 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
615
616 // Vectorize -Os.
617 StringRef S(A->getValue());
618 if (S == "s")
619 return true;
620
621 // Don't vectorize -Oz, unless it's the slp vectorizer.
622 if (S == "z")
623 return isSlpVec;
624
625 unsigned OptLevel = 0;
626 if (S.getAsInteger(10, OptLevel))
627 return false;
628
629 return OptLevel > 1;
630 }
631
632 return false;
633}
634
635/// Add -x lang to \p CmdArgs for \p Input.
636static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
637 ArgStringList &CmdArgs) {
638 // When using -verify-pch, we don't want to provide the type
639 // 'precompiled-header' if it was inferred from the file extension
640 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
641 return;
642
643 CmdArgs.push_back("-x");
644 if (Args.hasArg(options::OPT_rewrite_objc))
645 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000646 else {
647 // Map the driver type to the frontend type. This is mostly an identity
648 // mapping, except that the distinction between module interface units
649 // and other source files does not exist at the frontend layer.
650 const char *ClangType;
651 switch (Input.getType()) {
652 case types::TY_CXXModule:
653 ClangType = "c++";
654 break;
655 case types::TY_PP_CXXModule:
656 ClangType = "c++-cpp-output";
657 break;
658 default:
659 ClangType = types::getTypeName(Input.getType());
660 break;
661 }
662 CmdArgs.push_back(ClangType);
663 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000664}
665
666static void appendUserToPath(SmallVectorImpl<char> &Result) {
667#ifdef LLVM_ON_UNIX
668 const char *Username = getenv("LOGNAME");
669#else
670 const char *Username = getenv("USERNAME");
671#endif
672 if (Username) {
673 // Validate that LoginName can be used in a path, and get its length.
674 size_t Len = 0;
675 for (const char *P = Username; *P; ++P, ++Len) {
676 if (!clang::isAlphanumeric(*P) && *P != '_') {
677 Username = nullptr;
678 break;
679 }
680 }
681
682 if (Username && Len > 0) {
683 Result.append(Username, Username + Len);
684 return;
685 }
686 }
687
688// Fallback to user id.
689#ifdef LLVM_ON_UNIX
690 std::string UID = llvm::utostr(getuid());
691#else
692 // FIXME: Windows seems to have an 'SID' that might work.
693 std::string UID = "9999";
694#endif
695 Result.append(UID.begin(), UID.end());
696}
697
698static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
699 const InputInfo &Output, const ArgList &Args,
700 ArgStringList &CmdArgs) {
701
702 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
703 options::OPT_fprofile_generate_EQ,
704 options::OPT_fno_profile_generate);
705 if (PGOGenerateArg &&
706 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
707 PGOGenerateArg = nullptr;
708
709 auto *ProfileGenerateArg = Args.getLastArg(
710 options::OPT_fprofile_instr_generate,
711 options::OPT_fprofile_instr_generate_EQ,
712 options::OPT_fno_profile_instr_generate);
713 if (ProfileGenerateArg &&
714 ProfileGenerateArg->getOption().matches(
715 options::OPT_fno_profile_instr_generate))
716 ProfileGenerateArg = nullptr;
717
718 if (PGOGenerateArg && ProfileGenerateArg)
719 D.Diag(diag::err_drv_argument_not_allowed_with)
720 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
721
722 auto *ProfileUseArg = getLastProfileUseArg(Args);
723
724 if (PGOGenerateArg && ProfileUseArg)
725 D.Diag(diag::err_drv_argument_not_allowed_with)
726 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
727
728 if (ProfileGenerateArg && ProfileUseArg)
729 D.Diag(diag::err_drv_argument_not_allowed_with)
730 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
731
732 if (ProfileGenerateArg) {
733 if (ProfileGenerateArg->getOption().matches(
734 options::OPT_fprofile_instr_generate_EQ))
735 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
736 ProfileGenerateArg->getValue()));
737 // The default is to use Clang Instrumentation.
738 CmdArgs.push_back("-fprofile-instrument=clang");
739 }
740
741 if (PGOGenerateArg) {
742 CmdArgs.push_back("-fprofile-instrument=llvm");
743 if (PGOGenerateArg->getOption().matches(
744 options::OPT_fprofile_generate_EQ)) {
745 SmallString<128> Path(PGOGenerateArg->getValue());
746 llvm::sys::path::append(Path, "default_%m.profraw");
747 CmdArgs.push_back(
748 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
749 }
750 }
751
752 if (ProfileUseArg) {
753 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
754 CmdArgs.push_back(Args.MakeArgString(
755 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
756 else if ((ProfileUseArg->getOption().matches(
757 options::OPT_fprofile_use_EQ) ||
758 ProfileUseArg->getOption().matches(
759 options::OPT_fprofile_instr_use))) {
760 SmallString<128> Path(
761 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
762 if (Path.empty() || llvm::sys::fs::is_directory(Path))
763 llvm::sys::path::append(Path, "default.profdata");
764 CmdArgs.push_back(
765 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
766 }
767 }
768
769 if (Args.hasArg(options::OPT_ftest_coverage) ||
770 Args.hasArg(options::OPT_coverage))
771 CmdArgs.push_back("-femit-coverage-notes");
772 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
773 false) ||
774 Args.hasArg(options::OPT_coverage))
775 CmdArgs.push_back("-femit-coverage-data");
776
777 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000778 options::OPT_fno_coverage_mapping, false)) {
779 if (!ProfileGenerateArg)
780 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
781 << "-fcoverage-mapping"
782 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000783
David L. Jonesf561aba2017-03-08 01:02:16 +0000784 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000785 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000786
787 if (C.getArgs().hasArg(options::OPT_c) ||
788 C.getArgs().hasArg(options::OPT_S)) {
789 if (Output.isFilename()) {
790 CmdArgs.push_back("-coverage-notes-file");
791 SmallString<128> OutputFilename;
792 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
793 OutputFilename = FinalOutput->getValue();
794 else
795 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
796 SmallString<128> CoverageFilename = OutputFilename;
797 if (llvm::sys::path::is_relative(CoverageFilename)) {
798 SmallString<128> Pwd;
799 if (!llvm::sys::fs::current_path(Pwd)) {
800 llvm::sys::path::append(Pwd, CoverageFilename);
801 CoverageFilename.swap(Pwd);
802 }
803 }
804 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
805 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
806
807 // Leave -fprofile-dir= an unused argument unless .gcda emission is
808 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
809 // the flag used. There is no -fno-profile-dir, so the user has no
810 // targeted way to suppress the warning.
811 if (Args.hasArg(options::OPT_fprofile_arcs) ||
812 Args.hasArg(options::OPT_coverage)) {
813 CmdArgs.push_back("-coverage-data-file");
814 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
815 CoverageFilename = FProfileDir->getValue();
816 llvm::sys::path::append(CoverageFilename, OutputFilename);
817 }
818 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
819 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
820 }
821 }
822 }
823}
824
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000825/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000826static bool ContainsCompileAction(const Action *A) {
827 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
828 return true;
829
830 for (const auto &AI : A->inputs())
831 if (ContainsCompileAction(AI))
832 return true;
833
834 return false;
835}
836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000837/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000838/// This is done by default when compiling non-assembler source with -O0.
839static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
840 bool RelaxDefault = true;
841
842 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
843 RelaxDefault = A->getOption().matches(options::OPT_O0);
844
845 if (RelaxDefault) {
846 RelaxDefault = false;
847 for (const auto &Act : C.getActions()) {
848 if (ContainsCompileAction(Act)) {
849 RelaxDefault = true;
850 break;
851 }
852 }
853 }
854
855 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
856 RelaxDefault);
857}
858
859// Extract the integer N from a string spelled "-dwarf-N", returning 0
860// on mismatch. The StringRef input (rather than an Arg) allows
861// for use by the "-Xassembler" option parser.
862static unsigned DwarfVersionNum(StringRef ArgValue) {
863 return llvm::StringSwitch<unsigned>(ArgValue)
864 .Case("-gdwarf-2", 2)
865 .Case("-gdwarf-3", 3)
866 .Case("-gdwarf-4", 4)
867 .Case("-gdwarf-5", 5)
868 .Default(0);
869}
870
871static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
872 codegenoptions::DebugInfoKind DebugInfoKind,
873 unsigned DwarfVersion,
874 llvm::DebuggerKind DebuggerTuning) {
875 switch (DebugInfoKind) {
876 case codegenoptions::DebugLineTablesOnly:
877 CmdArgs.push_back("-debug-info-kind=line-tables-only");
878 break;
879 case codegenoptions::LimitedDebugInfo:
880 CmdArgs.push_back("-debug-info-kind=limited");
881 break;
882 case codegenoptions::FullDebugInfo:
883 CmdArgs.push_back("-debug-info-kind=standalone");
884 break;
885 default:
886 break;
887 }
888 if (DwarfVersion > 0)
889 CmdArgs.push_back(
890 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
891 switch (DebuggerTuning) {
892 case llvm::DebuggerKind::GDB:
893 CmdArgs.push_back("-debugger-tuning=gdb");
894 break;
895 case llvm::DebuggerKind::LLDB:
896 CmdArgs.push_back("-debugger-tuning=lldb");
897 break;
898 case llvm::DebuggerKind::SCE:
899 CmdArgs.push_back("-debugger-tuning=sce");
900 break;
901 default:
902 break;
903 }
904}
905
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000906static void RenderDebugInfoCompressionArgs(const ArgList &Args,
907 ArgStringList &CmdArgs,
908 const Driver &D) {
909 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
910 if (!A)
911 return;
912
913 if (A->getOption().getID() == options::OPT_gz) {
914 if (llvm::zlib::isAvailable())
915 CmdArgs.push_back("-compress-debug-sections");
916 else
917 D.Diag(diag::warn_debug_compression_unavailable);
918 return;
919 }
920
921 StringRef Value = A->getValue();
922 if (Value == "none") {
923 CmdArgs.push_back("-compress-debug-sections=none");
924 } else if (Value == "zlib" || Value == "zlib-gnu") {
925 if (llvm::zlib::isAvailable()) {
926 CmdArgs.push_back(
927 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
928 } else {
929 D.Diag(diag::warn_debug_compression_unavailable);
930 }
931 } else {
932 D.Diag(diag::err_drv_unsupported_option_argument)
933 << A->getOption().getName() << Value;
934 }
935}
936
David L. Jonesf561aba2017-03-08 01:02:16 +0000937static const char *RelocationModelName(llvm::Reloc::Model Model) {
938 switch (Model) {
939 case llvm::Reloc::Static:
940 return "static";
941 case llvm::Reloc::PIC_:
942 return "pic";
943 case llvm::Reloc::DynamicNoPIC:
944 return "dynamic-no-pic";
945 case llvm::Reloc::ROPI:
946 return "ropi";
947 case llvm::Reloc::RWPI:
948 return "rwpi";
949 case llvm::Reloc::ROPI_RWPI:
950 return "ropi-rwpi";
951 }
952 llvm_unreachable("Unknown Reloc::Model kind");
953}
954
955void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
956 const Driver &D, const ArgList &Args,
957 ArgStringList &CmdArgs,
958 const InputInfo &Output,
959 const InputInfoList &Inputs) const {
960 Arg *A;
961 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
962
963 CheckPreprocessingOptions(D, Args);
964
965 Args.AddLastArg(CmdArgs, options::OPT_C);
966 Args.AddLastArg(CmdArgs, options::OPT_CC);
967
968 // Handle dependency file generation.
969 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
970 (A = Args.getLastArg(options::OPT_MD)) ||
971 (A = Args.getLastArg(options::OPT_MMD))) {
972 // Determine the output location.
973 const char *DepFile;
974 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
975 DepFile = MF->getValue();
976 C.addFailureResultFile(DepFile, &JA);
977 } else if (Output.getType() == types::TY_Dependencies) {
978 DepFile = Output.getFilename();
979 } else if (A->getOption().matches(options::OPT_M) ||
980 A->getOption().matches(options::OPT_MM)) {
981 DepFile = "-";
982 } else {
983 DepFile = getDependencyFileName(Args, Inputs);
984 C.addFailureResultFile(DepFile, &JA);
985 }
986 CmdArgs.push_back("-dependency-file");
987 CmdArgs.push_back(DepFile);
988
989 // Add a default target if one wasn't specified.
990 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
991 const char *DepTarget;
992
993 // If user provided -o, that is the dependency target, except
994 // when we are only generating a dependency file.
995 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
996 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
997 DepTarget = OutputOpt->getValue();
998 } else {
999 // Otherwise derive from the base input.
1000 //
1001 // FIXME: This should use the computed output file location.
1002 SmallString<128> P(Inputs[0].getBaseInput());
1003 llvm::sys::path::replace_extension(P, "o");
1004 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1005 }
1006
Yuka Takahashicdb53482017-06-16 16:01:13 +00001007 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1008 CmdArgs.push_back("-w");
1009 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001010 CmdArgs.push_back("-MT");
1011 SmallString<128> Quoted;
1012 QuoteTarget(DepTarget, Quoted);
1013 CmdArgs.push_back(Args.MakeArgString(Quoted));
1014 }
1015
1016 if (A->getOption().matches(options::OPT_M) ||
1017 A->getOption().matches(options::OPT_MD))
1018 CmdArgs.push_back("-sys-header-deps");
1019 if ((isa<PrecompileJobAction>(JA) &&
1020 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1021 Args.hasArg(options::OPT_fmodule_file_deps))
1022 CmdArgs.push_back("-module-file-deps");
1023 }
1024
1025 if (Args.hasArg(options::OPT_MG)) {
1026 if (!A || A->getOption().matches(options::OPT_MD) ||
1027 A->getOption().matches(options::OPT_MMD))
1028 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1029 CmdArgs.push_back("-MG");
1030 }
1031
1032 Args.AddLastArg(CmdArgs, options::OPT_MP);
1033 Args.AddLastArg(CmdArgs, options::OPT_MV);
1034
1035 // Convert all -MQ <target> args to -MT <quoted target>
1036 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1037 A->claim();
1038
1039 if (A->getOption().matches(options::OPT_MQ)) {
1040 CmdArgs.push_back("-MT");
1041 SmallString<128> Quoted;
1042 QuoteTarget(A->getValue(), Quoted);
1043 CmdArgs.push_back(Args.MakeArgString(Quoted));
1044
1045 // -MT flag - no change
1046 } else {
1047 A->render(Args, CmdArgs);
1048 }
1049 }
1050
1051 // Add offload include arguments specific for CUDA. This must happen before
1052 // we -I or -include anything else, because we must pick up the CUDA headers
1053 // from the particular CUDA installation, rather than from e.g.
1054 // /usr/local/include.
1055 if (JA.isOffloading(Action::OFK_Cuda))
1056 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1057
1058 // Add -i* options, and automatically translate to
1059 // -include-pch/-include-pth for transparent PCH support. It's
1060 // wonky, but we include looking for .gch so we can support seamless
1061 // replacement into a build system already set up to be generating
1062 // .gch files.
1063 int YcIndex = -1, YuIndex = -1;
1064 {
1065 int AI = -1;
1066 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1067 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1068 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1069 // Walk the whole i_Group and skip non "-include" flags so that the index
1070 // here matches the index in the next loop below.
1071 ++AI;
1072 if (!A->getOption().matches(options::OPT_include))
1073 continue;
1074 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
1075 YcIndex = AI;
1076 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
1077 YuIndex = AI;
1078 }
1079 }
1080 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
1081 Driver::InputList Inputs;
1082 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
1083 assert(Inputs.size() == 1 && "Need one input when building pch");
1084 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
1085 Inputs[0].second->getValue()));
1086 }
1087
1088 bool RenderedImplicitInclude = false;
1089 int AI = -1;
1090 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1091 ++AI;
1092
1093 if (getToolChain().getDriver().IsCLMode() &&
1094 A->getOption().matches(options::OPT_include)) {
1095 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
1096 // include is compiled into foo.h, and everything after goes into
1097 // the .obj file. /Yufoo.h means that all includes prior to and including
1098 // foo.h are completely skipped and replaced with a use of the pch file
1099 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
1100 // just mean that the last one wins.) If /Yc and /Yu are both present
1101 // and refer to the same file, /Yc wins.
1102 // Note that OPT__SLASH_FI gets mapped to OPT_include.
1103 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
1104 // cl.exe seems to support both flags with different values, but that
1105 // seems strange (which flag does /Fp now refer to?), so don't implement
1106 // that until someone needs it.
1107 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
1108 if (PchIndex != -1) {
1109 if (isa<PrecompileJobAction>(JA)) {
1110 // When building the pch, skip all includes after the pch.
1111 assert(YcIndex != -1 && PchIndex == YcIndex);
1112 if (AI >= YcIndex)
1113 continue;
1114 } else {
1115 // When using the pch, skip all includes prior to the pch.
1116 if (AI < PchIndex) {
1117 A->claim();
1118 continue;
1119 }
1120 if (AI == PchIndex) {
1121 A->claim();
1122 CmdArgs.push_back("-include-pch");
1123 CmdArgs.push_back(
1124 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
1125 continue;
1126 }
1127 }
1128 }
1129 } else if (A->getOption().matches(options::OPT_include)) {
1130 // Handling of gcc-style gch precompiled headers.
1131 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1132 RenderedImplicitInclude = true;
1133
1134 // Use PCH if the user requested it.
1135 bool UsePCH = D.CCCUsePCH;
1136
1137 bool FoundPTH = false;
1138 bool FoundPCH = false;
1139 SmallString<128> P(A->getValue());
1140 // We want the files to have a name like foo.h.pch. Add a dummy extension
1141 // so that replace_extension does the right thing.
1142 P += ".dummy";
1143 if (UsePCH) {
1144 llvm::sys::path::replace_extension(P, "pch");
1145 if (llvm::sys::fs::exists(P))
1146 FoundPCH = true;
1147 }
1148
1149 if (!FoundPCH) {
1150 llvm::sys::path::replace_extension(P, "pth");
1151 if (llvm::sys::fs::exists(P))
1152 FoundPTH = true;
1153 }
1154
1155 if (!FoundPCH && !FoundPTH) {
1156 llvm::sys::path::replace_extension(P, "gch");
1157 if (llvm::sys::fs::exists(P)) {
1158 FoundPCH = UsePCH;
1159 FoundPTH = !UsePCH;
1160 }
1161 }
1162
1163 if (FoundPCH || FoundPTH) {
1164 if (IsFirstImplicitInclude) {
1165 A->claim();
1166 if (UsePCH)
1167 CmdArgs.push_back("-include-pch");
1168 else
1169 CmdArgs.push_back("-include-pth");
1170 CmdArgs.push_back(Args.MakeArgString(P));
1171 continue;
1172 } else {
1173 // Ignore the PCH if not first on command line and emit warning.
1174 D.Diag(diag::warn_drv_pch_not_first_include) << P
1175 << A->getAsString(Args);
1176 }
1177 }
1178 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1179 // Handling of paths which must come late. These entries are handled by
1180 // the toolchain itself after the resource dir is inserted in the right
1181 // search order.
1182 // Do not claim the argument so that the use of the argument does not
1183 // silently go unnoticed on toolchains which do not honour the option.
1184 continue;
1185 }
1186
1187 // Not translated, render as usual.
1188 A->claim();
1189 A->render(Args, CmdArgs);
1190 }
1191
1192 Args.AddAllArgs(CmdArgs,
1193 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1194 options::OPT_F, options::OPT_index_header_map});
1195
1196 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1197
1198 // FIXME: There is a very unfortunate problem here, some troubled
1199 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1200 // really support that we would have to parse and then translate
1201 // those options. :(
1202 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1203 options::OPT_Xpreprocessor);
1204
1205 // -I- is a deprecated GCC feature, reject it.
1206 if (Arg *A = Args.getLastArg(options::OPT_I_))
1207 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1208
1209 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1210 // -isysroot to the CC1 invocation.
1211 StringRef sysroot = C.getSysRoot();
1212 if (sysroot != "") {
1213 if (!Args.hasArg(options::OPT_isysroot)) {
1214 CmdArgs.push_back("-isysroot");
1215 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1216 }
1217 }
1218
1219 // Parse additional include paths from environment variables.
1220 // FIXME: We should probably sink the logic for handling these from the
1221 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1222 // CPATH - included following the user specified includes (but prior to
1223 // builtin and standard includes).
1224 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1225 // C_INCLUDE_PATH - system includes enabled when compiling C.
1226 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1227 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1228 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1229 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1230 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1231 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1232 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1233
1234 // While adding the include arguments, we also attempt to retrieve the
1235 // arguments of related offloading toolchains or arguments that are specific
1236 // of an offloading programming model.
1237
1238 // Add C++ include arguments, if needed.
1239 if (types::isCXX(Inputs[0].getType()))
1240 forAllAssociatedToolChains(C, JA, getToolChain(),
1241 [&Args, &CmdArgs](const ToolChain &TC) {
1242 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1243 });
1244
1245 // Add system include arguments for all targets but IAMCU.
1246 if (!IsIAMCU)
1247 forAllAssociatedToolChains(C, JA, getToolChain(),
1248 [&Args, &CmdArgs](const ToolChain &TC) {
1249 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1250 });
1251 else {
1252 // For IAMCU add special include arguments.
1253 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1254 }
1255}
1256
1257// FIXME: Move to target hook.
1258static bool isSignedCharDefault(const llvm::Triple &Triple) {
1259 switch (Triple.getArch()) {
1260 default:
1261 return true;
1262
1263 case llvm::Triple::aarch64:
1264 case llvm::Triple::aarch64_be:
1265 case llvm::Triple::arm:
1266 case llvm::Triple::armeb:
1267 case llvm::Triple::thumb:
1268 case llvm::Triple::thumbeb:
1269 if (Triple.isOSDarwin() || Triple.isOSWindows())
1270 return true;
1271 return false;
1272
1273 case llvm::Triple::ppc:
1274 case llvm::Triple::ppc64:
1275 if (Triple.isOSDarwin())
1276 return true;
1277 return false;
1278
1279 case llvm::Triple::hexagon:
1280 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001281 case llvm::Triple::riscv32:
1282 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001283 case llvm::Triple::systemz:
1284 case llvm::Triple::xcore:
1285 return false;
1286 }
1287}
1288
1289static bool isNoCommonDefault(const llvm::Triple &Triple) {
1290 switch (Triple.getArch()) {
1291 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001292 if (Triple.isOSFuchsia())
1293 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001294 return false;
1295
1296 case llvm::Triple::xcore:
1297 case llvm::Triple::wasm32:
1298 case llvm::Triple::wasm64:
1299 return true;
1300 }
1301}
1302
1303void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1304 ArgStringList &CmdArgs, bool KernelOrKext) const {
1305 // Select the ABI to use.
1306 // FIXME: Support -meabi.
1307 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1308 const char *ABIName = nullptr;
Eric Christopher53b2cb72017-06-30 00:03:56 +00001309 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
David L. Jonesf561aba2017-03-08 01:02:16 +00001310 ABIName = A->getValue();
Eric Christopher53b2cb72017-06-30 00:03:56 +00001311 else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001312 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001313 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001314 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001315
David L. Jonesf561aba2017-03-08 01:02:16 +00001316 CmdArgs.push_back("-target-abi");
1317 CmdArgs.push_back(ABIName);
1318
1319 // Determine floating point ABI from the options & target defaults.
1320 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1321 if (ABI == arm::FloatABI::Soft) {
1322 // Floating point operations and argument passing are soft.
1323 // FIXME: This changes CPP defines, we need -target-soft-float.
1324 CmdArgs.push_back("-msoft-float");
1325 CmdArgs.push_back("-mfloat-abi");
1326 CmdArgs.push_back("soft");
1327 } else if (ABI == arm::FloatABI::SoftFP) {
1328 // Floating point operations are hard, but argument passing is soft.
1329 CmdArgs.push_back("-mfloat-abi");
1330 CmdArgs.push_back("soft");
1331 } else {
1332 // Floating point operations and argument passing are hard.
1333 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1334 CmdArgs.push_back("-mfloat-abi");
1335 CmdArgs.push_back("hard");
1336 }
1337
1338 // Forward the -mglobal-merge option for explicit control over the pass.
1339 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1340 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001341 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001342 if (A->getOption().matches(options::OPT_mno_global_merge))
1343 CmdArgs.push_back("-arm-global-merge=false");
1344 else
1345 CmdArgs.push_back("-arm-global-merge=true");
1346 }
1347
1348 if (!Args.hasFlag(options::OPT_mimplicit_float,
1349 options::OPT_mno_implicit_float, true))
1350 CmdArgs.push_back("-no-implicit-float");
1351}
1352
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001353void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1354 const ArgList &Args, bool KernelOrKext,
1355 ArgStringList &CmdArgs) const {
1356 const ToolChain &TC = getToolChain();
1357
1358 // Add the target features
1359 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1360
1361 // Add target specific flags.
1362 switch (TC.getArch()) {
1363 default:
1364 break;
1365
1366 case llvm::Triple::arm:
1367 case llvm::Triple::armeb:
1368 case llvm::Triple::thumb:
1369 case llvm::Triple::thumbeb:
1370 // Use the effective triple, which takes into account the deployment target.
1371 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1372 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1373 break;
1374
1375 case llvm::Triple::aarch64:
1376 case llvm::Triple::aarch64_be:
1377 AddAArch64TargetArgs(Args, CmdArgs);
1378 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1379 break;
1380
1381 case llvm::Triple::mips:
1382 case llvm::Triple::mipsel:
1383 case llvm::Triple::mips64:
1384 case llvm::Triple::mips64el:
1385 AddMIPSTargetArgs(Args, CmdArgs);
1386 break;
1387
1388 case llvm::Triple::ppc:
1389 case llvm::Triple::ppc64:
1390 case llvm::Triple::ppc64le:
1391 AddPPCTargetArgs(Args, CmdArgs);
1392 break;
1393
Alex Bradbury71f45452018-01-11 13:36:56 +00001394 case llvm::Triple::riscv32:
1395 case llvm::Triple::riscv64:
1396 AddRISCVTargetArgs(Args, CmdArgs);
1397 break;
1398
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001399 case llvm::Triple::sparc:
1400 case llvm::Triple::sparcel:
1401 case llvm::Triple::sparcv9:
1402 AddSparcTargetArgs(Args, CmdArgs);
1403 break;
1404
1405 case llvm::Triple::systemz:
1406 AddSystemZTargetArgs(Args, CmdArgs);
1407 break;
1408
1409 case llvm::Triple::x86:
1410 case llvm::Triple::x86_64:
1411 AddX86TargetArgs(Args, CmdArgs);
1412 break;
1413
1414 case llvm::Triple::lanai:
1415 AddLanaiTargetArgs(Args, CmdArgs);
1416 break;
1417
1418 case llvm::Triple::hexagon:
1419 AddHexagonTargetArgs(Args, CmdArgs);
1420 break;
1421
1422 case llvm::Triple::wasm32:
1423 case llvm::Triple::wasm64:
1424 AddWebAssemblyTargetArgs(Args, CmdArgs);
1425 break;
1426 }
1427}
1428
David L. Jonesf561aba2017-03-08 01:02:16 +00001429void Clang::AddAArch64TargetArgs(const ArgList &Args,
1430 ArgStringList &CmdArgs) const {
1431 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1432
1433 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1434 Args.hasArg(options::OPT_mkernel) ||
1435 Args.hasArg(options::OPT_fapple_kext))
1436 CmdArgs.push_back("-disable-red-zone");
1437
1438 if (!Args.hasFlag(options::OPT_mimplicit_float,
1439 options::OPT_mno_implicit_float, true))
1440 CmdArgs.push_back("-no-implicit-float");
1441
1442 const char *ABIName = nullptr;
1443 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1444 ABIName = A->getValue();
1445 else if (Triple.isOSDarwin())
1446 ABIName = "darwinpcs";
1447 else
1448 ABIName = "aapcs";
1449
1450 CmdArgs.push_back("-target-abi");
1451 CmdArgs.push_back(ABIName);
1452
1453 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1454 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001455 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001456 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1457 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1458 else
1459 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1460 } else if (Triple.isAndroid()) {
1461 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001462 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001463 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1464 }
1465
1466 // Forward the -mglobal-merge option for explicit control over the pass.
1467 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1468 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001469 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001470 if (A->getOption().matches(options::OPT_mno_global_merge))
1471 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1472 else
1473 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1474 }
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001475
Jessica Paquette544bb552018-05-08 20:58:32 +00001476 if (!Args.hasArg(options::OPT_mno_outline) &&
1477 Args.getLastArg(options::OPT_moutline)) {
Jessica Paquette8e71ee32018-05-02 16:42:51 +00001478 CmdArgs.push_back("-mllvm");
1479 CmdArgs.push_back("-enable-machine-outliner");
1480 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001481}
1482
1483void Clang::AddMIPSTargetArgs(const ArgList &Args,
1484 ArgStringList &CmdArgs) const {
1485 const Driver &D = getToolChain().getDriver();
1486 StringRef CPUName;
1487 StringRef ABIName;
1488 const llvm::Triple &Triple = getToolChain().getTriple();
1489 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1490
1491 CmdArgs.push_back("-target-abi");
1492 CmdArgs.push_back(ABIName.data());
1493
1494 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1495 if (ABI == mips::FloatABI::Soft) {
1496 // Floating point operations and argument passing are soft.
1497 CmdArgs.push_back("-msoft-float");
1498 CmdArgs.push_back("-mfloat-abi");
1499 CmdArgs.push_back("soft");
1500 } else {
1501 // Floating point operations and argument passing are hard.
1502 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1503 CmdArgs.push_back("-mfloat-abi");
1504 CmdArgs.push_back("hard");
1505 }
1506
1507 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1508 if (A->getOption().matches(options::OPT_mxgot)) {
1509 CmdArgs.push_back("-mllvm");
1510 CmdArgs.push_back("-mxgot");
1511 }
1512 }
1513
1514 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1515 options::OPT_mno_ldc1_sdc1)) {
1516 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1517 CmdArgs.push_back("-mllvm");
1518 CmdArgs.push_back("-mno-ldc1-sdc1");
1519 }
1520 }
1521
1522 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1523 options::OPT_mno_check_zero_division)) {
1524 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1525 CmdArgs.push_back("-mllvm");
1526 CmdArgs.push_back("-mno-check-zero-division");
1527 }
1528 }
1529
1530 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1531 StringRef v = A->getValue();
1532 CmdArgs.push_back("-mllvm");
1533 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1534 A->claim();
1535 }
1536
Simon Dardis31636a12017-07-20 14:04:12 +00001537 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1538 Arg *ABICalls =
1539 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1540
1541 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1542 // -mgpopt is the default for static, -fno-pic environments but these two
1543 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1544 // the only case where -mllvm -mgpopt is passed.
1545 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1546 // passed explicitly when compiling something with -mabicalls
1547 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001548 //
1549 // When the ABI in use is N64, we also need to determine the PIC mode that
1550 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001551 bool NoABICalls =
1552 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001553
1554 llvm::Reloc::Model RelocationModel;
1555 unsigned PICLevel;
1556 bool IsPIE;
1557 std::tie(RelocationModel, PICLevel, IsPIE) =
1558 ParsePICArgs(getToolChain(), Args);
1559
1560 NoABICalls = NoABICalls ||
1561 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1562
Simon Dardis31636a12017-07-20 14:04:12 +00001563 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1564 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1565 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1566 CmdArgs.push_back("-mllvm");
1567 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001568
1569 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1570 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001571 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001572 options::OPT_mno_extern_sdata);
1573 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1574 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001575 if (LocalSData) {
1576 CmdArgs.push_back("-mllvm");
1577 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1578 CmdArgs.push_back("-mlocal-sdata=1");
1579 } else {
1580 CmdArgs.push_back("-mlocal-sdata=0");
1581 }
1582 LocalSData->claim();
1583 }
1584
Simon Dardis7d318782017-07-24 14:02:09 +00001585 if (ExternSData) {
1586 CmdArgs.push_back("-mllvm");
1587 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1588 CmdArgs.push_back("-mextern-sdata=1");
1589 } else {
1590 CmdArgs.push_back("-mextern-sdata=0");
1591 }
1592 ExternSData->claim();
1593 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001594
1595 if (EmbeddedData) {
1596 CmdArgs.push_back("-mllvm");
1597 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1598 CmdArgs.push_back("-membedded-data=1");
1599 } else {
1600 CmdArgs.push_back("-membedded-data=0");
1601 }
1602 EmbeddedData->claim();
1603 }
1604
Simon Dardis31636a12017-07-20 14:04:12 +00001605 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1606 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1607
1608 if (GPOpt)
1609 GPOpt->claim();
1610
David L. Jonesf561aba2017-03-08 01:02:16 +00001611 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1612 StringRef Val = StringRef(A->getValue());
1613 if (mips::hasCompactBranches(CPUName)) {
1614 if (Val == "never" || Val == "always" || Val == "optimal") {
1615 CmdArgs.push_back("-mllvm");
1616 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1617 } else
1618 D.Diag(diag::err_drv_unsupported_option_argument)
1619 << A->getOption().getName() << Val;
1620 } else
1621 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1622 }
1623}
1624
1625void Clang::AddPPCTargetArgs(const ArgList &Args,
1626 ArgStringList &CmdArgs) const {
1627 // Select the ABI to use.
1628 const char *ABIName = nullptr;
1629 if (getToolChain().getTriple().isOSLinux())
1630 switch (getToolChain().getArch()) {
1631 case llvm::Triple::ppc64: {
1632 // When targeting a processor that supports QPX, or if QPX is
1633 // specifically enabled, default to using the ABI that supports QPX (so
1634 // long as it is not specifically disabled).
1635 bool HasQPX = false;
1636 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1637 HasQPX = A->getValue() == StringRef("a2q");
1638 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1639 if (HasQPX) {
1640 ABIName = "elfv1-qpx";
1641 break;
1642 }
1643
1644 ABIName = "elfv1";
1645 break;
1646 }
1647 case llvm::Triple::ppc64le:
1648 ABIName = "elfv2";
1649 break;
1650 default:
1651 break;
1652 }
1653
1654 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1655 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1656 // the option if given as we don't have backend support for any targets
1657 // that don't use the altivec abi.
1658 if (StringRef(A->getValue()) != "altivec")
1659 ABIName = A->getValue();
1660
1661 ppc::FloatABI FloatABI =
1662 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1663
1664 if (FloatABI == ppc::FloatABI::Soft) {
1665 // Floating point operations and argument passing are soft.
1666 CmdArgs.push_back("-msoft-float");
1667 CmdArgs.push_back("-mfloat-abi");
1668 CmdArgs.push_back("soft");
1669 } else {
1670 // Floating point operations and argument passing are hard.
1671 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1672 CmdArgs.push_back("-mfloat-abi");
1673 CmdArgs.push_back("hard");
1674 }
1675
1676 if (ABIName) {
1677 CmdArgs.push_back("-target-abi");
1678 CmdArgs.push_back(ABIName);
1679 }
1680}
1681
Alex Bradbury71f45452018-01-11 13:36:56 +00001682void Clang::AddRISCVTargetArgs(const ArgList &Args,
1683 ArgStringList &CmdArgs) const {
1684 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001685 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001686 const char *ABIName = nullptr;
1687 const llvm::Triple &Triple = getToolChain().getTriple();
1688 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1689 ABIName = A->getValue();
1690 else if (Triple.getArch() == llvm::Triple::riscv32)
1691 ABIName = "ilp32";
1692 else if (Triple.getArch() == llvm::Triple::riscv64)
1693 ABIName = "lp64";
1694 else
1695 llvm_unreachable("Unexpected triple!");
1696
1697 CmdArgs.push_back("-target-abi");
1698 CmdArgs.push_back(ABIName);
1699}
1700
David L. Jonesf561aba2017-03-08 01:02:16 +00001701void Clang::AddSparcTargetArgs(const ArgList &Args,
1702 ArgStringList &CmdArgs) const {
1703 sparc::FloatABI FloatABI =
1704 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1705
1706 if (FloatABI == sparc::FloatABI::Soft) {
1707 // Floating point operations and argument passing are soft.
1708 CmdArgs.push_back("-msoft-float");
1709 CmdArgs.push_back("-mfloat-abi");
1710 CmdArgs.push_back("soft");
1711 } else {
1712 // Floating point operations and argument passing are hard.
1713 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1714 CmdArgs.push_back("-mfloat-abi");
1715 CmdArgs.push_back("hard");
1716 }
1717}
1718
1719void Clang::AddSystemZTargetArgs(const ArgList &Args,
1720 ArgStringList &CmdArgs) const {
1721 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1722 CmdArgs.push_back("-mbackchain");
1723}
1724
1725void Clang::AddX86TargetArgs(const ArgList &Args,
1726 ArgStringList &CmdArgs) const {
1727 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1728 Args.hasArg(options::OPT_mkernel) ||
1729 Args.hasArg(options::OPT_fapple_kext))
1730 CmdArgs.push_back("-disable-red-zone");
1731
1732 // Default to avoid implicit floating-point for kernel/kext code, but allow
1733 // that to be overridden with -mno-soft-float.
1734 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1735 Args.hasArg(options::OPT_fapple_kext));
1736 if (Arg *A = Args.getLastArg(
1737 options::OPT_msoft_float, options::OPT_mno_soft_float,
1738 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1739 const Option &O = A->getOption();
1740 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1741 O.matches(options::OPT_msoft_float));
1742 }
1743 if (NoImplicitFloat)
1744 CmdArgs.push_back("-no-implicit-float");
1745
1746 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1747 StringRef Value = A->getValue();
1748 if (Value == "intel" || Value == "att") {
1749 CmdArgs.push_back("-mllvm");
1750 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1751 } else {
1752 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1753 << A->getOption().getName() << Value;
1754 }
Nico Webere3712cf2018-01-17 13:34:20 +00001755 } else if (getToolChain().getDriver().IsCLMode()) {
1756 CmdArgs.push_back("-mllvm");
1757 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001758 }
1759
1760 // Set flags to support MCU ABI.
1761 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1762 CmdArgs.push_back("-mfloat-abi");
1763 CmdArgs.push_back("soft");
1764 CmdArgs.push_back("-mstack-alignment=4");
1765 }
1766}
1767
1768void Clang::AddHexagonTargetArgs(const ArgList &Args,
1769 ArgStringList &CmdArgs) const {
1770 CmdArgs.push_back("-mqdsp6-compat");
1771 CmdArgs.push_back("-Wreturn-type");
1772
1773 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001774 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001775 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1776 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001777 }
1778
1779 if (!Args.hasArg(options::OPT_fno_short_enums))
1780 CmdArgs.push_back("-fshort-enums");
1781 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1782 CmdArgs.push_back("-mllvm");
1783 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1784 }
1785 CmdArgs.push_back("-mllvm");
1786 CmdArgs.push_back("-machine-sink-split=0");
1787}
1788
1789void Clang::AddLanaiTargetArgs(const ArgList &Args,
1790 ArgStringList &CmdArgs) const {
1791 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1792 StringRef CPUName = A->getValue();
1793
1794 CmdArgs.push_back("-target-cpu");
1795 CmdArgs.push_back(Args.MakeArgString(CPUName));
1796 }
1797 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1798 StringRef Value = A->getValue();
1799 // Only support mregparm=4 to support old usage. Report error for all other
1800 // cases.
1801 int Mregparm;
1802 if (Value.getAsInteger(10, Mregparm)) {
1803 if (Mregparm != 4) {
1804 getToolChain().getDriver().Diag(
1805 diag::err_drv_unsupported_option_argument)
1806 << A->getOption().getName() << Value;
1807 }
1808 }
1809 }
1810}
1811
1812void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1813 ArgStringList &CmdArgs) const {
1814 // Default to "hidden" visibility.
1815 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1816 options::OPT_fvisibility_ms_compat)) {
1817 CmdArgs.push_back("-fvisibility");
1818 CmdArgs.push_back("hidden");
1819 }
1820}
1821
1822void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1823 StringRef Target, const InputInfo &Output,
1824 const InputInfo &Input, const ArgList &Args) const {
1825 // If this is a dry run, do not create the compilation database file.
1826 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1827 return;
1828
1829 using llvm::yaml::escape;
1830 const Driver &D = getToolChain().getDriver();
1831
1832 if (!CompilationDatabase) {
1833 std::error_code EC;
1834 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1835 if (EC) {
1836 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1837 << EC.message();
1838 return;
1839 }
1840 CompilationDatabase = std::move(File);
1841 }
1842 auto &CDB = *CompilationDatabase;
1843 SmallString<128> Buf;
1844 if (llvm::sys::fs::current_path(Buf))
1845 Buf = ".";
1846 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1847 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1848 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1849 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1850 Buf = "-x";
1851 Buf += types::getTypeName(Input.getType());
1852 CDB << ", \"" << escape(Buf) << "\"";
1853 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1854 Buf = "--sysroot=";
1855 Buf += D.SysRoot;
1856 CDB << ", \"" << escape(Buf) << "\"";
1857 }
1858 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1859 for (auto &A: Args) {
1860 auto &O = A->getOption();
1861 // Skip language selection, which is positional.
1862 if (O.getID() == options::OPT_x)
1863 continue;
1864 // Skip writing dependency output and the compilation database itself.
1865 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1866 continue;
1867 // Skip inputs.
1868 if (O.getKind() == Option::InputClass)
1869 continue;
1870 // All other arguments are quoted and appended.
1871 ArgStringList ASL;
1872 A->render(Args, ASL);
1873 for (auto &it: ASL)
1874 CDB << ", \"" << escape(it) << "\"";
1875 }
1876 Buf = "--target=";
1877 Buf += Target;
1878 CDB << ", \"" << escape(Buf) << "\"]},\n";
1879}
1880
1881static void CollectArgsForIntegratedAssembler(Compilation &C,
1882 const ArgList &Args,
1883 ArgStringList &CmdArgs,
1884 const Driver &D) {
1885 if (UseRelaxAll(C, Args))
1886 CmdArgs.push_back("-mrelax-all");
1887
1888 // Only default to -mincremental-linker-compatible if we think we are
1889 // targeting the MSVC linker.
1890 bool DefaultIncrementalLinkerCompatible =
1891 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1892 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1893 options::OPT_mno_incremental_linker_compatible,
1894 DefaultIncrementalLinkerCompatible))
1895 CmdArgs.push_back("-mincremental-linker-compatible");
1896
1897 switch (C.getDefaultToolChain().getArch()) {
1898 case llvm::Triple::arm:
1899 case llvm::Triple::armeb:
1900 case llvm::Triple::thumb:
1901 case llvm::Triple::thumbeb:
1902 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1903 StringRef Value = A->getValue();
1904 if (Value == "always" || Value == "never" || Value == "arm" ||
1905 Value == "thumb") {
1906 CmdArgs.push_back("-mllvm");
1907 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1908 } else {
1909 D.Diag(diag::err_drv_unsupported_option_argument)
1910 << A->getOption().getName() << Value;
1911 }
1912 }
1913 break;
1914 default:
1915 break;
1916 }
1917
1918 // When passing -I arguments to the assembler we sometimes need to
1919 // unconditionally take the next argument. For example, when parsing
1920 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1921 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1922 // arg after parsing the '-I' arg.
1923 bool TakeNextArg = false;
1924
Petr Hosek5668d832017-11-22 01:38:31 +00001925 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001926 const char *MipsTargetFeature = nullptr;
1927 for (const Arg *A :
1928 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1929 A->claim();
1930
1931 for (StringRef Value : A->getValues()) {
1932 if (TakeNextArg) {
1933 CmdArgs.push_back(Value.data());
1934 TakeNextArg = false;
1935 continue;
1936 }
1937
1938 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1939 Value == "-mbig-obj")
1940 continue; // LLVM handles bigobj automatically
1941
1942 switch (C.getDefaultToolChain().getArch()) {
1943 default:
1944 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001945 case llvm::Triple::thumb:
1946 case llvm::Triple::thumbeb:
1947 case llvm::Triple::arm:
1948 case llvm::Triple::armeb:
1949 if (Value == "-mthumb")
1950 // -mthumb has already been processed in ComputeLLVMTriple()
1951 // recognize but skip over here.
1952 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001953 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001954 case llvm::Triple::mips:
1955 case llvm::Triple::mipsel:
1956 case llvm::Triple::mips64:
1957 case llvm::Triple::mips64el:
1958 if (Value == "--trap") {
1959 CmdArgs.push_back("-target-feature");
1960 CmdArgs.push_back("+use-tcc-in-div");
1961 continue;
1962 }
1963 if (Value == "--break") {
1964 CmdArgs.push_back("-target-feature");
1965 CmdArgs.push_back("-use-tcc-in-div");
1966 continue;
1967 }
1968 if (Value.startswith("-msoft-float")) {
1969 CmdArgs.push_back("-target-feature");
1970 CmdArgs.push_back("+soft-float");
1971 continue;
1972 }
1973 if (Value.startswith("-mhard-float")) {
1974 CmdArgs.push_back("-target-feature");
1975 CmdArgs.push_back("-soft-float");
1976 continue;
1977 }
1978
1979 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1980 .Case("-mips1", "+mips1")
1981 .Case("-mips2", "+mips2")
1982 .Case("-mips3", "+mips3")
1983 .Case("-mips4", "+mips4")
1984 .Case("-mips5", "+mips5")
1985 .Case("-mips32", "+mips32")
1986 .Case("-mips32r2", "+mips32r2")
1987 .Case("-mips32r3", "+mips32r3")
1988 .Case("-mips32r5", "+mips32r5")
1989 .Case("-mips32r6", "+mips32r6")
1990 .Case("-mips64", "+mips64")
1991 .Case("-mips64r2", "+mips64r2")
1992 .Case("-mips64r3", "+mips64r3")
1993 .Case("-mips64r5", "+mips64r5")
1994 .Case("-mips64r6", "+mips64r6")
1995 .Default(nullptr);
1996 if (MipsTargetFeature)
1997 continue;
1998 }
1999
2000 if (Value == "-force_cpusubtype_ALL") {
2001 // Do nothing, this is the default and we don't support anything else.
2002 } else if (Value == "-L") {
2003 CmdArgs.push_back("-msave-temp-labels");
2004 } else if (Value == "--fatal-warnings") {
2005 CmdArgs.push_back("-massembler-fatal-warnings");
2006 } else if (Value == "--noexecstack") {
2007 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002008 } else if (Value.startswith("-compress-debug-sections") ||
2009 Value.startswith("--compress-debug-sections") ||
2010 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002011 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002012 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002013 } else if (Value == "-mrelax-relocations=yes" ||
2014 Value == "--mrelax-relocations=yes") {
2015 UseRelaxRelocations = true;
2016 } else if (Value == "-mrelax-relocations=no" ||
2017 Value == "--mrelax-relocations=no") {
2018 UseRelaxRelocations = false;
2019 } else if (Value.startswith("-I")) {
2020 CmdArgs.push_back(Value.data());
2021 // We need to consume the next argument if the current arg is a plain
2022 // -I. The next arg will be the include directory.
2023 if (Value == "-I")
2024 TakeNextArg = true;
2025 } else if (Value.startswith("-gdwarf-")) {
2026 // "-gdwarf-N" options are not cc1as options.
2027 unsigned DwarfVersion = DwarfVersionNum(Value);
2028 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2029 CmdArgs.push_back(Value.data());
2030 } else {
2031 RenderDebugEnablingArgs(Args, CmdArgs,
2032 codegenoptions::LimitedDebugInfo,
2033 DwarfVersion, llvm::DebuggerKind::Default);
2034 }
2035 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2036 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2037 // Do nothing, we'll validate it later.
2038 } else if (Value == "-defsym") {
2039 if (A->getNumValues() != 2) {
2040 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2041 break;
2042 }
2043 const char *S = A->getValue(1);
2044 auto Pair = StringRef(S).split('=');
2045 auto Sym = Pair.first;
2046 auto SVal = Pair.second;
2047
2048 if (Sym.empty() || SVal.empty()) {
2049 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2050 break;
2051 }
2052 int64_t IVal;
2053 if (SVal.getAsInteger(0, IVal)) {
2054 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2055 break;
2056 }
2057 CmdArgs.push_back(Value.data());
2058 TakeNextArg = true;
2059 } else {
2060 D.Diag(diag::err_drv_unsupported_option_argument)
2061 << A->getOption().getName() << Value;
2062 }
2063 }
2064 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002065 if (UseRelaxRelocations)
2066 CmdArgs.push_back("--mrelax-relocations");
2067 if (MipsTargetFeature != nullptr) {
2068 CmdArgs.push_back("-target-feature");
2069 CmdArgs.push_back(MipsTargetFeature);
2070 }
2071}
2072
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002073static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2074 bool OFastEnabled, const ArgList &Args,
2075 ArgStringList &CmdArgs) {
2076 // Handle various floating point optimization flags, mapping them to the
2077 // appropriate LLVM code generation flags. This is complicated by several
2078 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002079 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002080 // LLVM flags based on the final state.
2081 bool HonorINFs = true;
2082 bool HonorNaNs = true;
2083 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2084 bool MathErrno = TC.IsMathErrnoDefault();
2085 bool AssociativeMath = false;
2086 bool ReciprocalMath = false;
2087 bool SignedZeros = true;
2088 bool TrappingMath = true;
2089 StringRef DenormalFPMath = "";
2090 StringRef FPContract = "";
2091
2092 for (const Arg *A : Args) {
2093 switch (A->getOption().getID()) {
2094 // If this isn't an FP option skip the claim below
2095 default: continue;
2096
2097 // Options controlling individual features
2098 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2099 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2100 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2101 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2102 case options::OPT_fmath_errno: MathErrno = true; break;
2103 case options::OPT_fno_math_errno: MathErrno = false; break;
2104 case options::OPT_fassociative_math: AssociativeMath = true; break;
2105 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2106 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2107 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2108 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2109 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2110 case options::OPT_ftrapping_math: TrappingMath = true; break;
2111 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2112
2113 case options::OPT_fdenormal_fp_math_EQ:
2114 DenormalFPMath = A->getValue();
2115 break;
2116
2117 // Validate and pass through -fp-contract option.
2118 case options::OPT_ffp_contract: {
2119 StringRef Val = A->getValue();
2120 if (Val == "fast" || Val == "on" || Val == "off")
2121 FPContract = Val;
2122 else
2123 D.Diag(diag::err_drv_unsupported_option_argument)
2124 << A->getOption().getName() << Val;
2125 break;
2126 }
2127
2128 case options::OPT_ffinite_math_only:
2129 HonorINFs = false;
2130 HonorNaNs = false;
2131 break;
2132 case options::OPT_fno_finite_math_only:
2133 HonorINFs = true;
2134 HonorNaNs = true;
2135 break;
2136
2137 case options::OPT_funsafe_math_optimizations:
2138 AssociativeMath = true;
2139 ReciprocalMath = true;
2140 SignedZeros = false;
2141 TrappingMath = false;
2142 break;
2143 case options::OPT_fno_unsafe_math_optimizations:
2144 AssociativeMath = false;
2145 ReciprocalMath = false;
2146 SignedZeros = true;
2147 TrappingMath = true;
2148 // -fno_unsafe_math_optimizations restores default denormal handling
2149 DenormalFPMath = "";
2150 break;
2151
2152 case options::OPT_Ofast:
2153 // If -Ofast is the optimization level, then -ffast-math should be enabled
2154 if (!OFastEnabled)
2155 continue;
2156 LLVM_FALLTHROUGH;
2157 case options::OPT_ffast_math:
2158 HonorINFs = false;
2159 HonorNaNs = false;
2160 MathErrno = false;
2161 AssociativeMath = true;
2162 ReciprocalMath = true;
2163 SignedZeros = false;
2164 TrappingMath = false;
2165 // If fast-math is set then set the fp-contract mode to fast.
2166 FPContract = "fast";
2167 break;
2168 case options::OPT_fno_fast_math:
2169 HonorINFs = true;
2170 HonorNaNs = true;
2171 // Turning on -ffast-math (with either flag) removes the need for
2172 // MathErrno. However, turning *off* -ffast-math merely restores the
2173 // toolchain default (which may be false).
2174 MathErrno = TC.IsMathErrnoDefault();
2175 AssociativeMath = false;
2176 ReciprocalMath = false;
2177 SignedZeros = true;
2178 TrappingMath = true;
2179 // -fno_fast_math restores default denormal and fpcontract handling
2180 DenormalFPMath = "";
2181 FPContract = "";
2182 break;
2183 }
2184
2185 // If we handled this option claim it
2186 A->claim();
2187 }
2188
2189 if (!HonorINFs)
2190 CmdArgs.push_back("-menable-no-infs");
2191
2192 if (!HonorNaNs)
2193 CmdArgs.push_back("-menable-no-nans");
2194
2195 if (MathErrno)
2196 CmdArgs.push_back("-fmath-errno");
2197
2198 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2199 !TrappingMath)
2200 CmdArgs.push_back("-menable-unsafe-fp-math");
2201
2202 if (!SignedZeros)
2203 CmdArgs.push_back("-fno-signed-zeros");
2204
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002205 if (AssociativeMath && !SignedZeros && !TrappingMath)
2206 CmdArgs.push_back("-mreassociate");
2207
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002208 if (ReciprocalMath)
2209 CmdArgs.push_back("-freciprocal-math");
2210
2211 if (!TrappingMath)
2212 CmdArgs.push_back("-fno-trapping-math");
2213
2214 if (!DenormalFPMath.empty())
2215 CmdArgs.push_back(
2216 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2217
2218 if (!FPContract.empty())
2219 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2220
2221 ParseMRecip(D, Args, CmdArgs);
2222
2223 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2224 // individual features enabled by -ffast-math instead of the option itself as
2225 // that's consistent with gcc's behaviour.
2226 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2227 ReciprocalMath && !SignedZeros && !TrappingMath)
2228 CmdArgs.push_back("-ffast-math");
2229
2230 // Handle __FINITE_MATH_ONLY__ similarly.
2231 if (!HonorINFs && !HonorNaNs)
2232 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002233
2234 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2235 CmdArgs.push_back("-mfpmath");
2236 CmdArgs.push_back(A->getValue());
2237 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002238
2239 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002240 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2241 options::OPT_fstrict_float_cast_overflow, false))
2242 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002243}
2244
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002245static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2246 const llvm::Triple &Triple,
2247 const InputInfo &Input) {
2248 // Enable region store model by default.
2249 CmdArgs.push_back("-analyzer-store=region");
2250
2251 // Treat blocks as analysis entry points.
2252 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2253
2254 CmdArgs.push_back("-analyzer-eagerly-assume");
2255
2256 // Add default argument set.
2257 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2258 CmdArgs.push_back("-analyzer-checker=core");
2259 CmdArgs.push_back("-analyzer-checker=apiModeling");
2260
2261 if (!Triple.isWindowsMSVCEnvironment()) {
2262 CmdArgs.push_back("-analyzer-checker=unix");
2263 } else {
2264 // Enable "unix" checkers that also work on Windows.
2265 CmdArgs.push_back("-analyzer-checker=unix.API");
2266 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2267 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2268 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2269 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2270 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2271 }
2272
2273 // Disable some unix checkers for PS4.
2274 if (Triple.isPS4CPU()) {
2275 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2276 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2277 }
2278
2279 if (Triple.isOSDarwin())
2280 CmdArgs.push_back("-analyzer-checker=osx");
2281
2282 CmdArgs.push_back("-analyzer-checker=deadcode");
2283
2284 if (types::isCXX(Input.getType()))
2285 CmdArgs.push_back("-analyzer-checker=cplusplus");
2286
2287 if (!Triple.isPS4CPU()) {
2288 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2289 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2290 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2291 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2292 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2293 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2294 }
2295
2296 // Default nullability checks.
2297 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2298 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2299 }
2300
2301 // Set the output format. The default is plist, for (lame) historical reasons.
2302 CmdArgs.push_back("-analyzer-output");
2303 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2304 CmdArgs.push_back(A->getValue());
2305 else
2306 CmdArgs.push_back("plist");
2307
2308 // Disable the presentation of standard compiler warnings when using
2309 // --analyze. We only want to show static analyzer diagnostics or frontend
2310 // errors.
2311 CmdArgs.push_back("-w");
2312
2313 // Add -Xanalyzer arguments when running as analyzer.
2314 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2315}
2316
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002317static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002318 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002319 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2320
2321 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2322 // doesn't even have a stack!
2323 if (EffectiveTriple.isNVPTX())
2324 return;
2325
2326 // -stack-protector=0 is default.
2327 unsigned StackProtectorLevel = 0;
2328 unsigned DefaultStackProtectorLevel =
2329 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2330
2331 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2332 options::OPT_fstack_protector_all,
2333 options::OPT_fstack_protector_strong,
2334 options::OPT_fstack_protector)) {
2335 if (A->getOption().matches(options::OPT_fstack_protector))
2336 StackProtectorLevel =
2337 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2338 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2339 StackProtectorLevel = LangOptions::SSPStrong;
2340 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2341 StackProtectorLevel = LangOptions::SSPReq;
2342 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002343 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002344 }
2345
2346 if (StackProtectorLevel) {
2347 CmdArgs.push_back("-stack-protector");
2348 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2349 }
2350
2351 // --param ssp-buffer-size=
2352 for (const Arg *A : Args.filtered(options::OPT__param)) {
2353 StringRef Str(A->getValue());
2354 if (Str.startswith("ssp-buffer-size=")) {
2355 if (StackProtectorLevel) {
2356 CmdArgs.push_back("-stack-protector-buffer-size");
2357 // FIXME: Verify the argument is a valid integer.
2358 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2359 }
2360 A->claim();
2361 }
2362 }
2363}
2364
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002365static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2366 const unsigned ForwardedArguments[] = {
2367 options::OPT_cl_opt_disable,
2368 options::OPT_cl_strict_aliasing,
2369 options::OPT_cl_single_precision_constant,
2370 options::OPT_cl_finite_math_only,
2371 options::OPT_cl_kernel_arg_info,
2372 options::OPT_cl_unsafe_math_optimizations,
2373 options::OPT_cl_fast_relaxed_math,
2374 options::OPT_cl_mad_enable,
2375 options::OPT_cl_no_signed_zeros,
2376 options::OPT_cl_denorms_are_zero,
2377 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002378 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002379 };
2380
2381 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2382 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2383 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2384 }
2385
2386 for (const auto &Arg : ForwardedArguments)
2387 if (const auto *A = Args.getLastArg(Arg))
2388 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2389}
2390
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002391static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2392 ArgStringList &CmdArgs) {
2393 bool ARCMTEnabled = false;
2394 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2395 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2396 options::OPT_ccc_arcmt_modify,
2397 options::OPT_ccc_arcmt_migrate)) {
2398 ARCMTEnabled = true;
2399 switch (A->getOption().getID()) {
2400 default: llvm_unreachable("missed a case");
2401 case options::OPT_ccc_arcmt_check:
2402 CmdArgs.push_back("-arcmt-check");
2403 break;
2404 case options::OPT_ccc_arcmt_modify:
2405 CmdArgs.push_back("-arcmt-modify");
2406 break;
2407 case options::OPT_ccc_arcmt_migrate:
2408 CmdArgs.push_back("-arcmt-migrate");
2409 CmdArgs.push_back("-mt-migrate-directory");
2410 CmdArgs.push_back(A->getValue());
2411
2412 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2413 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2414 break;
2415 }
2416 }
2417 } else {
2418 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2419 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2420 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2421 }
2422
2423 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2424 if (ARCMTEnabled)
2425 D.Diag(diag::err_drv_argument_not_allowed_with)
2426 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2427
2428 CmdArgs.push_back("-mt-migrate-directory");
2429 CmdArgs.push_back(A->getValue());
2430
2431 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2432 options::OPT_objcmt_migrate_subscripting,
2433 options::OPT_objcmt_migrate_property)) {
2434 // None specified, means enable them all.
2435 CmdArgs.push_back("-objcmt-migrate-literals");
2436 CmdArgs.push_back("-objcmt-migrate-subscripting");
2437 CmdArgs.push_back("-objcmt-migrate-property");
2438 } else {
2439 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2440 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2441 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2442 }
2443 } else {
2444 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2445 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2446 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2447 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2448 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2449 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2450 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2451 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2452 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2453 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2454 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2455 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2456 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2457 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2458 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2459 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2460 }
2461}
2462
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002463static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2464 const ArgList &Args, ArgStringList &CmdArgs) {
2465 // -fbuiltin is default unless -mkernel is used.
2466 bool UseBuiltins =
2467 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2468 !Args.hasArg(options::OPT_mkernel));
2469 if (!UseBuiltins)
2470 CmdArgs.push_back("-fno-builtin");
2471
2472 // -ffreestanding implies -fno-builtin.
2473 if (Args.hasArg(options::OPT_ffreestanding))
2474 UseBuiltins = false;
2475
2476 // Process the -fno-builtin-* options.
2477 for (const auto &Arg : Args) {
2478 const Option &O = Arg->getOption();
2479 if (!O.matches(options::OPT_fno_builtin_))
2480 continue;
2481
2482 Arg->claim();
2483
2484 // If -fno-builtin is specified, then there's no need to pass the option to
2485 // the frontend.
2486 if (!UseBuiltins)
2487 continue;
2488
2489 StringRef FuncName = Arg->getValue();
2490 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2491 }
2492
2493 // le32-specific flags:
2494 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2495 // by default.
2496 if (TC.getArch() == llvm::Triple::le32)
2497 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002498}
2499
Adrian Prantl70599032018-02-09 18:43:10 +00002500void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2501 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2502 llvm::sys::path::append(Result, "org.llvm.clang.");
2503 appendUserToPath(Result);
2504 llvm::sys::path::append(Result, "ModuleCache");
2505}
2506
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002507static void RenderModulesOptions(Compilation &C, const Driver &D,
2508 const ArgList &Args, const InputInfo &Input,
2509 const InputInfo &Output,
2510 ArgStringList &CmdArgs, bool &HaveModules) {
2511 // -fmodules enables the use of precompiled modules (off by default).
2512 // Users can pass -fno-cxx-modules to turn off modules support for
2513 // C++/Objective-C++ programs.
2514 bool HaveClangModules = false;
2515 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2516 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2517 options::OPT_fno_cxx_modules, true);
2518 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2519 CmdArgs.push_back("-fmodules");
2520 HaveClangModules = true;
2521 }
2522 }
2523
2524 HaveModules = HaveClangModules;
2525 if (Args.hasArg(options::OPT_fmodules_ts)) {
2526 CmdArgs.push_back("-fmodules-ts");
2527 HaveModules = true;
2528 }
2529
2530 // -fmodule-maps enables implicit reading of module map files. By default,
2531 // this is enabled if we are using Clang's flavor of precompiled modules.
2532 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2533 options::OPT_fno_implicit_module_maps, HaveClangModules))
2534 CmdArgs.push_back("-fimplicit-module-maps");
2535
2536 // -fmodules-decluse checks that modules used are declared so (off by default)
2537 if (Args.hasFlag(options::OPT_fmodules_decluse,
2538 options::OPT_fno_modules_decluse, false))
2539 CmdArgs.push_back("-fmodules-decluse");
2540
2541 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2542 // all #included headers are part of modules.
2543 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2544 options::OPT_fno_modules_strict_decluse, false))
2545 CmdArgs.push_back("-fmodules-strict-decluse");
2546
2547 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002548 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002549 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2550 options::OPT_fno_implicit_modules, HaveClangModules)) {
2551 if (HaveModules)
2552 CmdArgs.push_back("-fno-implicit-modules");
2553 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002554 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002555 // -fmodule-cache-path specifies where our implicitly-built module files
2556 // should be written.
2557 SmallString<128> Path;
2558 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2559 Path = A->getValue();
2560
2561 if (C.isForDiagnostics()) {
2562 // When generating crash reports, we want to emit the modules along with
2563 // the reproduction sources, so we ignore any provided module path.
2564 Path = Output.getFilename();
2565 llvm::sys::path::replace_extension(Path, ".cache");
2566 llvm::sys::path::append(Path, "modules");
2567 } else if (Path.empty()) {
2568 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002569 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002570 }
2571
2572 const char Arg[] = "-fmodules-cache-path=";
2573 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2574 CmdArgs.push_back(Args.MakeArgString(Path));
2575 }
2576
2577 if (HaveModules) {
2578 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2579 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2580 CmdArgs.push_back(Args.MakeArgString(
2581 std::string("-fprebuilt-module-path=") + A->getValue()));
2582 A->claim();
2583 }
2584 }
2585
2586 // -fmodule-name specifies the module that is currently being built (or
2587 // used for header checking by -fmodule-maps).
2588 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2589
2590 // -fmodule-map-file can be used to specify files containing module
2591 // definitions.
2592 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2593
2594 // -fbuiltin-module-map can be used to load the clang
2595 // builtin headers modulemap file.
2596 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2597 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2598 llvm::sys::path::append(BuiltinModuleMap, "include");
2599 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2600 if (llvm::sys::fs::exists(BuiltinModuleMap))
2601 CmdArgs.push_back(
2602 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2603 }
2604
2605 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2606 // names to precompiled module files (the module is loaded only if used).
2607 // The -fmodule-file=<file> form can be used to unconditionally load
2608 // precompiled module files (whether used or not).
2609 if (HaveModules)
2610 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2611 else
2612 Args.ClaimAllArgs(options::OPT_fmodule_file);
2613
2614 // When building modules and generating crashdumps, we need to dump a module
2615 // dependency VFS alongside the output.
2616 if (HaveClangModules && C.isForDiagnostics()) {
2617 SmallString<128> VFSDir(Output.getFilename());
2618 llvm::sys::path::replace_extension(VFSDir, ".cache");
2619 // Add the cache directory as a temp so the crash diagnostics pick it up.
2620 C.addTempFile(Args.MakeArgString(VFSDir));
2621
2622 llvm::sys::path::append(VFSDir, "vfs");
2623 CmdArgs.push_back("-module-dependency-dir");
2624 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2625 }
2626
2627 if (HaveClangModules)
2628 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2629
2630 // Pass through all -fmodules-ignore-macro arguments.
2631 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2632 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2633 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2634
2635 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2636
2637 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2638 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2639 D.Diag(diag::err_drv_argument_not_allowed_with)
2640 << A->getAsString(Args) << "-fbuild-session-timestamp";
2641
2642 llvm::sys::fs::file_status Status;
2643 if (llvm::sys::fs::status(A->getValue(), Status))
2644 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2645 CmdArgs.push_back(
2646 Args.MakeArgString("-fbuild-session-timestamp=" +
2647 Twine((uint64_t)Status.getLastModificationTime()
2648 .time_since_epoch()
2649 .count())));
2650 }
2651
2652 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2653 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2654 options::OPT_fbuild_session_file))
2655 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2656
2657 Args.AddLastArg(CmdArgs,
2658 options::OPT_fmodules_validate_once_per_build_session);
2659 }
2660
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002661 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2662 options::OPT_fno_modules_validate_system_headers,
2663 ImplicitModules))
2664 CmdArgs.push_back("-fmodules-validate-system-headers");
2665
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002666 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2667}
2668
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002669static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2670 ArgStringList &CmdArgs) {
2671 // -fsigned-char is default.
2672 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2673 options::OPT_fno_signed_char,
2674 options::OPT_funsigned_char,
2675 options::OPT_fno_unsigned_char)) {
2676 if (A->getOption().matches(options::OPT_funsigned_char) ||
2677 A->getOption().matches(options::OPT_fno_signed_char)) {
2678 CmdArgs.push_back("-fno-signed-char");
2679 }
2680 } else if (!isSignedCharDefault(T)) {
2681 CmdArgs.push_back("-fno-signed-char");
2682 }
2683
Richard Smith3a8244d2018-05-01 05:02:45 +00002684 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2685 CmdArgs.push_back("-fchar8_t");
2686
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002687 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2688 options::OPT_fno_short_wchar)) {
2689 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2690 CmdArgs.push_back("-fwchar-type=short");
2691 CmdArgs.push_back("-fno-signed-wchar");
2692 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002693 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002694 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002695 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2696 T.getOS() == llvm::Triple::OpenBSD))
2697 CmdArgs.push_back("-fno-signed-wchar");
2698 else
2699 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002700 }
2701 }
2702}
2703
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002704static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2705 const llvm::Triple &T, const ArgList &Args,
2706 ObjCRuntime &Runtime, bool InferCovariantReturns,
2707 const InputInfo &Input, ArgStringList &CmdArgs) {
2708 const llvm::Triple::ArchType Arch = TC.getArch();
2709
2710 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2711 // is the default. Except for deployment target of 10.5, next runtime is
2712 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2713 if (Runtime.isNonFragile()) {
2714 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2715 options::OPT_fno_objc_legacy_dispatch,
2716 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2717 if (TC.UseObjCMixedDispatch())
2718 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2719 else
2720 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2721 }
2722 }
2723
2724 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2725 // to do Array/Dictionary subscripting by default.
2726 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2727 !T.isMacOSXVersionLT(10, 7) &&
2728 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2729 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2730
2731 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2732 // NOTE: This logic is duplicated in ToolChains.cpp.
2733 if (isObjCAutoRefCount(Args)) {
2734 TC.CheckObjCARC();
2735
2736 CmdArgs.push_back("-fobjc-arc");
2737
2738 // FIXME: It seems like this entire block, and several around it should be
2739 // wrapped in isObjC, but for now we just use it here as this is where it
2740 // was being used previously.
2741 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2742 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2743 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2744 else
2745 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2746 }
2747
2748 // Allow the user to enable full exceptions code emission.
2749 // We default off for Objective-C, on for Objective-C++.
2750 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2751 options::OPT_fno_objc_arc_exceptions,
2752 /*default=*/types::isCXX(Input.getType())))
2753 CmdArgs.push_back("-fobjc-arc-exceptions");
2754 }
2755
2756 // Silence warning for full exception code emission options when explicitly
2757 // set to use no ARC.
2758 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2759 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2760 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2761 }
2762
2763 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2764 // rewriter.
2765 if (InferCovariantReturns)
2766 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2767
2768 // Pass down -fobjc-weak or -fno-objc-weak if present.
2769 if (types::isObjC(Input.getType())) {
2770 auto WeakArg =
2771 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2772 if (!WeakArg) {
2773 // nothing to do
2774 } else if (!Runtime.allowsWeak()) {
2775 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2776 D.Diag(diag::err_objc_weak_unsupported);
2777 } else {
2778 WeakArg->render(Args, CmdArgs);
2779 }
2780 }
2781}
2782
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002783static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2784 ArgStringList &CmdArgs) {
2785 bool CaretDefault = true;
2786 bool ColumnDefault = true;
2787
2788 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2789 options::OPT__SLASH_diagnostics_column,
2790 options::OPT__SLASH_diagnostics_caret)) {
2791 switch (A->getOption().getID()) {
2792 case options::OPT__SLASH_diagnostics_caret:
2793 CaretDefault = true;
2794 ColumnDefault = true;
2795 break;
2796 case options::OPT__SLASH_diagnostics_column:
2797 CaretDefault = false;
2798 ColumnDefault = true;
2799 break;
2800 case options::OPT__SLASH_diagnostics_classic:
2801 CaretDefault = false;
2802 ColumnDefault = false;
2803 break;
2804 }
2805 }
2806
2807 // -fcaret-diagnostics is default.
2808 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2809 options::OPT_fno_caret_diagnostics, CaretDefault))
2810 CmdArgs.push_back("-fno-caret-diagnostics");
2811
2812 // -fdiagnostics-fixit-info is default, only pass non-default.
2813 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2814 options::OPT_fno_diagnostics_fixit_info))
2815 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2816
2817 // Enable -fdiagnostics-show-option by default.
2818 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2819 options::OPT_fno_diagnostics_show_option))
2820 CmdArgs.push_back("-fdiagnostics-show-option");
2821
2822 if (const Arg *A =
2823 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2824 CmdArgs.push_back("-fdiagnostics-show-category");
2825 CmdArgs.push_back(A->getValue());
2826 }
2827
2828 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2829 options::OPT_fno_diagnostics_show_hotness, false))
2830 CmdArgs.push_back("-fdiagnostics-show-hotness");
2831
2832 if (const Arg *A =
2833 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2834 std::string Opt =
2835 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2836 CmdArgs.push_back(Args.MakeArgString(Opt));
2837 }
2838
2839 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2840 CmdArgs.push_back("-fdiagnostics-format");
2841 CmdArgs.push_back(A->getValue());
2842 }
2843
2844 if (const Arg *A = Args.getLastArg(
2845 options::OPT_fdiagnostics_show_note_include_stack,
2846 options::OPT_fno_diagnostics_show_note_include_stack)) {
2847 const Option &O = A->getOption();
2848 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2849 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2850 else
2851 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2852 }
2853
2854 // Color diagnostics are parsed by the driver directly from argv and later
2855 // re-parsed to construct this job; claim any possible color diagnostic here
2856 // to avoid warn_drv_unused_argument and diagnose bad
2857 // OPT_fdiagnostics_color_EQ values.
2858 for (const Arg *A : Args) {
2859 const Option &O = A->getOption();
2860 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2861 !O.matches(options::OPT_fdiagnostics_color) &&
2862 !O.matches(options::OPT_fno_color_diagnostics) &&
2863 !O.matches(options::OPT_fno_diagnostics_color) &&
2864 !O.matches(options::OPT_fdiagnostics_color_EQ))
2865 continue;
2866
2867 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2868 StringRef Value(A->getValue());
2869 if (Value != "always" && Value != "never" && Value != "auto")
2870 D.Diag(diag::err_drv_clang_unsupported)
2871 << ("-fdiagnostics-color=" + Value).str();
2872 }
2873 A->claim();
2874 }
2875
2876 if (D.getDiags().getDiagnosticOptions().ShowColors)
2877 CmdArgs.push_back("-fcolor-diagnostics");
2878
2879 if (Args.hasArg(options::OPT_fansi_escape_codes))
2880 CmdArgs.push_back("-fansi-escape-codes");
2881
2882 if (!Args.hasFlag(options::OPT_fshow_source_location,
2883 options::OPT_fno_show_source_location))
2884 CmdArgs.push_back("-fno-show-source-location");
2885
2886 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2887 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2888
2889 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2890 ColumnDefault))
2891 CmdArgs.push_back("-fno-show-column");
2892
2893 if (!Args.hasFlag(options::OPT_fspell_checking,
2894 options::OPT_fno_spell_checking))
2895 CmdArgs.push_back("-fno-spell-checking");
2896}
2897
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002898static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2899 const llvm::Triple &T, const ArgList &Args,
2900 bool EmitCodeView, bool IsWindowsMSVC,
2901 ArgStringList &CmdArgs,
2902 codegenoptions::DebugInfoKind &DebugInfoKind,
2903 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002904 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2905 options::OPT_fno_debug_info_for_profiling, false))
2906 CmdArgs.push_back("-fdebug-info-for-profiling");
2907
2908 // The 'g' groups options involve a somewhat intricate sequence of decisions
2909 // about what to pass from the driver to the frontend, but by the time they
2910 // reach cc1 they've been factored into three well-defined orthogonal choices:
2911 // * what level of debug info to generate
2912 // * what dwarf version to write
2913 // * what debugger tuning to use
2914 // This avoids having to monkey around further in cc1 other than to disable
2915 // codeview if not running in a Windows environment. Perhaps even that
2916 // decision should be made in the driver as well though.
2917 unsigned DWARFVersion = 0;
2918 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2919
2920 bool SplitDWARFInlining =
2921 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2922 options::OPT_fno_split_dwarf_inlining, true);
2923
2924 Args.ClaimAllArgs(options::OPT_g_Group);
2925
2926 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2927
2928 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2929 // If the last option explicitly specified a debug-info level, use it.
2930 if (A->getOption().matches(options::OPT_gN_Group)) {
2931 DebugInfoKind = DebugLevelToInfoKind(*A);
2932 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2933 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2934 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2935 // This gets a bit more complicated if you've disabled inline info in the
2936 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2937 // split-dwarf and line-tables-only, so let those compose naturally in
2938 // that case.
2939 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2940 if (SplitDWARFArg) {
2941 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2942 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2943 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2944 SplitDWARFInlining))
2945 SplitDWARFArg = nullptr;
2946 } else if (SplitDWARFInlining)
2947 DebugInfoKind = codegenoptions::NoDebugInfo;
2948 }
2949 } else {
2950 // For any other 'g' option, use Limited.
2951 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2952 }
2953 }
2954
2955 // If a debugger tuning argument appeared, remember it.
2956 if (const Arg *A =
2957 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2958 if (A->getOption().matches(options::OPT_glldb))
2959 DebuggerTuning = llvm::DebuggerKind::LLDB;
2960 else if (A->getOption().matches(options::OPT_gsce))
2961 DebuggerTuning = llvm::DebuggerKind::SCE;
2962 else
2963 DebuggerTuning = llvm::DebuggerKind::GDB;
2964 }
2965
2966 // If a -gdwarf argument appeared, remember it.
2967 if (const Arg *A =
2968 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2969 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2970 DWARFVersion = DwarfVersionNum(A->getSpelling());
2971
2972 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2973 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002974 if (EmitCodeView) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002975 // DWARFVersion remains at 0 if no explicit choice was made.
2976 CmdArgs.push_back("-gcodeview");
2977 } else if (DWARFVersion == 0 &&
2978 DebugInfoKind != codegenoptions::NoDebugInfo) {
2979 DWARFVersion = TC.GetDefaultDwarfVersion();
2980 }
2981
2982 // We ignore flag -gstrict-dwarf for now.
2983 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2984 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2985
Paul Robinsona8280812017-09-29 21:25:07 +00002986 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002987 // Clang doesn't track end columns, just starting columns, which, in theory,
2988 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2989 // debuggers don't handle missing end columns well, so it's better not to
2990 // include any column info.
2991 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002992 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002993 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002994 CmdArgs.push_back("-dwarf-column-info");
2995
2996 // FIXME: Move backend command line options to the module.
2997 // If -gline-tables-only is the last option it wins.
2998 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2999 Args.hasArg(options::OPT_gmodules)) {
3000 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3001 CmdArgs.push_back("-dwarf-ext-refs");
3002 CmdArgs.push_back("-fmodule-format=obj");
3003 }
3004
3005 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3006 // splitting and extraction.
3007 // FIXME: Currently only works on Linux.
3008 if (T.isOSLinux()) {
3009 if (!SplitDWARFInlining)
3010 CmdArgs.push_back("-fno-split-dwarf-inlining");
3011
3012 if (SplitDWARFArg) {
3013 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3014 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3015 CmdArgs.push_back("-enable-split-dwarf");
3016 }
3017 }
3018
3019 // After we've dealt with all combinations of things that could
3020 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3021 // figure out if we need to "upgrade" it to standalone debug info.
3022 // We parse these two '-f' options whether or not they will be used,
3023 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3024 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3025 options::OPT_fno_standalone_debug,
3026 TC.GetDefaultStandaloneDebug());
3027 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3028 DebugInfoKind = codegenoptions::FullDebugInfo;
3029
Scott Lindera2fbcef2018-02-26 17:32:31 +00003030 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, false)) {
3031 // Source embedding is a vendor extension to DWARF v5. By now we have
3032 // checked if a DWARF version was stated explicitly, and have otherwise
3033 // fallen back to the target default, so if this is still not at least 5 we
3034 // emit an error.
3035 if (DWARFVersion < 5)
3036 D.Diag(diag::err_drv_argument_only_allowed_with)
3037 << Args.getLastArg(options::OPT_gembed_source)->getAsString(Args)
3038 << "-gdwarf-5";
3039 CmdArgs.push_back("-gembed-source");
3040 }
3041
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003042 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3043 DebuggerTuning);
3044
3045 // -fdebug-macro turns on macro debug info generation.
3046 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3047 false))
3048 CmdArgs.push_back("-debug-info-macro");
3049
3050 // -ggnu-pubnames turns on gnu style pubnames in the backend.
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003051 if (Args.hasArg(options::OPT_ggnu_pubnames))
3052 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003053
3054 // -gdwarf-aranges turns on the emission of the aranges section in the
3055 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003056 // Always enabled for SCE tuning.
3057 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3058 DebuggerTuning == llvm::DebuggerKind::SCE) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003059 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003060 CmdArgs.push_back("-generate-arange-section");
3061 }
3062
3063 if (Args.hasFlag(options::OPT_fdebug_types_section,
3064 options::OPT_fno_debug_types_section, false)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003065 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003066 CmdArgs.push_back("-generate-type-units");
3067 }
3068
Paul Robinson1787f812017-09-28 18:37:02 +00003069 // Decide how to render forward declarations of template instantiations.
3070 // SCE wants full descriptions, others just get them in the name.
3071 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3072 CmdArgs.push_back("-debug-forward-template-params");
3073
Paul Robinsona8280812017-09-29 21:25:07 +00003074 // Do we need to explicitly import anonymous namespaces into the parent scope?
3075 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3076 CmdArgs.push_back("-dwarf-explicit-import");
3077
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003078 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3079}
3080
David L. Jonesf561aba2017-03-08 01:02:16 +00003081void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3082 const InputInfo &Output, const InputInfoList &Inputs,
3083 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003084 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003085 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3086 const std::string &TripleStr = Triple.getTriple();
3087
3088 bool KernelOrKext =
3089 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3090 const Driver &D = getToolChain().getDriver();
3091 ArgStringList CmdArgs;
3092
3093 // Check number of inputs for sanity. We need at least one input.
3094 assert(Inputs.size() >= 1 && "Must have at least one input.");
3095 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003096 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003097 // device-side compilations). OpenMP device jobs also take the host IR as a
3098 // second input. All other jobs are expected to have exactly one
3099 // input.
3100 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003101 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003102 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003103 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003104 Inputs.size() == 1) &&
3105 "Unable to handle multiple inputs.");
3106
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003107 const llvm::Triple *AuxTriple =
3108 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3109
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003110 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3111 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3112 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003113 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003114
Yaxun Liu398612b2018-05-08 21:02:12 +00003115 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3116 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3117 // Windows), we need to pass Windows-specific flags to cc1.
3118 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003119 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3120 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3121 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3122 }
3123
3124 // C++ is not supported for IAMCU.
3125 if (IsIAMCU && types::isCXX(Input.getType()))
3126 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3127
3128 // Invoke ourselves in -cc1 mode.
3129 //
3130 // FIXME: Implement custom jobs for internal actions.
3131 CmdArgs.push_back("-cc1");
3132
3133 // Add the "effective" target triple.
3134 CmdArgs.push_back("-triple");
3135 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3136
3137 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3138 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3139 Args.ClaimAllArgs(options::OPT_MJ);
3140 }
3141
Yaxun Liu398612b2018-05-08 21:02:12 +00003142 if (IsCuda || IsHIP) {
3143 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3144 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003145 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003146 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3147 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003148 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3149 ->getTriple()
3150 .normalize();
3151 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003152 NormalizedTriple =
3153 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3154 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3155 ->getTriple()
3156 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003157
3158 CmdArgs.push_back("-aux-triple");
3159 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3160 }
3161
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003162 if (IsOpenMPDevice) {
3163 // We have to pass the triple of the host if compiling for an OpenMP device.
3164 std::string NormalizedTriple =
3165 C.getSingleOffloadToolChain<Action::OFK_Host>()
3166 ->getTriple()
3167 .normalize();
3168 CmdArgs.push_back("-aux-triple");
3169 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3170 }
3171
David L. Jonesf561aba2017-03-08 01:02:16 +00003172 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3173 Triple.getArch() == llvm::Triple::thumb)) {
3174 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3175 unsigned Version;
3176 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3177 if (Version < 7)
3178 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3179 << TripleStr;
3180 }
3181
3182 // Push all default warning arguments that are specific to
3183 // the given target. These come before user provided warning options
3184 // are provided.
3185 getToolChain().addClangWarningOptions(CmdArgs);
3186
3187 // Select the appropriate action.
3188 RewriteKind rewriteKind = RK_None;
3189
3190 if (isa<AnalyzeJobAction>(JA)) {
3191 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3192 CmdArgs.push_back("-analyze");
3193 } else if (isa<MigrateJobAction>(JA)) {
3194 CmdArgs.push_back("-migrate");
3195 } else if (isa<PreprocessJobAction>(JA)) {
3196 if (Output.getType() == types::TY_Dependencies)
3197 CmdArgs.push_back("-Eonly");
3198 else {
3199 CmdArgs.push_back("-E");
3200 if (Args.hasArg(options::OPT_rewrite_objc) &&
3201 !Args.hasArg(options::OPT_g_Group))
3202 CmdArgs.push_back("-P");
3203 }
3204 } else if (isa<AssembleJobAction>(JA)) {
3205 CmdArgs.push_back("-emit-obj");
3206
3207 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3208
3209 // Also ignore explicit -force_cpusubtype_ALL option.
3210 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3211 } else if (isa<PrecompileJobAction>(JA)) {
3212 // Use PCH if the user requested it.
3213 bool UsePCH = D.CCCUsePCH;
3214
3215 if (JA.getType() == types::TY_Nothing)
3216 CmdArgs.push_back("-fsyntax-only");
3217 else if (JA.getType() == types::TY_ModuleFile)
3218 CmdArgs.push_back("-emit-module-interface");
3219 else if (UsePCH)
3220 CmdArgs.push_back("-emit-pch");
3221 else
3222 CmdArgs.push_back("-emit-pth");
3223 } else if (isa<VerifyPCHJobAction>(JA)) {
3224 CmdArgs.push_back("-verify-pch");
3225 } else {
3226 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3227 "Invalid action for clang tool.");
3228 if (JA.getType() == types::TY_Nothing) {
3229 CmdArgs.push_back("-fsyntax-only");
3230 } else if (JA.getType() == types::TY_LLVM_IR ||
3231 JA.getType() == types::TY_LTO_IR) {
3232 CmdArgs.push_back("-emit-llvm");
3233 } else if (JA.getType() == types::TY_LLVM_BC ||
3234 JA.getType() == types::TY_LTO_BC) {
3235 CmdArgs.push_back("-emit-llvm-bc");
3236 } else if (JA.getType() == types::TY_PP_Asm) {
3237 CmdArgs.push_back("-S");
3238 } else if (JA.getType() == types::TY_AST) {
3239 CmdArgs.push_back("-emit-pch");
3240 } else if (JA.getType() == types::TY_ModuleFile) {
3241 CmdArgs.push_back("-module-file-info");
3242 } else if (JA.getType() == types::TY_RewrittenObjC) {
3243 CmdArgs.push_back("-rewrite-objc");
3244 rewriteKind = RK_NonFragile;
3245 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3246 CmdArgs.push_back("-rewrite-objc");
3247 rewriteKind = RK_Fragile;
3248 } else {
3249 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3250 }
3251
3252 // Preserve use-list order by default when emitting bitcode, so that
3253 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3254 // same result as running passes here. For LTO, we don't need to preserve
3255 // the use-list order, since serialization to bitcode is part of the flow.
3256 if (JA.getType() == types::TY_LLVM_BC)
3257 CmdArgs.push_back("-emit-llvm-uselists");
3258
Artem Belevichecb178b2018-03-21 22:22:59 +00003259 // Device-side jobs do not support LTO.
3260 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3261 JA.isDeviceOffloading(Action::OFK_Host));
3262
3263 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003264 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3265
Paul Robinsond23f2a82017-07-13 21:25:47 +00003266 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3267 // does not support LTO unit features (CFI, whole program vtable opt)
3268 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003269 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003270 D.getLTOMode() == LTOK_Full)
3271 CmdArgs.push_back("-flto-unit");
3272 }
3273 }
3274
3275 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3276 if (!types::isLLVMIR(Input.getType()))
3277 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3278 << "-x ir";
3279 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3280 }
3281
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003282 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003283 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3284
David L. Jonesf561aba2017-03-08 01:02:16 +00003285 // Embed-bitcode option.
3286 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3287 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3288 // Add flags implied by -fembed-bitcode.
3289 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3290 // Disable all llvm IR level optimizations.
3291 CmdArgs.push_back("-disable-llvm-passes");
3292 }
3293 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3294 CmdArgs.push_back("-fembed-bitcode=marker");
3295
3296 // We normally speed up the clang process a bit by skipping destructors at
3297 // exit, but when we're generating diagnostics we can rely on some of the
3298 // cleanup.
3299 if (!C.isForDiagnostics())
3300 CmdArgs.push_back("-disable-free");
3301
David L. Jonesf561aba2017-03-08 01:02:16 +00003302#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003303 const bool IsAssertBuild = false;
3304#else
3305 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003306#endif
3307
Eric Fiselier123c7492018-02-07 18:36:51 +00003308 // Disable the verification pass in -asserts builds.
3309 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003310 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003311
3312 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003313 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3314 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003315 CmdArgs.push_back("-discard-value-names");
3316
David L. Jonesf561aba2017-03-08 01:02:16 +00003317 // Set the main file name, so that debug info works even with
3318 // -save-temps.
3319 CmdArgs.push_back("-main-file-name");
3320 CmdArgs.push_back(getBaseInputName(Args, Input));
3321
3322 // Some flags which affect the language (via preprocessor
3323 // defines).
3324 if (Args.hasArg(options::OPT_static))
3325 CmdArgs.push_back("-static-define");
3326
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003327 if (isa<AnalyzeJobAction>(JA))
3328 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003329
3330 CheckCodeGenerationOptions(D, Args);
3331
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003332 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3333 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3334 if (FunctionAlignment) {
3335 CmdArgs.push_back("-function-alignment");
3336 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3337 }
3338
David L. Jonesf561aba2017-03-08 01:02:16 +00003339 llvm::Reloc::Model RelocationModel;
3340 unsigned PICLevel;
3341 bool IsPIE;
3342 std::tie(RelocationModel, PICLevel, IsPIE) =
3343 ParsePICArgs(getToolChain(), Args);
3344
3345 const char *RMName = RelocationModelName(RelocationModel);
3346
3347 if ((RelocationModel == llvm::Reloc::ROPI ||
3348 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3349 types::isCXX(Input.getType()) &&
3350 !Args.hasArg(options::OPT_fallow_unsupported))
3351 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3352
3353 if (RMName) {
3354 CmdArgs.push_back("-mrelocation-model");
3355 CmdArgs.push_back(RMName);
3356 }
3357 if (PICLevel > 0) {
3358 CmdArgs.push_back("-pic-level");
3359 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3360 if (IsPIE)
3361 CmdArgs.push_back("-pic-is-pie");
3362 }
3363
3364 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3365 CmdArgs.push_back("-meabi");
3366 CmdArgs.push_back(A->getValue());
3367 }
3368
3369 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003370 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3371 if (!getToolChain().isThreadModelSupported(A->getValue()))
3372 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3373 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003374 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003375 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003376 else
3377 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3378
3379 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3380
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003381 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3382 options::OPT_fno_merge_all_constants, false))
3383 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003384
3385 // LLVM Code Generator Options.
3386
3387 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3388 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3389 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3390 options::OPT_frewrite_map_file_EQ)) {
3391 StringRef Map = A->getValue();
3392 if (!llvm::sys::fs::exists(Map)) {
3393 D.Diag(diag::err_drv_no_such_file) << Map;
3394 } else {
3395 CmdArgs.push_back("-frewrite-map-file");
3396 CmdArgs.push_back(A->getValue());
3397 A->claim();
3398 }
3399 }
3400 }
3401
3402 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3403 StringRef v = A->getValue();
3404 CmdArgs.push_back("-mllvm");
3405 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3406 A->claim();
3407 }
3408
3409 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3410 true))
3411 CmdArgs.push_back("-fno-jump-tables");
3412
Dehao Chen5e97f232017-08-24 21:37:33 +00003413 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3414 options::OPT_fno_profile_sample_accurate, false))
3415 CmdArgs.push_back("-fprofile-sample-accurate");
3416
David L. Jonesf561aba2017-03-08 01:02:16 +00003417 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3418 options::OPT_fno_preserve_as_comments, true))
3419 CmdArgs.push_back("-fno-preserve-as-comments");
3420
3421 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3422 CmdArgs.push_back("-mregparm");
3423 CmdArgs.push_back(A->getValue());
3424 }
3425
3426 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3427 options::OPT_freg_struct_return)) {
3428 if (getToolChain().getArch() != llvm::Triple::x86) {
3429 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003430 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3432 CmdArgs.push_back("-fpcc-struct-return");
3433 } else {
3434 assert(A->getOption().matches(options::OPT_freg_struct_return));
3435 CmdArgs.push_back("-freg-struct-return");
3436 }
3437 }
3438
3439 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3440 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3441
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003442 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003443 CmdArgs.push_back("-mdisable-fp-elim");
3444 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3445 options::OPT_fno_zero_initialized_in_bss))
3446 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3447
3448 bool OFastEnabled = isOptimizationLevelFast(Args);
3449 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3450 // enabled. This alias option is being used to simplify the hasFlag logic.
3451 OptSpecifier StrictAliasingAliasOption =
3452 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3453 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3454 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003455 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003456 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3457 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3458 CmdArgs.push_back("-relaxed-aliasing");
3459 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3460 options::OPT_fno_struct_path_tbaa))
3461 CmdArgs.push_back("-no-struct-path-tbaa");
3462 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3463 false))
3464 CmdArgs.push_back("-fstrict-enums");
3465 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3466 true))
3467 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003468 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3469 options::OPT_fno_allow_editor_placeholders, false))
3470 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003471 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3472 options::OPT_fno_strict_vtable_pointers,
3473 false))
3474 CmdArgs.push_back("-fstrict-vtable-pointers");
3475 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3476 options::OPT_fno_optimize_sibling_calls))
3477 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003478 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003479 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003480 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003481
Wei Mi9b3d6272017-10-16 16:50:27 +00003482 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3483 options::OPT_fno_fine_grained_bitfield_accesses);
3484
David L. Jonesf561aba2017-03-08 01:02:16 +00003485 // Handle segmented stacks.
3486 if (Args.hasArg(options::OPT_fsplit_stack))
3487 CmdArgs.push_back("-split-stacks");
3488
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003489 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003490
3491 // Decide whether to use verbose asm. Verbose assembly is the default on
3492 // toolchains which have the integrated assembler on by default.
3493 bool IsIntegratedAssemblerDefault =
3494 getToolChain().IsIntegratedAssemblerDefault();
3495 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3496 IsIntegratedAssemblerDefault) ||
3497 Args.hasArg(options::OPT_dA))
3498 CmdArgs.push_back("-masm-verbose");
3499
3500 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3501 IsIntegratedAssemblerDefault))
3502 CmdArgs.push_back("-no-integrated-as");
3503
3504 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3505 CmdArgs.push_back("-mdebug-pass");
3506 CmdArgs.push_back("Structure");
3507 }
3508 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3509 CmdArgs.push_back("-mdebug-pass");
3510 CmdArgs.push_back("Arguments");
3511 }
3512
3513 // Enable -mconstructor-aliases except on darwin, where we have to work around
3514 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3515 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003516 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003517 CmdArgs.push_back("-mconstructor-aliases");
3518
3519 // Darwin's kernel doesn't support guard variables; just die if we
3520 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003521 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003522 CmdArgs.push_back("-fforbid-guard-variables");
3523
3524 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3525 false)) {
3526 CmdArgs.push_back("-mms-bitfields");
3527 }
3528
3529 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3530 options::OPT_mno_pie_copy_relocations,
3531 false)) {
3532 CmdArgs.push_back("-mpie-copy-relocations");
3533 }
3534
Sriraman Tallam5c651482017-11-07 19:37:51 +00003535 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3536 CmdArgs.push_back("-fno-plt");
3537 }
3538
Vedant Kumardf502592017-09-12 22:51:53 +00003539 // -fhosted is default.
3540 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3541 // use Freestanding.
3542 bool Freestanding =
3543 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3544 KernelOrKext;
3545 if (Freestanding)
3546 CmdArgs.push_back("-ffreestanding");
3547
David L. Jonesf561aba2017-03-08 01:02:16 +00003548 // This is a coarse approximation of what llvm-gcc actually does, both
3549 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3550 // complicated ways.
3551 bool AsynchronousUnwindTables =
3552 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3553 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003554 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003555 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003556 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003557 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3558 AsynchronousUnwindTables))
3559 CmdArgs.push_back("-munwind-tables");
3560
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003561 getToolChain().addClangTargetOptions(Args, CmdArgs,
3562 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003563
3564 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3565 CmdArgs.push_back("-mlimit-float-precision");
3566 CmdArgs.push_back(A->getValue());
3567 }
3568
3569 // FIXME: Handle -mtune=.
3570 (void)Args.hasArg(options::OPT_mtune_EQ);
3571
3572 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3573 CmdArgs.push_back("-mcode-model");
3574 CmdArgs.push_back(A->getValue());
3575 }
3576
3577 // Add the target cpu
3578 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3579 if (!CPU.empty()) {
3580 CmdArgs.push_back("-target-cpu");
3581 CmdArgs.push_back(Args.MakeArgString(CPU));
3582 }
3583
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003584 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003585
David L. Jonesf561aba2017-03-08 01:02:16 +00003586 // These two are potentially updated by AddClangCLArgs.
3587 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3588 bool EmitCodeView = false;
3589
3590 // Add clang-cl arguments.
3591 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003592 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003593 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003594 else
3595 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003596
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003597 const Arg *SplitDWARFArg = nullptr;
3598 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3599 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3600
3601 // Add the split debug info name to the command lines here so we
3602 // can propagate it to the backend.
3603 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3604 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3605 isa<BackendJobAction>(JA));
3606 const char *SplitDWARFOut;
3607 if (SplitDWARF) {
3608 CmdArgs.push_back("-split-dwarf-file");
3609 SplitDWARFOut = SplitDebugName(Args, Input);
3610 CmdArgs.push_back(SplitDWARFOut);
3611 }
3612
David L. Jonesf561aba2017-03-08 01:02:16 +00003613 // Pass the linker version in use.
3614 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3615 CmdArgs.push_back("-target-linker-version");
3616 CmdArgs.push_back(A->getValue());
3617 }
3618
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003619 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003620 CmdArgs.push_back("-momit-leaf-frame-pointer");
3621
3622 // Explicitly error on some things we know we don't support and can't just
3623 // ignore.
3624 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3625 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003626 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003627 getToolChain().getArch() == llvm::Triple::x86) {
3628 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3629 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3630 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3631 << Unsupported->getOption().getName();
3632 }
Eric Christopher758aad72017-03-21 22:06:18 +00003633 // The faltivec option has been superseded by the maltivec option.
3634 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3635 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3636 << Unsupported->getOption().getName()
3637 << "please use -maltivec and include altivec.h explicitly";
3638 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3639 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3640 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003641 }
3642
3643 Args.AddAllArgs(CmdArgs, options::OPT_v);
3644 Args.AddLastArg(CmdArgs, options::OPT_H);
3645 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3646 CmdArgs.push_back("-header-include-file");
3647 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3648 : "-");
3649 }
3650 Args.AddLastArg(CmdArgs, options::OPT_P);
3651 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3652
3653 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3654 CmdArgs.push_back("-diagnostic-log-file");
3655 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3656 : "-");
3657 }
3658
David L. Jonesf561aba2017-03-08 01:02:16 +00003659 bool UseSeparateSections = isUseSeparateSections(Triple);
3660
3661 if (Args.hasFlag(options::OPT_ffunction_sections,
3662 options::OPT_fno_function_sections, UseSeparateSections)) {
3663 CmdArgs.push_back("-ffunction-sections");
3664 }
3665
3666 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3667 UseSeparateSections)) {
3668 CmdArgs.push_back("-fdata-sections");
3669 }
3670
3671 if (!Args.hasFlag(options::OPT_funique_section_names,
3672 options::OPT_fno_unique_section_names, true))
3673 CmdArgs.push_back("-fno-unique-section-names");
3674
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003675 if (auto *A = Args.getLastArg(
3676 options::OPT_finstrument_functions,
3677 options::OPT_finstrument_functions_after_inlining,
3678 options::OPT_finstrument_function_entry_bare))
3679 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003680
Artem Belevichc30bcad2018-01-24 17:41:02 +00003681 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3682 // sampling, overhead of call arc collection is way too high and there's no
3683 // way to collect the output.
3684 if (!Triple.isNVPTX())
3685 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003686
Richard Smithf667ad52017-08-26 01:04:35 +00003687 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3688 ABICompatArg->render(Args, CmdArgs);
3689
David L. Jonesf561aba2017-03-08 01:02:16 +00003690 // Add runtime flag for PS4 when PGO or Coverage are enabled.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003691 if (RawTriple.isPS4CPU())
David L. Jonesf561aba2017-03-08 01:02:16 +00003692 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
3693
3694 // Pass options for controlling the default header search paths.
3695 if (Args.hasArg(options::OPT_nostdinc)) {
3696 CmdArgs.push_back("-nostdsysteminc");
3697 CmdArgs.push_back("-nobuiltininc");
3698 } else {
3699 if (Args.hasArg(options::OPT_nostdlibinc))
3700 CmdArgs.push_back("-nostdsysteminc");
3701 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3702 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3703 }
3704
3705 // Pass the path to compiler resource files.
3706 CmdArgs.push_back("-resource-dir");
3707 CmdArgs.push_back(D.ResourceDir.c_str());
3708
3709 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3710
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003711 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003712
3713 // Add preprocessing options like -I, -D, etc. if we are using the
3714 // preprocessor.
3715 //
3716 // FIXME: Support -fpreprocessed
3717 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3718 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3719
3720 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3721 // that "The compiler can only warn and ignore the option if not recognized".
3722 // When building with ccache, it will pass -D options to clang even on
3723 // preprocessed inputs and configure concludes that -fPIC is not supported.
3724 Args.ClaimAllArgs(options::OPT_D);
3725
3726 // Manually translate -O4 to -O3; let clang reject others.
3727 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3728 if (A->getOption().matches(options::OPT_O4)) {
3729 CmdArgs.push_back("-O3");
3730 D.Diag(diag::warn_O4_is_O3);
3731 } else {
3732 A->render(Args, CmdArgs);
3733 }
3734 }
3735
3736 // Warn about ignored options to clang.
3737 for (const Arg *A :
3738 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3739 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3740 A->claim();
3741 }
3742
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003743 for (const Arg *A :
3744 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3745 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3746 A->claim();
3747 }
3748
David L. Jonesf561aba2017-03-08 01:02:16 +00003749 claimNoWarnArgs(Args);
3750
3751 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3752
3753 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3754 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3755 CmdArgs.push_back("-pedantic");
3756 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3757 Args.AddLastArg(CmdArgs, options::OPT_w);
3758
3759 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3760 // (-ansi is equivalent to -std=c89 or -std=c++98).
3761 //
3762 // If a std is supplied, only add -trigraphs if it follows the
3763 // option.
3764 bool ImplyVCPPCXXVer = false;
3765 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3766 if (Std->getOption().matches(options::OPT_ansi))
3767 if (types::isCXX(InputType))
3768 CmdArgs.push_back("-std=c++98");
3769 else
3770 CmdArgs.push_back("-std=c89");
3771 else
3772 Std->render(Args, CmdArgs);
3773
3774 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3775 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3776 options::OPT_ftrigraphs,
3777 options::OPT_fno_trigraphs))
3778 if (A != Std)
3779 A->render(Args, CmdArgs);
3780 } else {
3781 // Honor -std-default.
3782 //
3783 // FIXME: Clang doesn't correctly handle -std= when the input language
3784 // doesn't match. For the time being just ignore this for C++ inputs;
3785 // eventually we want to do all the standard defaulting here instead of
3786 // splitting it between the driver and clang -cc1.
3787 if (!types::isCXX(InputType))
3788 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3789 /*Joined=*/true);
3790 else if (IsWindowsMSVC)
3791 ImplyVCPPCXXVer = true;
3792
3793 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3794 options::OPT_fno_trigraphs);
3795 }
3796
3797 // GCC's behavior for -Wwrite-strings is a bit strange:
3798 // * In C, this "warning flag" changes the types of string literals from
3799 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3800 // for the discarded qualifier.
3801 // * In C++, this is just a normal warning flag.
3802 //
3803 // Implementing this warning correctly in C is hard, so we follow GCC's
3804 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3805 // a non-const char* in C, rather than using this crude hack.
3806 if (!types::isCXX(InputType)) {
3807 // FIXME: This should behave just like a warning flag, and thus should also
3808 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3809 Arg *WriteStrings =
3810 Args.getLastArg(options::OPT_Wwrite_strings,
3811 options::OPT_Wno_write_strings, options::OPT_w);
3812 if (WriteStrings &&
3813 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3814 CmdArgs.push_back("-fconst-strings");
3815 }
3816
3817 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3818 // during C++ compilation, which it is by default. GCC keeps this define even
3819 // in the presence of '-w', match this behavior bug-for-bug.
3820 if (types::isCXX(InputType) &&
3821 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3822 true)) {
3823 CmdArgs.push_back("-fdeprecated-macro");
3824 }
3825
3826 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3827 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3828 if (Asm->getOption().matches(options::OPT_fasm))
3829 CmdArgs.push_back("-fgnu-keywords");
3830 else
3831 CmdArgs.push_back("-fno-gnu-keywords");
3832 }
3833
3834 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3835 CmdArgs.push_back("-fno-dwarf-directory-asm");
3836
3837 if (ShouldDisableAutolink(Args, getToolChain()))
3838 CmdArgs.push_back("-fno-autolink");
3839
3840 // Add in -fdebug-compilation-dir if necessary.
3841 addDebugCompDirArg(Args, CmdArgs);
3842
3843 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3844 StringRef Map = A->getValue();
3845 if (Map.find('=') == StringRef::npos)
3846 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3847 else
3848 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3849 A->claim();
3850 }
3851
3852 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3853 options::OPT_ftemplate_depth_EQ)) {
3854 CmdArgs.push_back("-ftemplate-depth");
3855 CmdArgs.push_back(A->getValue());
3856 }
3857
3858 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3859 CmdArgs.push_back("-foperator-arrow-depth");
3860 CmdArgs.push_back(A->getValue());
3861 }
3862
3863 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3864 CmdArgs.push_back("-fconstexpr-depth");
3865 CmdArgs.push_back(A->getValue());
3866 }
3867
3868 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3869 CmdArgs.push_back("-fconstexpr-steps");
3870 CmdArgs.push_back(A->getValue());
3871 }
3872
3873 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3874 CmdArgs.push_back("-fbracket-depth");
3875 CmdArgs.push_back(A->getValue());
3876 }
3877
3878 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3879 options::OPT_Wlarge_by_value_copy_def)) {
3880 if (A->getNumValues()) {
3881 StringRef bytes = A->getValue();
3882 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3883 } else
3884 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3885 }
3886
3887 if (Args.hasArg(options::OPT_relocatable_pch))
3888 CmdArgs.push_back("-relocatable-pch");
3889
3890 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3891 CmdArgs.push_back("-fconstant-string-class");
3892 CmdArgs.push_back(A->getValue());
3893 }
3894
3895 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3896 CmdArgs.push_back("-ftabstop");
3897 CmdArgs.push_back(A->getValue());
3898 }
3899
Sean Eveson5110d4f2018-01-08 13:42:26 +00003900 if (Args.hasFlag(options::OPT_fstack_size_section,
3901 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3902 CmdArgs.push_back("-fstack-size-section");
3903
David L. Jonesf561aba2017-03-08 01:02:16 +00003904 CmdArgs.push_back("-ferror-limit");
3905 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3906 CmdArgs.push_back(A->getValue());
3907 else
3908 CmdArgs.push_back("19");
3909
3910 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3911 CmdArgs.push_back("-fmacro-backtrace-limit");
3912 CmdArgs.push_back(A->getValue());
3913 }
3914
3915 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3916 CmdArgs.push_back("-ftemplate-backtrace-limit");
3917 CmdArgs.push_back(A->getValue());
3918 }
3919
3920 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3921 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3922 CmdArgs.push_back(A->getValue());
3923 }
3924
3925 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3926 CmdArgs.push_back("-fspell-checking-limit");
3927 CmdArgs.push_back(A->getValue());
3928 }
3929
3930 // Pass -fmessage-length=.
3931 CmdArgs.push_back("-fmessage-length");
3932 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3933 CmdArgs.push_back(A->getValue());
3934 } else {
3935 // If -fmessage-length=N was not specified, determine whether this is a
3936 // terminal and, if so, implicitly define -fmessage-length appropriately.
3937 unsigned N = llvm::sys::Process::StandardErrColumns();
3938 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3939 }
3940
3941 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3942 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3943 options::OPT_fvisibility_ms_compat)) {
3944 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3945 CmdArgs.push_back("-fvisibility");
3946 CmdArgs.push_back(A->getValue());
3947 } else {
3948 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3949 CmdArgs.push_back("-fvisibility");
3950 CmdArgs.push_back("hidden");
3951 CmdArgs.push_back("-ftype-visibility");
3952 CmdArgs.push_back("default");
3953 }
3954 }
3955
3956 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3957
3958 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3959
David L. Jonesf561aba2017-03-08 01:02:16 +00003960 // Forward -f (flag) options which we can pass directly.
3961 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3962 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3963 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00003964 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
3965 options::OPT_fno_emulated_tls);
3966
David L. Jonesf561aba2017-03-08 01:02:16 +00003967 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003968 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003969 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003970
David L. Jonesf561aba2017-03-08 01:02:16 +00003971 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3972 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3973
3974 // Forward flags for OpenMP. We don't do this if the current action is an
3975 // device offloading action other than OpenMP.
3976 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3977 options::OPT_fno_openmp, false) &&
3978 (JA.isDeviceOffloading(Action::OFK_None) ||
3979 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003980 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003981 case Driver::OMPRT_OMP:
3982 case Driver::OMPRT_IOMP5:
3983 // Clang can generate useful OpenMP code for these two runtime libraries.
3984 CmdArgs.push_back("-fopenmp");
3985
3986 // If no option regarding the use of TLS in OpenMP codegeneration is
3987 // given, decide a default based on the target. Otherwise rely on the
3988 // options and pass the right information to the frontend.
3989 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3990 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3991 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00003992 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3993 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00003994 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00003995
3996 // When in OpenMP offloading mode with NVPTX target, forward
3997 // cuda-mode flag
3998 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
3999 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00004000 break;
4001 default:
4002 // By default, if Clang doesn't know how to generate useful OpenMP code
4003 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4004 // down to the actual compilation.
4005 // FIXME: It would be better to have a mode which *only* omits IR
4006 // generation based on the OpenMP support so that we get consistent
4007 // semantic analysis, etc.
4008 break;
4009 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004010 } else {
4011 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4012 options::OPT_fno_openmp_simd);
4013 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004014 }
4015
4016 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4017 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4018
Dean Michael Berris835832d2017-03-30 00:29:36 +00004019 const XRayArgs &XRay = getToolChain().getXRayArgs();
4020 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4021
David L. Jonesf561aba2017-03-08 01:02:16 +00004022 if (getToolChain().SupportsProfiling())
4023 Args.AddLastArg(CmdArgs, options::OPT_pg);
4024
4025 if (getToolChain().SupportsProfiling())
4026 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4027
4028 // -flax-vector-conversions is default.
4029 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4030 options::OPT_fno_lax_vector_conversions))
4031 CmdArgs.push_back("-fno-lax-vector-conversions");
4032
4033 if (Args.getLastArg(options::OPT_fapple_kext) ||
4034 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4035 CmdArgs.push_back("-fapple-kext");
4036
4037 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4038 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4039 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4040 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4041 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4042
4043 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4044 CmdArgs.push_back("-ftrapv-handler");
4045 CmdArgs.push_back(A->getValue());
4046 }
4047
4048 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4049
4050 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4051 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4052 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4053 if (A->getOption().matches(options::OPT_fwrapv))
4054 CmdArgs.push_back("-fwrapv");
4055 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4056 options::OPT_fno_strict_overflow)) {
4057 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4058 CmdArgs.push_back("-fwrapv");
4059 }
4060
4061 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4062 options::OPT_fno_reroll_loops))
4063 if (A->getOption().matches(options::OPT_freroll_loops))
4064 CmdArgs.push_back("-freroll-loops");
4065
4066 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4067 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4068 options::OPT_fno_unroll_loops);
4069
4070 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4071
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004072 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004073
4074 // Translate -mstackrealign
4075 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4076 false))
4077 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4078
4079 if (Args.hasArg(options::OPT_mstack_alignment)) {
4080 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4081 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4082 }
4083
4084 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4085 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4086
4087 if (!Size.empty())
4088 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4089 else
4090 CmdArgs.push_back("-mstack-probe-size=0");
4091 }
4092
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004093 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4094 options::OPT_mno_stack_arg_probe, true))
4095 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4096
David L. Jonesf561aba2017-03-08 01:02:16 +00004097 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4098 options::OPT_mno_restrict_it)) {
4099 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004100 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004101 CmdArgs.push_back("-arm-restrict-it");
4102 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004103 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004104 CmdArgs.push_back("-arm-no-restrict-it");
4105 }
4106 } else if (Triple.isOSWindows() &&
4107 (Triple.getArch() == llvm::Triple::arm ||
4108 Triple.getArch() == llvm::Triple::thumb)) {
4109 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004110 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004111 CmdArgs.push_back("-arm-restrict-it");
4112 }
4113
4114 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004115 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004116
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004117 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4118 CmdArgs.push_back(
4119 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4120 }
4121
David L. Jonesf561aba2017-03-08 01:02:16 +00004122 // Forward -f options with positive and negative forms; we translate
4123 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004124 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004125 StringRef fname = A->getValue();
4126 if (!llvm::sys::fs::exists(fname))
4127 D.Diag(diag::err_drv_no_such_file) << fname;
4128 else
4129 A->render(Args, CmdArgs);
4130 }
4131
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004132 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004133
4134 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4135 options::OPT_fno_assume_sane_operator_new))
4136 CmdArgs.push_back("-fno-assume-sane-operator-new");
4137
4138 // -fblocks=0 is default.
4139 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4140 getToolChain().IsBlocksDefault()) ||
4141 (Args.hasArg(options::OPT_fgnu_runtime) &&
4142 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4143 !Args.hasArg(options::OPT_fno_blocks))) {
4144 CmdArgs.push_back("-fblocks");
4145
4146 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4147 !getToolChain().hasBlocksRuntime())
4148 CmdArgs.push_back("-fblocks-runtime-optional");
4149 }
4150
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004151 // -fencode-extended-block-signature=1 is default.
4152 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4153 CmdArgs.push_back("-fencode-extended-block-signature");
4154
David L. Jonesf561aba2017-03-08 01:02:16 +00004155 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4156 false) &&
4157 types::isCXX(InputType)) {
4158 CmdArgs.push_back("-fcoroutines-ts");
4159 }
4160
Aaron Ballman61736552017-10-21 20:28:58 +00004161 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4162 options::OPT_fno_double_square_bracket_attributes);
4163
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004164 bool HaveModules = false;
4165 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004166
4167 // -faccess-control is default.
4168 if (Args.hasFlag(options::OPT_fno_access_control,
4169 options::OPT_faccess_control, false))
4170 CmdArgs.push_back("-fno-access-control");
4171
4172 // -felide-constructors is the default.
4173 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4174 options::OPT_felide_constructors, false))
4175 CmdArgs.push_back("-fno-elide-constructors");
4176
4177 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4178
4179 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004180 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004181 CmdArgs.push_back("-fno-rtti");
4182
4183 // -fshort-enums=0 is default for all architectures except Hexagon.
4184 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4185 getToolChain().getArch() == llvm::Triple::hexagon))
4186 CmdArgs.push_back("-fshort-enums");
4187
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004188 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004189
4190 // -fuse-cxa-atexit is default.
4191 if (!Args.hasFlag(
4192 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004193 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004194 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004195 getToolChain().getArch() != llvm::Triple::hexagon &&
4196 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004197 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4198 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004199 KernelOrKext)
4200 CmdArgs.push_back("-fno-use-cxa-atexit");
4201
Akira Hatanaka617e2612018-04-17 18:41:52 +00004202 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4203 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004204 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004205 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4206
David L. Jonesf561aba2017-03-08 01:02:16 +00004207 // -fms-extensions=0 is default.
4208 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4209 IsWindowsMSVC))
4210 CmdArgs.push_back("-fms-extensions");
4211
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004212 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004213 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004214 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004215 CmdArgs.push_back("-fuse-line-directives");
4216
4217 // -fms-compatibility=0 is default.
4218 if (Args.hasFlag(options::OPT_fms_compatibility,
4219 options::OPT_fno_ms_compatibility,
4220 (IsWindowsMSVC &&
4221 Args.hasFlag(options::OPT_fms_extensions,
4222 options::OPT_fno_ms_extensions, true))))
4223 CmdArgs.push_back("-fms-compatibility");
4224
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004225 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004226 if (!MSVT.empty())
4227 CmdArgs.push_back(
4228 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4229
4230 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4231 if (ImplyVCPPCXXVer) {
4232 StringRef LanguageStandard;
4233 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4234 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4235 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004236 .Case("c++17", "-std=c++17")
4237 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004238 .Default("");
4239 if (LanguageStandard.empty())
4240 D.Diag(clang::diag::warn_drv_unused_argument)
4241 << StdArg->getAsString(Args);
4242 }
4243
4244 if (LanguageStandard.empty()) {
4245 if (IsMSVC2015Compatible)
4246 LanguageStandard = "-std=c++14";
4247 else
4248 LanguageStandard = "-std=c++11";
4249 }
4250
4251 CmdArgs.push_back(LanguageStandard.data());
4252 }
4253
4254 // -fno-borland-extensions is default.
4255 if (Args.hasFlag(options::OPT_fborland_extensions,
4256 options::OPT_fno_borland_extensions, false))
4257 CmdArgs.push_back("-fborland-extensions");
4258
4259 // -fno-declspec is default, except for PS4.
4260 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004261 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004262 CmdArgs.push_back("-fdeclspec");
4263 else if (Args.hasArg(options::OPT_fno_declspec))
4264 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4265
4266 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4267 // than 19.
4268 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4269 options::OPT_fno_threadsafe_statics,
4270 !IsWindowsMSVC || IsMSVC2015Compatible))
4271 CmdArgs.push_back("-fno-threadsafe-statics");
4272
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004273 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004274 // Many old Windows SDK versions require this to parse.
4275 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4276 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004277 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4278 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4279 CmdArgs.push_back("-fdelayed-template-parsing");
4280
4281 // -fgnu-keywords default varies depending on language; only pass if
4282 // specified.
4283 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4284 options::OPT_fno_gnu_keywords))
4285 A->render(Args, CmdArgs);
4286
4287 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4288 false))
4289 CmdArgs.push_back("-fgnu89-inline");
4290
4291 if (Args.hasArg(options::OPT_fno_inline))
4292 CmdArgs.push_back("-fno-inline");
4293
4294 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4295 options::OPT_finline_hint_functions,
4296 options::OPT_fno_inline_functions))
4297 InlineArg->render(Args, CmdArgs);
4298
4299 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4300 options::OPT_fno_experimental_new_pass_manager);
4301
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004302 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4303 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4304 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004305
4306 if (Args.hasFlag(options::OPT_fapplication_extension,
4307 options::OPT_fno_application_extension, false))
4308 CmdArgs.push_back("-fapplication-extension");
4309
4310 // Handle GCC-style exception args.
4311 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004312 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004313 CmdArgs);
4314
Martell Malonec950c652017-11-29 07:25:12 +00004315 // Handle exception personalities
4316 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4317 options::OPT_fseh_exceptions,
4318 options::OPT_fdwarf_exceptions);
4319 if (A) {
4320 const Option &Opt = A->getOption();
4321 if (Opt.matches(options::OPT_fsjlj_exceptions))
4322 CmdArgs.push_back("-fsjlj-exceptions");
4323 if (Opt.matches(options::OPT_fseh_exceptions))
4324 CmdArgs.push_back("-fseh-exceptions");
4325 if (Opt.matches(options::OPT_fdwarf_exceptions))
4326 CmdArgs.push_back("-fdwarf-exceptions");
4327 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004328 switch (getToolChain().GetExceptionModel(Args)) {
4329 default:
4330 break;
4331 case llvm::ExceptionHandling::DwarfCFI:
4332 CmdArgs.push_back("-fdwarf-exceptions");
4333 break;
4334 case llvm::ExceptionHandling::SjLj:
4335 CmdArgs.push_back("-fsjlj-exceptions");
4336 break;
4337 case llvm::ExceptionHandling::WinEH:
4338 CmdArgs.push_back("-fseh-exceptions");
4339 break;
Martell Malonec950c652017-11-29 07:25:12 +00004340 }
4341 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004342
4343 // C++ "sane" operator new.
4344 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4345 options::OPT_fno_assume_sane_operator_new))
4346 CmdArgs.push_back("-fno-assume-sane-operator-new");
4347
4348 // -frelaxed-template-template-args is off by default, as it is a severe
4349 // breaking change until a corresponding change to template partial ordering
4350 // is provided.
4351 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4352 options::OPT_fno_relaxed_template_template_args, false))
4353 CmdArgs.push_back("-frelaxed-template-template-args");
4354
4355 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4356 // most platforms.
4357 if (Args.hasFlag(options::OPT_fsized_deallocation,
4358 options::OPT_fno_sized_deallocation, false))
4359 CmdArgs.push_back("-fsized-deallocation");
4360
4361 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4362 // by default.
4363 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4364 options::OPT_fno_aligned_allocation,
4365 options::OPT_faligned_new_EQ)) {
4366 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4367 CmdArgs.push_back("-fno-aligned-allocation");
4368 else
4369 CmdArgs.push_back("-faligned-allocation");
4370 }
4371
4372 // The default new alignment can be specified using a dedicated option or via
4373 // a GCC-compatible option that also turns on aligned allocation.
4374 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4375 options::OPT_faligned_new_EQ))
4376 CmdArgs.push_back(
4377 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4378
4379 // -fconstant-cfstrings is default, and may be subject to argument translation
4380 // on Darwin.
4381 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4382 options::OPT_fno_constant_cfstrings) ||
4383 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4384 options::OPT_mno_constant_cfstrings))
4385 CmdArgs.push_back("-fno-constant-cfstrings");
4386
David L. Jonesf561aba2017-03-08 01:02:16 +00004387 // -fno-pascal-strings is default, only pass non-default.
4388 if (Args.hasFlag(options::OPT_fpascal_strings,
4389 options::OPT_fno_pascal_strings, false))
4390 CmdArgs.push_back("-fpascal-strings");
4391
4392 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4393 // -fno-pack-struct doesn't apply to -fpack-struct=.
4394 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4395 std::string PackStructStr = "-fpack-struct=";
4396 PackStructStr += A->getValue();
4397 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4398 } else if (Args.hasFlag(options::OPT_fpack_struct,
4399 options::OPT_fno_pack_struct, false)) {
4400 CmdArgs.push_back("-fpack-struct=1");
4401 }
4402
4403 // Handle -fmax-type-align=N and -fno-type-align
4404 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4405 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4406 if (!SkipMaxTypeAlign) {
4407 std::string MaxTypeAlignStr = "-fmax-type-align=";
4408 MaxTypeAlignStr += A->getValue();
4409 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4410 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004411 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004412 if (!SkipMaxTypeAlign) {
4413 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4414 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4415 }
4416 }
4417
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004418 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4419 CmdArgs.push_back("-Qn");
4420
David L. Jonesf561aba2017-03-08 01:02:16 +00004421 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004422 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004423 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4424 !NoCommonDefault))
4425 CmdArgs.push_back("-fno-common");
4426
4427 // -fsigned-bitfields is default, and clang doesn't yet support
4428 // -funsigned-bitfields.
4429 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4430 options::OPT_funsigned_bitfields))
4431 D.Diag(diag::warn_drv_clang_unsupported)
4432 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4433
4434 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4435 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4436 D.Diag(diag::err_drv_clang_unsupported)
4437 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4438
4439 // -finput_charset=UTF-8 is default. Reject others
4440 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4441 StringRef value = inputCharset->getValue();
4442 if (!value.equals_lower("utf-8"))
4443 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4444 << value;
4445 }
4446
4447 // -fexec_charset=UTF-8 is default. Reject others
4448 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4449 StringRef value = execCharset->getValue();
4450 if (!value.equals_lower("utf-8"))
4451 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4452 << value;
4453 }
4454
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004455 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004456
4457 // -fno-asm-blocks is default.
4458 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4459 false))
4460 CmdArgs.push_back("-fasm-blocks");
4461
4462 // -fgnu-inline-asm is default.
4463 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4464 options::OPT_fno_gnu_inline_asm, true))
4465 CmdArgs.push_back("-fno-gnu-inline-asm");
4466
4467 // Enable vectorization per default according to the optimization level
4468 // selected. For optimization levels that want vectorization we use the alias
4469 // option to simplify the hasFlag logic.
4470 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4471 OptSpecifier VectorizeAliasOption =
4472 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4473 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4474 options::OPT_fno_vectorize, EnableVec))
4475 CmdArgs.push_back("-vectorize-loops");
4476
4477 // -fslp-vectorize is enabled based on the optimization level selected.
4478 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4479 OptSpecifier SLPVectAliasOption =
4480 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4481 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4482 options::OPT_fno_slp_vectorize, EnableSLPVec))
4483 CmdArgs.push_back("-vectorize-slp");
4484
Craig Topper9a724aa2017-12-11 21:09:19 +00004485 ParseMPreferVectorWidth(D, Args, CmdArgs);
4486
David L. Jonesf561aba2017-03-08 01:02:16 +00004487 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4488 A->render(Args, CmdArgs);
4489
4490 if (Arg *A = Args.getLastArg(
4491 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4492 A->render(Args, CmdArgs);
4493
4494 // -fdollars-in-identifiers default varies depending on platform and
4495 // language; only pass if specified.
4496 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4497 options::OPT_fno_dollars_in_identifiers)) {
4498 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4499 CmdArgs.push_back("-fdollars-in-identifiers");
4500 else
4501 CmdArgs.push_back("-fno-dollars-in-identifiers");
4502 }
4503
4504 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4505 // practical purposes.
4506 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4507 options::OPT_fno_unit_at_a_time)) {
4508 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4509 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4510 }
4511
4512 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4513 options::OPT_fno_apple_pragma_pack, false))
4514 CmdArgs.push_back("-fapple-pragma-pack");
4515
David L. Jonesf561aba2017-03-08 01:02:16 +00004516 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004517 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004518 options::OPT_fno_save_optimization_record, false)) {
4519 CmdArgs.push_back("-opt-record-file");
4520
4521 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4522 if (A) {
4523 CmdArgs.push_back(A->getValue());
4524 } else {
4525 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004526
4527 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4528 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4529 F = FinalOutput->getValue();
4530 }
4531
4532 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004533 // Use the input filename.
4534 F = llvm::sys::path::stem(Input.getBaseInput());
4535
4536 // If we're compiling for an offload architecture (i.e. a CUDA device),
4537 // we need to make the file name for the device compilation different
4538 // from the host compilation.
4539 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4540 !JA.isDeviceOffloading(Action::OFK_Host)) {
4541 llvm::sys::path::replace_extension(F, "");
4542 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4543 Triple.normalize());
4544 F += "-";
4545 F += JA.getOffloadingArch();
4546 }
4547 }
4548
4549 llvm::sys::path::replace_extension(F, "opt.yaml");
4550 CmdArgs.push_back(Args.MakeArgString(F));
4551 }
4552 }
4553
Richard Smith86a3ef52017-06-09 21:24:02 +00004554 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4555 options::OPT_fno_rewrite_imports, false);
4556 if (RewriteImports)
4557 CmdArgs.push_back("-frewrite-imports");
4558
David L. Jonesf561aba2017-03-08 01:02:16 +00004559 // Enable rewrite includes if the user's asked for it or if we're generating
4560 // diagnostics.
4561 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4562 // nice to enable this when doing a crashdump for modules as well.
4563 if (Args.hasFlag(options::OPT_frewrite_includes,
4564 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004565 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004566 CmdArgs.push_back("-frewrite-includes");
4567
4568 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4569 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4570 options::OPT_traditional_cpp)) {
4571 if (isa<PreprocessJobAction>(JA))
4572 CmdArgs.push_back("-traditional-cpp");
4573 else
4574 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4575 }
4576
4577 Args.AddLastArg(CmdArgs, options::OPT_dM);
4578 Args.AddLastArg(CmdArgs, options::OPT_dD);
4579
4580 // Handle serialized diagnostics.
4581 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4582 CmdArgs.push_back("-serialize-diagnostic-file");
4583 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4584 }
4585
4586 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4587 CmdArgs.push_back("-fretain-comments-from-system-headers");
4588
4589 // Forward -fcomment-block-commands to -cc1.
4590 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4591 // Forward -fparse-all-comments to -cc1.
4592 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4593
4594 // Turn -fplugin=name.so into -load name.so
4595 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4596 CmdArgs.push_back("-load");
4597 CmdArgs.push_back(A->getValue());
4598 A->claim();
4599 }
4600
4601 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004602 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4603 if (!StatsFile.empty())
4604 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004605
4606 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4607 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004608 // -finclude-default-header flag is for preprocessor,
4609 // do not pass it to other cc1 commands when save-temps is enabled
4610 if (C.getDriver().isSaveTempsEnabled() &&
4611 !isa<PreprocessJobAction>(JA)) {
4612 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4613 Arg->claim();
4614 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4615 CmdArgs.push_back(Arg->getValue());
4616 }
4617 }
4618 else {
4619 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4620 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004621 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4622 A->claim();
4623
4624 // We translate this by hand to the -cc1 argument, since nightly test uses
4625 // it and developers have been trained to spell it with -mllvm. Both
4626 // spellings are now deprecated and should be removed.
4627 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4628 CmdArgs.push_back("-disable-llvm-optzns");
4629 } else {
4630 A->render(Args, CmdArgs);
4631 }
4632 }
4633
4634 // With -save-temps, we want to save the unoptimized bitcode output from the
4635 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4636 // by the frontend.
4637 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4638 // has slightly different breakdown between stages.
4639 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4640 // pristine IR generated by the frontend. Ideally, a new compile action should
4641 // be added so both IR can be captured.
4642 if (C.getDriver().isSaveTempsEnabled() &&
4643 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4644 isa<CompileJobAction>(JA))
4645 CmdArgs.push_back("-disable-llvm-passes");
4646
4647 if (Output.getType() == types::TY_Dependencies) {
4648 // Handled with other dependency code.
4649 } else if (Output.isFilename()) {
4650 CmdArgs.push_back("-o");
4651 CmdArgs.push_back(Output.getFilename());
4652 } else {
4653 assert(Output.isNothing() && "Invalid output.");
4654 }
4655
4656 addDashXForInput(Args, Input, CmdArgs);
4657
4658 if (Input.isFilename())
4659 CmdArgs.push_back(Input.getFilename());
4660 else
4661 Input.getInputArg().renderAsInput(Args, CmdArgs);
4662
4663 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4664
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004665 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004666
4667 // Optionally embed the -cc1 level arguments into the debug info, for build
4668 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004669 // Also record command line arguments into the debug info if
4670 // -grecord-gcc-switches options is set on.
4671 // By default, -gno-record-gcc-switches is set on and no recording.
4672 if (getToolChain().UseDwarfDebugFlags() ||
4673 Args.hasFlag(options::OPT_grecord_gcc_switches,
4674 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004675 ArgStringList OriginalArgs;
4676 for (const auto &Arg : Args)
4677 Arg->render(Args, OriginalArgs);
4678
4679 SmallString<256> Flags;
4680 Flags += Exec;
4681 for (const char *OriginalArg : OriginalArgs) {
4682 SmallString<128> EscapedArg;
4683 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4684 Flags += " ";
4685 Flags += EscapedArg;
4686 }
4687 CmdArgs.push_back("-dwarf-debug-flags");
4688 CmdArgs.push_back(Args.MakeArgString(Flags));
4689 }
4690
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004691 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004692 // Host-side cuda compilation receives all device-side outputs in a single
4693 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004694 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004695 assert(Inputs.size() == 2 && "More than one GPU binary!");
4696 CmdArgs.push_back("-fcuda-include-gpubinary");
4697 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004698 }
4699
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004700 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4701 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004702 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4703 options::OPT_fno_cuda_short_ptr, false))
4704 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004705 }
4706
David L. Jonesf561aba2017-03-08 01:02:16 +00004707 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4708 // to specify the result of the compile phase on the host, so the meaningful
4709 // device declarations can be identified. Also, -fopenmp-is-device is passed
4710 // along to tell the frontend that it is generating code for a device, so that
4711 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004712 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004713 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004714 if (Inputs.size() == 2) {
4715 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4716 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4717 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004718 }
4719
4720 // For all the host OpenMP offloading compile jobs we need to pass the targets
4721 // information using -fopenmp-targets= option.
4722 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4723 SmallString<128> TargetInfo("-fopenmp-targets=");
4724
4725 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4726 assert(Tgts && Tgts->getNumValues() &&
4727 "OpenMP offloading has to have targets specified.");
4728 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4729 if (i)
4730 TargetInfo += ',';
4731 // We need to get the string from the triple because it may be not exactly
4732 // the same as the one we get directly from the arguments.
4733 llvm::Triple T(Tgts->getValue(i));
4734 TargetInfo += T.getTriple();
4735 }
4736 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4737 }
4738
4739 bool WholeProgramVTables =
4740 Args.hasFlag(options::OPT_fwhole_program_vtables,
4741 options::OPT_fno_whole_program_vtables, false);
4742 if (WholeProgramVTables) {
4743 if (!D.isUsingLTO())
4744 D.Diag(diag::err_drv_argument_only_allowed_with)
4745 << "-fwhole-program-vtables"
4746 << "-flto";
4747 CmdArgs.push_back("-fwhole-program-vtables");
4748 }
4749
Amara Emerson4ee9f822018-01-26 00:27:22 +00004750 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4751 options::OPT_fno_experimental_isel)) {
4752 CmdArgs.push_back("-mllvm");
4753 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4754 CmdArgs.push_back("-global-isel=1");
4755
4756 // GISel is on by default on AArch64 -O0, so don't bother adding
4757 // the fallback remarks for it. Other combinations will add a warning of
4758 // some kind.
4759 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4760 bool IsOptLevelSupported = false;
4761
4762 Arg *A = Args.getLastArg(options::OPT_O_Group);
4763 if (Triple.getArch() == llvm::Triple::aarch64) {
4764 if (!A || A->getOption().matches(options::OPT_O0))
4765 IsOptLevelSupported = true;
4766 }
4767 if (!IsArchSupported || !IsOptLevelSupported) {
4768 CmdArgs.push_back("-mllvm");
4769 CmdArgs.push_back("-global-isel-abort=2");
4770
4771 if (!IsArchSupported)
4772 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4773 else
4774 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4775 }
4776 } else {
4777 CmdArgs.push_back("-global-isel=0");
4778 }
4779 }
4780
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004781 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4782 options::OPT_fno_force_enable_int128)) {
4783 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4784 CmdArgs.push_back("-fforce-enable-int128");
4785 }
4786
David L. Jonesf561aba2017-03-08 01:02:16 +00004787 // Finally add the compile command to the compilation.
4788 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4789 Output.getType() == types::TY_Object &&
4790 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4791 auto CLCommand =
4792 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4793 C.addCommand(llvm::make_unique<FallbackCommand>(
4794 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4795 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4796 isa<PrecompileJobAction>(JA)) {
4797 // In /fallback builds, run the main compilation even if the pch generation
4798 // fails, so that the main compilation's fallback to cl.exe runs.
4799 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4800 CmdArgs, Inputs));
4801 } else {
4802 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4803 }
4804
David L. Jonesf561aba2017-03-08 01:02:16 +00004805 if (Arg *A = Args.getLastArg(options::OPT_pg))
4806 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4807 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4808 << A->getAsString(Args);
4809
4810 // Claim some arguments which clang supports automatically.
4811
4812 // -fpch-preprocess is used with gcc to add a special marker in the output to
4813 // include the PCH file. Clang's PTH solution is completely transparent, so we
4814 // do not need to deal with it at all.
4815 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4816
4817 // Claim some arguments which clang doesn't support, but we don't
4818 // care to warn the user about.
4819 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4820 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4821
4822 // Disable warnings for clang -E -emit-llvm foo.c
4823 Args.ClaimAllArgs(options::OPT_emit_llvm);
4824}
4825
4826Clang::Clang(const ToolChain &TC)
4827 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4828 // as it is for other tools. Some operations on a Tool actually test
4829 // whether that tool is Clang based on the Tool's Name as a string.
4830 : Tool("clang", "clang frontend", TC, RF_Full) {}
4831
4832Clang::~Clang() {}
4833
4834/// Add options related to the Objective-C runtime/ABI.
4835///
4836/// Returns true if the runtime is non-fragile.
4837ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4838 ArgStringList &cmdArgs,
4839 RewriteKind rewriteKind) const {
4840 // Look for the controlling runtime option.
4841 Arg *runtimeArg =
4842 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4843 options::OPT_fobjc_runtime_EQ);
4844
4845 // Just forward -fobjc-runtime= to the frontend. This supercedes
4846 // options about fragility.
4847 if (runtimeArg &&
4848 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4849 ObjCRuntime runtime;
4850 StringRef value = runtimeArg->getValue();
4851 if (runtime.tryParse(value)) {
4852 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4853 << value;
4854 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004855 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4856 (runtime.getVersion() >= VersionTuple(2, 0)))
4857 if (!getToolChain().getTriple().isOSBinFormatELF()) {
4858 getToolChain().getDriver().Diag(
4859 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4860 << runtime.getVersion().getMajor();
4861 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004862
4863 runtimeArg->render(args, cmdArgs);
4864 return runtime;
4865 }
4866
4867 // Otherwise, we'll need the ABI "version". Version numbers are
4868 // slightly confusing for historical reasons:
4869 // 1 - Traditional "fragile" ABI
4870 // 2 - Non-fragile ABI, version 1
4871 // 3 - Non-fragile ABI, version 2
4872 unsigned objcABIVersion = 1;
4873 // If -fobjc-abi-version= is present, use that to set the version.
4874 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4875 StringRef value = abiArg->getValue();
4876 if (value == "1")
4877 objcABIVersion = 1;
4878 else if (value == "2")
4879 objcABIVersion = 2;
4880 else if (value == "3")
4881 objcABIVersion = 3;
4882 else
4883 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4884 } else {
4885 // Otherwise, determine if we are using the non-fragile ABI.
4886 bool nonFragileABIIsDefault =
4887 (rewriteKind == RK_NonFragile ||
4888 (rewriteKind == RK_None &&
4889 getToolChain().IsObjCNonFragileABIDefault()));
4890 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4891 options::OPT_fno_objc_nonfragile_abi,
4892 nonFragileABIIsDefault)) {
4893// Determine the non-fragile ABI version to use.
4894#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4895 unsigned nonFragileABIVersion = 1;
4896#else
4897 unsigned nonFragileABIVersion = 2;
4898#endif
4899
4900 if (Arg *abiArg =
4901 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4902 StringRef value = abiArg->getValue();
4903 if (value == "1")
4904 nonFragileABIVersion = 1;
4905 else if (value == "2")
4906 nonFragileABIVersion = 2;
4907 else
4908 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4909 << value;
4910 }
4911
4912 objcABIVersion = 1 + nonFragileABIVersion;
4913 } else {
4914 objcABIVersion = 1;
4915 }
4916 }
4917
4918 // We don't actually care about the ABI version other than whether
4919 // it's non-fragile.
4920 bool isNonFragile = objcABIVersion != 1;
4921
4922 // If we have no runtime argument, ask the toolchain for its default runtime.
4923 // However, the rewriter only really supports the Mac runtime, so assume that.
4924 ObjCRuntime runtime;
4925 if (!runtimeArg) {
4926 switch (rewriteKind) {
4927 case RK_None:
4928 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4929 break;
4930 case RK_Fragile:
4931 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4932 break;
4933 case RK_NonFragile:
4934 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4935 break;
4936 }
4937
4938 // -fnext-runtime
4939 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4940 // On Darwin, make this use the default behavior for the toolchain.
4941 if (getToolChain().getTriple().isOSDarwin()) {
4942 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4943
4944 // Otherwise, build for a generic macosx port.
4945 } else {
4946 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4947 }
4948
4949 // -fgnu-runtime
4950 } else {
4951 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4952 // Legacy behaviour is to target the gnustep runtime if we are in
4953 // non-fragile mode or the GCC runtime in fragile mode.
4954 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00004955 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00004956 else
4957 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4958 }
4959
4960 cmdArgs.push_back(
4961 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4962 return runtime;
4963}
4964
4965static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4966 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4967 I += HaveDash;
4968 return !HaveDash;
4969}
4970
4971namespace {
4972struct EHFlags {
4973 bool Synch = false;
4974 bool Asynch = false;
4975 bool NoUnwindC = false;
4976};
4977} // end anonymous namespace
4978
4979/// /EH controls whether to run destructor cleanups when exceptions are
4980/// thrown. There are three modifiers:
4981/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4982/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4983/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4984/// - c: Assume that extern "C" functions are implicitly nounwind.
4985/// The default is /EHs-c-, meaning cleanups are disabled.
4986static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4987 EHFlags EH;
4988
4989 std::vector<std::string> EHArgs =
4990 Args.getAllArgValues(options::OPT__SLASH_EH);
4991 for (auto EHVal : EHArgs) {
4992 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4993 switch (EHVal[I]) {
4994 case 'a':
4995 EH.Asynch = maybeConsumeDash(EHVal, I);
4996 if (EH.Asynch)
4997 EH.Synch = false;
4998 continue;
4999 case 'c':
5000 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5001 continue;
5002 case 's':
5003 EH.Synch = maybeConsumeDash(EHVal, I);
5004 if (EH.Synch)
5005 EH.Asynch = false;
5006 continue;
5007 default:
5008 break;
5009 }
5010 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5011 break;
5012 }
5013 }
5014 // The /GX, /GX- flags are only processed if there are not /EH flags.
5015 // The default is that /GX is not specified.
5016 if (EHArgs.empty() &&
5017 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5018 /*default=*/false)) {
5019 EH.Synch = true;
5020 EH.NoUnwindC = true;
5021 }
5022
5023 return EH;
5024}
5025
5026void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5027 ArgStringList &CmdArgs,
5028 codegenoptions::DebugInfoKind *DebugInfoKind,
5029 bool *EmitCodeView) const {
5030 unsigned RTOptionID = options::OPT__SLASH_MT;
5031
5032 if (Args.hasArg(options::OPT__SLASH_LDd))
5033 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5034 // but defining _DEBUG is sticky.
5035 RTOptionID = options::OPT__SLASH_MTd;
5036
5037 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5038 RTOptionID = A->getOption().getID();
5039
5040 StringRef FlagForCRT;
5041 switch (RTOptionID) {
5042 case options::OPT__SLASH_MD:
5043 if (Args.hasArg(options::OPT__SLASH_LDd))
5044 CmdArgs.push_back("-D_DEBUG");
5045 CmdArgs.push_back("-D_MT");
5046 CmdArgs.push_back("-D_DLL");
5047 FlagForCRT = "--dependent-lib=msvcrt";
5048 break;
5049 case options::OPT__SLASH_MDd:
5050 CmdArgs.push_back("-D_DEBUG");
5051 CmdArgs.push_back("-D_MT");
5052 CmdArgs.push_back("-D_DLL");
5053 FlagForCRT = "--dependent-lib=msvcrtd";
5054 break;
5055 case options::OPT__SLASH_MT:
5056 if (Args.hasArg(options::OPT__SLASH_LDd))
5057 CmdArgs.push_back("-D_DEBUG");
5058 CmdArgs.push_back("-D_MT");
5059 CmdArgs.push_back("-flto-visibility-public-std");
5060 FlagForCRT = "--dependent-lib=libcmt";
5061 break;
5062 case options::OPT__SLASH_MTd:
5063 CmdArgs.push_back("-D_DEBUG");
5064 CmdArgs.push_back("-D_MT");
5065 CmdArgs.push_back("-flto-visibility-public-std");
5066 FlagForCRT = "--dependent-lib=libcmtd";
5067 break;
5068 default:
5069 llvm_unreachable("Unexpected option ID.");
5070 }
5071
5072 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5073 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5074 } else {
5075 CmdArgs.push_back(FlagForCRT.data());
5076
5077 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5078 // users want. The /Za flag to cl.exe turns this off, but it's not
5079 // implemented in clang.
5080 CmdArgs.push_back("--dependent-lib=oldnames");
5081 }
5082
Erich Keane425f48d2018-05-04 15:58:31 +00005083 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5084 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005085
5086 // This controls whether or not we emit RTTI data for polymorphic types.
5087 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5088 /*default=*/false))
5089 CmdArgs.push_back("-fno-rtti-data");
5090
5091 // This controls whether or not we emit stack-protector instrumentation.
5092 // In MSVC, Buffer Security Check (/GS) is on by default.
5093 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5094 /*default=*/true)) {
5095 CmdArgs.push_back("-stack-protector");
5096 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5097 }
5098
5099 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5100 if (Arg *DebugInfoArg =
5101 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5102 options::OPT_gline_tables_only)) {
5103 *EmitCodeView = true;
5104 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5105 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5106 else
5107 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5108 CmdArgs.push_back("-gcodeview");
5109 } else {
5110 *EmitCodeView = false;
5111 }
5112
5113 const Driver &D = getToolChain().getDriver();
5114 EHFlags EH = parseClangCLEHFlags(D, Args);
5115 if (EH.Synch || EH.Asynch) {
5116 if (types::isCXX(InputType))
5117 CmdArgs.push_back("-fcxx-exceptions");
5118 CmdArgs.push_back("-fexceptions");
5119 }
5120 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5121 CmdArgs.push_back("-fexternc-nounwind");
5122
5123 // /EP should expand to -E -P.
5124 if (Args.hasArg(options::OPT__SLASH_EP)) {
5125 CmdArgs.push_back("-E");
5126 CmdArgs.push_back("-P");
5127 }
5128
5129 unsigned VolatileOptionID;
5130 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5131 getToolChain().getArch() == llvm::Triple::x86)
5132 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5133 else
5134 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5135
5136 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5137 VolatileOptionID = A->getOption().getID();
5138
5139 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5140 CmdArgs.push_back("-fms-volatile");
5141
5142 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5143 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5144 if (MostGeneralArg && BestCaseArg)
5145 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5146 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5147
5148 if (MostGeneralArg) {
5149 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5150 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5151 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5152
5153 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5154 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5155 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5156 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5157 << FirstConflict->getAsString(Args)
5158 << SecondConflict->getAsString(Args);
5159
5160 if (SingleArg)
5161 CmdArgs.push_back("-fms-memptr-rep=single");
5162 else if (MultipleArg)
5163 CmdArgs.push_back("-fms-memptr-rep=multiple");
5164 else
5165 CmdArgs.push_back("-fms-memptr-rep=virtual");
5166 }
5167
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005168 // Parse the default calling convention options.
5169 if (Arg *CCArg =
5170 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005171 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5172 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005173 unsigned DCCOptId = CCArg->getOption().getID();
5174 const char *DCCFlag = nullptr;
5175 bool ArchSupported = true;
5176 llvm::Triple::ArchType Arch = getToolChain().getArch();
5177 switch (DCCOptId) {
5178 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005179 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005180 break;
5181 case options::OPT__SLASH_Gr:
5182 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005183 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005184 break;
5185 case options::OPT__SLASH_Gz:
5186 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005187 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005188 break;
5189 case options::OPT__SLASH_Gv:
5190 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005191 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005192 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005193 case options::OPT__SLASH_Gregcall:
5194 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5195 DCCFlag = "-fdefault-calling-conv=regcall";
5196 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005197 }
5198
5199 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5200 if (ArchSupported && DCCFlag)
5201 CmdArgs.push_back(DCCFlag);
5202 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005203
5204 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5205 A->render(Args, CmdArgs);
5206
5207 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5208 CmdArgs.push_back("-fdiagnostics-format");
5209 if (Args.hasArg(options::OPT__SLASH_fallback))
5210 CmdArgs.push_back("msvc-fallback");
5211 else
5212 CmdArgs.push_back("msvc");
5213 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005214
5215 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5216 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5217 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005218}
5219
5220visualstudio::Compiler *Clang::getCLFallback() const {
5221 if (!CLFallback)
5222 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5223 return CLFallback.get();
5224}
5225
5226
5227const char *Clang::getBaseInputName(const ArgList &Args,
5228 const InputInfo &Input) {
5229 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5230}
5231
5232const char *Clang::getBaseInputStem(const ArgList &Args,
5233 const InputInfoList &Inputs) {
5234 const char *Str = getBaseInputName(Args, Inputs[0]);
5235
5236 if (const char *End = strrchr(Str, '.'))
5237 return Args.MakeArgString(std::string(Str, End));
5238
5239 return Str;
5240}
5241
5242const char *Clang::getDependencyFileName(const ArgList &Args,
5243 const InputInfoList &Inputs) {
5244 // FIXME: Think about this more.
5245 std::string Res;
5246
5247 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5248 std::string Str(OutputOpt->getValue());
5249 Res = Str.substr(0, Str.rfind('.'));
5250 } else {
5251 Res = getBaseInputStem(Args, Inputs);
5252 }
5253 return Args.MakeArgString(Res + ".d");
5254}
5255
5256// Begin ClangAs
5257
5258void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5259 ArgStringList &CmdArgs) const {
5260 StringRef CPUName;
5261 StringRef ABIName;
5262 const llvm::Triple &Triple = getToolChain().getTriple();
5263 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5264
5265 CmdArgs.push_back("-target-abi");
5266 CmdArgs.push_back(ABIName.data());
5267}
5268
5269void ClangAs::AddX86TargetArgs(const ArgList &Args,
5270 ArgStringList &CmdArgs) const {
5271 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5272 StringRef Value = A->getValue();
5273 if (Value == "intel" || Value == "att") {
5274 CmdArgs.push_back("-mllvm");
5275 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5276 } else {
5277 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5278 << A->getOption().getName() << Value;
5279 }
5280 }
5281}
5282
5283void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5284 const InputInfo &Output, const InputInfoList &Inputs,
5285 const ArgList &Args,
5286 const char *LinkingOutput) const {
5287 ArgStringList CmdArgs;
5288
5289 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5290 const InputInfo &Input = Inputs[0];
5291
5292 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5293 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005294 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005295
5296 // Don't warn about "clang -w -c foo.s"
5297 Args.ClaimAllArgs(options::OPT_w);
5298 // and "clang -emit-llvm -c foo.s"
5299 Args.ClaimAllArgs(options::OPT_emit_llvm);
5300
5301 claimNoWarnArgs(Args);
5302
5303 // Invoke ourselves in -cc1as mode.
5304 //
5305 // FIXME: Implement custom jobs for internal actions.
5306 CmdArgs.push_back("-cc1as");
5307
5308 // Add the "effective" target triple.
5309 CmdArgs.push_back("-triple");
5310 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5311
5312 // Set the output mode, we currently only expect to be used as a real
5313 // assembler.
5314 CmdArgs.push_back("-filetype");
5315 CmdArgs.push_back("obj");
5316
5317 // Set the main file name, so that debug info works even with
5318 // -save-temps or preprocessed assembly.
5319 CmdArgs.push_back("-main-file-name");
5320 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5321
5322 // Add the target cpu
5323 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5324 if (!CPU.empty()) {
5325 CmdArgs.push_back("-target-cpu");
5326 CmdArgs.push_back(Args.MakeArgString(CPU));
5327 }
5328
5329 // Add the target features
5330 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5331
5332 // Ignore explicit -force_cpusubtype_ALL option.
5333 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5334
5335 // Pass along any -I options so we get proper .include search paths.
5336 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5337
5338 // Determine the original source input.
5339 const Action *SourceAction = &JA;
5340 while (SourceAction->getKind() != Action::InputClass) {
5341 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5342 SourceAction = SourceAction->getInputs()[0];
5343 }
5344
5345 // Forward -g and handle debug info related flags, assuming we are dealing
5346 // with an actual assembly file.
5347 bool WantDebug = false;
5348 unsigned DwarfVersion = 0;
5349 Args.ClaimAllArgs(options::OPT_g_Group);
5350 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5351 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5352 !A->getOption().matches(options::OPT_ggdb0);
5353 if (WantDebug)
5354 DwarfVersion = DwarfVersionNum(A->getSpelling());
5355 }
5356 if (DwarfVersion == 0)
5357 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5358
5359 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5360
5361 if (SourceAction->getType() == types::TY_Asm ||
5362 SourceAction->getType() == types::TY_PP_Asm) {
5363 // You might think that it would be ok to set DebugInfoKind outside of
5364 // the guard for source type, however there is a test which asserts
5365 // that some assembler invocation receives no -debug-info-kind,
5366 // and it's not clear whether that test is just overly restrictive.
5367 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5368 : codegenoptions::NoDebugInfo);
5369 // Add the -fdebug-compilation-dir flag if needed.
5370 addDebugCompDirArg(Args, CmdArgs);
5371
5372 // Set the AT_producer to the clang version when using the integrated
5373 // assembler on assembly source files.
5374 CmdArgs.push_back("-dwarf-debug-producer");
5375 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5376
5377 // And pass along -I options
5378 Args.AddAllArgs(CmdArgs, options::OPT_I);
5379 }
5380 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5381 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005382 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5383
David L. Jonesf561aba2017-03-08 01:02:16 +00005384
5385 // Handle -fPIC et al -- the relocation-model affects the assembler
5386 // for some targets.
5387 llvm::Reloc::Model RelocationModel;
5388 unsigned PICLevel;
5389 bool IsPIE;
5390 std::tie(RelocationModel, PICLevel, IsPIE) =
5391 ParsePICArgs(getToolChain(), Args);
5392
5393 const char *RMName = RelocationModelName(RelocationModel);
5394 if (RMName) {
5395 CmdArgs.push_back("-mrelocation-model");
5396 CmdArgs.push_back(RMName);
5397 }
5398
5399 // Optionally embed the -cc1as level arguments into the debug info, for build
5400 // analysis.
5401 if (getToolChain().UseDwarfDebugFlags()) {
5402 ArgStringList OriginalArgs;
5403 for (const auto &Arg : Args)
5404 Arg->render(Args, OriginalArgs);
5405
5406 SmallString<256> Flags;
5407 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5408 Flags += Exec;
5409 for (const char *OriginalArg : OriginalArgs) {
5410 SmallString<128> EscapedArg;
5411 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5412 Flags += " ";
5413 Flags += EscapedArg;
5414 }
5415 CmdArgs.push_back("-dwarf-debug-flags");
5416 CmdArgs.push_back(Args.MakeArgString(Flags));
5417 }
5418
5419 // FIXME: Add -static support, once we have it.
5420
5421 // Add target specific flags.
5422 switch (getToolChain().getArch()) {
5423 default:
5424 break;
5425
5426 case llvm::Triple::mips:
5427 case llvm::Triple::mipsel:
5428 case llvm::Triple::mips64:
5429 case llvm::Triple::mips64el:
5430 AddMIPSTargetArgs(Args, CmdArgs);
5431 break;
5432
5433 case llvm::Triple::x86:
5434 case llvm::Triple::x86_64:
5435 AddX86TargetArgs(Args, CmdArgs);
5436 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005437
5438 case llvm::Triple::arm:
5439 case llvm::Triple::armeb:
5440 case llvm::Triple::thumb:
5441 case llvm::Triple::thumbeb:
5442 // This isn't in AddARMTargetArgs because we want to do this for assembly
5443 // only, not C/C++.
5444 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5445 options::OPT_mno_default_build_attributes, true)) {
5446 CmdArgs.push_back("-mllvm");
5447 CmdArgs.push_back("-arm-add-build-attributes");
5448 }
5449 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005450 }
5451
5452 // Consume all the warning flags. Usually this would be handled more
5453 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5454 // doesn't handle that so rather than warning about unused flags that are
5455 // actually used, we'll lie by omission instead.
5456 // FIXME: Stop lying and consume only the appropriate driver flags
5457 Args.ClaimAllArgs(options::OPT_W_Group);
5458
5459 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5460 getToolChain().getDriver());
5461
5462 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5463
5464 assert(Output.isFilename() && "Unexpected lipo output.");
5465 CmdArgs.push_back("-o");
5466 CmdArgs.push_back(Output.getFilename());
5467
Peter Collingbourne47bc0172018-05-21 20:31:59 +00005468 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5469 getToolChain().getTriple().isOSLinux()) {
5470 CmdArgs.push_back("-split-dwarf-file");
5471 CmdArgs.push_back(SplitDebugName(Args, Input));
5472 }
5473
David L. Jonesf561aba2017-03-08 01:02:16 +00005474 assert(Input.isFilename() && "Invalid input.");
5475 CmdArgs.push_back(Input.getFilename());
5476
5477 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5478 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005479}
5480
5481// Begin OffloadBundler
5482
5483void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5484 const InputInfo &Output,
5485 const InputInfoList &Inputs,
5486 const llvm::opt::ArgList &TCArgs,
5487 const char *LinkingOutput) const {
5488 // The version with only one output is expected to refer to a bundling job.
5489 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5490
5491 // The bundling command looks like this:
5492 // clang-offload-bundler -type=bc
5493 // -targets=host-triple,openmp-triple1,openmp-triple2
5494 // -outputs=input_file
5495 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5496
5497 ArgStringList CmdArgs;
5498
5499 // Get the type.
5500 CmdArgs.push_back(TCArgs.MakeArgString(
5501 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5502
5503 assert(JA.getInputs().size() == Inputs.size() &&
5504 "Not have inputs for all dependence actions??");
5505
5506 // Get the targets.
5507 SmallString<128> Triples;
5508 Triples += "-targets=";
5509 for (unsigned I = 0; I < Inputs.size(); ++I) {
5510 if (I)
5511 Triples += ',';
5512
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005513 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005514 Action::OffloadKind CurKind = Action::OFK_Host;
5515 const ToolChain *CurTC = &getToolChain();
5516 const Action *CurDep = JA.getInputs()[I];
5517
5518 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005519 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005520 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005521 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005522 CurKind = A->getOffloadingDeviceKind();
5523 CurTC = TC;
5524 });
5525 }
5526 Triples += Action::GetOffloadKindName(CurKind);
5527 Triples += '-';
5528 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005529 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5530 Triples += '-';
5531 Triples += CurDep->getOffloadingArch();
5532 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005533 }
5534 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5535
5536 // Get bundled file command.
5537 CmdArgs.push_back(
5538 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5539
5540 // Get unbundled files command.
5541 SmallString<128> UB;
5542 UB += "-inputs=";
5543 for (unsigned I = 0; I < Inputs.size(); ++I) {
5544 if (I)
5545 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005546
5547 // Find ToolChain for this input.
5548 const ToolChain *CurTC = &getToolChain();
5549 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5550 CurTC = nullptr;
5551 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5552 assert(CurTC == nullptr && "Expected one dependence!");
5553 CurTC = TC;
5554 });
5555 }
5556 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005557 }
5558 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5559
5560 // All the inputs are encoded as commands.
5561 C.addCommand(llvm::make_unique<Command>(
5562 JA, *this,
5563 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5564 CmdArgs, None));
5565}
5566
5567void OffloadBundler::ConstructJobMultipleOutputs(
5568 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5569 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5570 const char *LinkingOutput) const {
5571 // The version with multiple outputs is expected to refer to a unbundling job.
5572 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5573
5574 // The unbundling command looks like this:
5575 // clang-offload-bundler -type=bc
5576 // -targets=host-triple,openmp-triple1,openmp-triple2
5577 // -inputs=input_file
5578 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5579 // -unbundle
5580
5581 ArgStringList CmdArgs;
5582
5583 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5584 InputInfo Input = Inputs.front();
5585
5586 // Get the type.
5587 CmdArgs.push_back(TCArgs.MakeArgString(
5588 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5589
5590 // Get the targets.
5591 SmallString<128> Triples;
5592 Triples += "-targets=";
5593 auto DepInfo = UA.getDependentActionsInfo();
5594 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5595 if (I)
5596 Triples += ',';
5597
5598 auto &Dep = DepInfo[I];
5599 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5600 Triples += '-';
5601 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005602 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5603 !Dep.DependentBoundArch.empty()) {
5604 Triples += '-';
5605 Triples += Dep.DependentBoundArch;
5606 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005607 }
5608
5609 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5610
5611 // Get bundled file command.
5612 CmdArgs.push_back(
5613 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5614
5615 // Get unbundled files command.
5616 SmallString<128> UB;
5617 UB += "-outputs=";
5618 for (unsigned I = 0; I < Outputs.size(); ++I) {
5619 if (I)
5620 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005621 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005622 }
5623 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5624 CmdArgs.push_back("-unbundle");
5625
5626 // All the inputs are encoded as commands.
5627 C.addCommand(llvm::make_unique<Command>(
5628 JA, *this,
5629 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5630 CmdArgs, None));
5631}