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