blob: 8d73db1ca22c517adf6d6a141180a1667f74cddc [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 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001458
1459 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address)) {
1460 CmdArgs.push_back(
1461 Args.MakeArgString(Twine("-msign-return-address=") + A->getValue()));
1462 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001463}
1464
1465void Clang::AddMIPSTargetArgs(const ArgList &Args,
1466 ArgStringList &CmdArgs) const {
1467 const Driver &D = getToolChain().getDriver();
1468 StringRef CPUName;
1469 StringRef ABIName;
1470 const llvm::Triple &Triple = getToolChain().getTriple();
1471 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1472
1473 CmdArgs.push_back("-target-abi");
1474 CmdArgs.push_back(ABIName.data());
1475
1476 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1477 if (ABI == mips::FloatABI::Soft) {
1478 // Floating point operations and argument passing are soft.
1479 CmdArgs.push_back("-msoft-float");
1480 CmdArgs.push_back("-mfloat-abi");
1481 CmdArgs.push_back("soft");
1482 } else {
1483 // Floating point operations and argument passing are hard.
1484 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1485 CmdArgs.push_back("-mfloat-abi");
1486 CmdArgs.push_back("hard");
1487 }
1488
1489 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1490 if (A->getOption().matches(options::OPT_mxgot)) {
1491 CmdArgs.push_back("-mllvm");
1492 CmdArgs.push_back("-mxgot");
1493 }
1494 }
1495
1496 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1497 options::OPT_mno_ldc1_sdc1)) {
1498 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1499 CmdArgs.push_back("-mllvm");
1500 CmdArgs.push_back("-mno-ldc1-sdc1");
1501 }
1502 }
1503
1504 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1505 options::OPT_mno_check_zero_division)) {
1506 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1507 CmdArgs.push_back("-mllvm");
1508 CmdArgs.push_back("-mno-check-zero-division");
1509 }
1510 }
1511
1512 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1513 StringRef v = A->getValue();
1514 CmdArgs.push_back("-mllvm");
1515 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1516 A->claim();
1517 }
1518
Simon Dardis31636a12017-07-20 14:04:12 +00001519 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1520 Arg *ABICalls =
1521 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1522
1523 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1524 // -mgpopt is the default for static, -fno-pic environments but these two
1525 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1526 // the only case where -mllvm -mgpopt is passed.
1527 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1528 // passed explicitly when compiling something with -mabicalls
1529 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001530 //
1531 // When the ABI in use is N64, we also need to determine the PIC mode that
1532 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001533 bool NoABICalls =
1534 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001535
1536 llvm::Reloc::Model RelocationModel;
1537 unsigned PICLevel;
1538 bool IsPIE;
1539 std::tie(RelocationModel, PICLevel, IsPIE) =
1540 ParsePICArgs(getToolChain(), Args);
1541
1542 NoABICalls = NoABICalls ||
1543 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1544
Simon Dardis31636a12017-07-20 14:04:12 +00001545 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1546 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1547 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1548 CmdArgs.push_back("-mllvm");
1549 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001550
1551 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1552 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001553 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001554 options::OPT_mno_extern_sdata);
1555 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1556 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001557 if (LocalSData) {
1558 CmdArgs.push_back("-mllvm");
1559 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1560 CmdArgs.push_back("-mlocal-sdata=1");
1561 } else {
1562 CmdArgs.push_back("-mlocal-sdata=0");
1563 }
1564 LocalSData->claim();
1565 }
1566
Simon Dardis7d318782017-07-24 14:02:09 +00001567 if (ExternSData) {
1568 CmdArgs.push_back("-mllvm");
1569 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1570 CmdArgs.push_back("-mextern-sdata=1");
1571 } else {
1572 CmdArgs.push_back("-mextern-sdata=0");
1573 }
1574 ExternSData->claim();
1575 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001576
1577 if (EmbeddedData) {
1578 CmdArgs.push_back("-mllvm");
1579 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1580 CmdArgs.push_back("-membedded-data=1");
1581 } else {
1582 CmdArgs.push_back("-membedded-data=0");
1583 }
1584 EmbeddedData->claim();
1585 }
1586
Simon Dardis31636a12017-07-20 14:04:12 +00001587 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1588 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1589
1590 if (GPOpt)
1591 GPOpt->claim();
1592
David L. Jonesf561aba2017-03-08 01:02:16 +00001593 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1594 StringRef Val = StringRef(A->getValue());
1595 if (mips::hasCompactBranches(CPUName)) {
1596 if (Val == "never" || Val == "always" || Val == "optimal") {
1597 CmdArgs.push_back("-mllvm");
1598 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1599 } else
1600 D.Diag(diag::err_drv_unsupported_option_argument)
1601 << A->getOption().getName() << Val;
1602 } else
1603 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1604 }
1605}
1606
1607void Clang::AddPPCTargetArgs(const ArgList &Args,
1608 ArgStringList &CmdArgs) const {
1609 // Select the ABI to use.
1610 const char *ABIName = nullptr;
1611 if (getToolChain().getTriple().isOSLinux())
1612 switch (getToolChain().getArch()) {
1613 case llvm::Triple::ppc64: {
1614 // When targeting a processor that supports QPX, or if QPX is
1615 // specifically enabled, default to using the ABI that supports QPX (so
1616 // long as it is not specifically disabled).
1617 bool HasQPX = false;
1618 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1619 HasQPX = A->getValue() == StringRef("a2q");
1620 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1621 if (HasQPX) {
1622 ABIName = "elfv1-qpx";
1623 break;
1624 }
1625
1626 ABIName = "elfv1";
1627 break;
1628 }
1629 case llvm::Triple::ppc64le:
1630 ABIName = "elfv2";
1631 break;
1632 default:
1633 break;
1634 }
1635
1636 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1637 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1638 // the option if given as we don't have backend support for any targets
1639 // that don't use the altivec abi.
1640 if (StringRef(A->getValue()) != "altivec")
1641 ABIName = A->getValue();
1642
1643 ppc::FloatABI FloatABI =
1644 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1645
1646 if (FloatABI == ppc::FloatABI::Soft) {
1647 // Floating point operations and argument passing are soft.
1648 CmdArgs.push_back("-msoft-float");
1649 CmdArgs.push_back("-mfloat-abi");
1650 CmdArgs.push_back("soft");
1651 } else {
1652 // Floating point operations and argument passing are hard.
1653 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1654 CmdArgs.push_back("-mfloat-abi");
1655 CmdArgs.push_back("hard");
1656 }
1657
1658 if (ABIName) {
1659 CmdArgs.push_back("-target-abi");
1660 CmdArgs.push_back(ABIName);
1661 }
1662}
1663
Alex Bradbury71f45452018-01-11 13:36:56 +00001664void Clang::AddRISCVTargetArgs(const ArgList &Args,
1665 ArgStringList &CmdArgs) const {
1666 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001667 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001668 const char *ABIName = nullptr;
1669 const llvm::Triple &Triple = getToolChain().getTriple();
1670 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1671 ABIName = A->getValue();
1672 else if (Triple.getArch() == llvm::Triple::riscv32)
1673 ABIName = "ilp32";
1674 else if (Triple.getArch() == llvm::Triple::riscv64)
1675 ABIName = "lp64";
1676 else
1677 llvm_unreachable("Unexpected triple!");
1678
1679 CmdArgs.push_back("-target-abi");
1680 CmdArgs.push_back(ABIName);
1681}
1682
David L. Jonesf561aba2017-03-08 01:02:16 +00001683void Clang::AddSparcTargetArgs(const ArgList &Args,
1684 ArgStringList &CmdArgs) const {
1685 sparc::FloatABI FloatABI =
1686 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1687
1688 if (FloatABI == sparc::FloatABI::Soft) {
1689 // Floating point operations and argument passing are soft.
1690 CmdArgs.push_back("-msoft-float");
1691 CmdArgs.push_back("-mfloat-abi");
1692 CmdArgs.push_back("soft");
1693 } else {
1694 // Floating point operations and argument passing are hard.
1695 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1696 CmdArgs.push_back("-mfloat-abi");
1697 CmdArgs.push_back("hard");
1698 }
1699}
1700
1701void Clang::AddSystemZTargetArgs(const ArgList &Args,
1702 ArgStringList &CmdArgs) const {
1703 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1704 CmdArgs.push_back("-mbackchain");
1705}
1706
1707void Clang::AddX86TargetArgs(const ArgList &Args,
1708 ArgStringList &CmdArgs) const {
1709 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1710 Args.hasArg(options::OPT_mkernel) ||
1711 Args.hasArg(options::OPT_fapple_kext))
1712 CmdArgs.push_back("-disable-red-zone");
1713
1714 // Default to avoid implicit floating-point for kernel/kext code, but allow
1715 // that to be overridden with -mno-soft-float.
1716 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1717 Args.hasArg(options::OPT_fapple_kext));
1718 if (Arg *A = Args.getLastArg(
1719 options::OPT_msoft_float, options::OPT_mno_soft_float,
1720 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1721 const Option &O = A->getOption();
1722 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1723 O.matches(options::OPT_msoft_float));
1724 }
1725 if (NoImplicitFloat)
1726 CmdArgs.push_back("-no-implicit-float");
1727
1728 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1729 StringRef Value = A->getValue();
1730 if (Value == "intel" || Value == "att") {
1731 CmdArgs.push_back("-mllvm");
1732 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1733 } else {
1734 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1735 << A->getOption().getName() << Value;
1736 }
Nico Webere3712cf2018-01-17 13:34:20 +00001737 } else if (getToolChain().getDriver().IsCLMode()) {
1738 CmdArgs.push_back("-mllvm");
1739 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001740 }
1741
1742 // Set flags to support MCU ABI.
1743 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1744 CmdArgs.push_back("-mfloat-abi");
1745 CmdArgs.push_back("soft");
1746 CmdArgs.push_back("-mstack-alignment=4");
1747 }
1748}
1749
1750void Clang::AddHexagonTargetArgs(const ArgList &Args,
1751 ArgStringList &CmdArgs) const {
1752 CmdArgs.push_back("-mqdsp6-compat");
1753 CmdArgs.push_back("-Wreturn-type");
1754
1755 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001756 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001757 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1758 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001759 }
1760
1761 if (!Args.hasArg(options::OPT_fno_short_enums))
1762 CmdArgs.push_back("-fshort-enums");
1763 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1764 CmdArgs.push_back("-mllvm");
1765 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1766 }
1767 CmdArgs.push_back("-mllvm");
1768 CmdArgs.push_back("-machine-sink-split=0");
1769}
1770
1771void Clang::AddLanaiTargetArgs(const ArgList &Args,
1772 ArgStringList &CmdArgs) const {
1773 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1774 StringRef CPUName = A->getValue();
1775
1776 CmdArgs.push_back("-target-cpu");
1777 CmdArgs.push_back(Args.MakeArgString(CPUName));
1778 }
1779 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1780 StringRef Value = A->getValue();
1781 // Only support mregparm=4 to support old usage. Report error for all other
1782 // cases.
1783 int Mregparm;
1784 if (Value.getAsInteger(10, Mregparm)) {
1785 if (Mregparm != 4) {
1786 getToolChain().getDriver().Diag(
1787 diag::err_drv_unsupported_option_argument)
1788 << A->getOption().getName() << Value;
1789 }
1790 }
1791 }
1792}
1793
1794void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1795 ArgStringList &CmdArgs) const {
1796 // Default to "hidden" visibility.
1797 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1798 options::OPT_fvisibility_ms_compat)) {
1799 CmdArgs.push_back("-fvisibility");
1800 CmdArgs.push_back("hidden");
1801 }
1802}
1803
1804void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1805 StringRef Target, const InputInfo &Output,
1806 const InputInfo &Input, const ArgList &Args) const {
1807 // If this is a dry run, do not create the compilation database file.
1808 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1809 return;
1810
1811 using llvm::yaml::escape;
1812 const Driver &D = getToolChain().getDriver();
1813
1814 if (!CompilationDatabase) {
1815 std::error_code EC;
1816 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1817 if (EC) {
1818 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1819 << EC.message();
1820 return;
1821 }
1822 CompilationDatabase = std::move(File);
1823 }
1824 auto &CDB = *CompilationDatabase;
1825 SmallString<128> Buf;
1826 if (llvm::sys::fs::current_path(Buf))
1827 Buf = ".";
1828 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1829 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1830 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1831 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1832 Buf = "-x";
1833 Buf += types::getTypeName(Input.getType());
1834 CDB << ", \"" << escape(Buf) << "\"";
1835 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1836 Buf = "--sysroot=";
1837 Buf += D.SysRoot;
1838 CDB << ", \"" << escape(Buf) << "\"";
1839 }
1840 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1841 for (auto &A: Args) {
1842 auto &O = A->getOption();
1843 // Skip language selection, which is positional.
1844 if (O.getID() == options::OPT_x)
1845 continue;
1846 // Skip writing dependency output and the compilation database itself.
1847 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1848 continue;
1849 // Skip inputs.
1850 if (O.getKind() == Option::InputClass)
1851 continue;
1852 // All other arguments are quoted and appended.
1853 ArgStringList ASL;
1854 A->render(Args, ASL);
1855 for (auto &it: ASL)
1856 CDB << ", \"" << escape(it) << "\"";
1857 }
1858 Buf = "--target=";
1859 Buf += Target;
1860 CDB << ", \"" << escape(Buf) << "\"]},\n";
1861}
1862
1863static void CollectArgsForIntegratedAssembler(Compilation &C,
1864 const ArgList &Args,
1865 ArgStringList &CmdArgs,
1866 const Driver &D) {
1867 if (UseRelaxAll(C, Args))
1868 CmdArgs.push_back("-mrelax-all");
1869
1870 // Only default to -mincremental-linker-compatible if we think we are
1871 // targeting the MSVC linker.
1872 bool DefaultIncrementalLinkerCompatible =
1873 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1874 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1875 options::OPT_mno_incremental_linker_compatible,
1876 DefaultIncrementalLinkerCompatible))
1877 CmdArgs.push_back("-mincremental-linker-compatible");
1878
1879 switch (C.getDefaultToolChain().getArch()) {
1880 case llvm::Triple::arm:
1881 case llvm::Triple::armeb:
1882 case llvm::Triple::thumb:
1883 case llvm::Triple::thumbeb:
1884 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1885 StringRef Value = A->getValue();
1886 if (Value == "always" || Value == "never" || Value == "arm" ||
1887 Value == "thumb") {
1888 CmdArgs.push_back("-mllvm");
1889 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1890 } else {
1891 D.Diag(diag::err_drv_unsupported_option_argument)
1892 << A->getOption().getName() << Value;
1893 }
1894 }
1895 break;
1896 default:
1897 break;
1898 }
1899
1900 // When passing -I arguments to the assembler we sometimes need to
1901 // unconditionally take the next argument. For example, when parsing
1902 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1903 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1904 // arg after parsing the '-I' arg.
1905 bool TakeNextArg = false;
1906
Petr Hosek5668d832017-11-22 01:38:31 +00001907 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001908 const char *MipsTargetFeature = nullptr;
1909 for (const Arg *A :
1910 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1911 A->claim();
1912
1913 for (StringRef Value : A->getValues()) {
1914 if (TakeNextArg) {
1915 CmdArgs.push_back(Value.data());
1916 TakeNextArg = false;
1917 continue;
1918 }
1919
1920 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1921 Value == "-mbig-obj")
1922 continue; // LLVM handles bigobj automatically
1923
1924 switch (C.getDefaultToolChain().getArch()) {
1925 default:
1926 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001927 case llvm::Triple::thumb:
1928 case llvm::Triple::thumbeb:
1929 case llvm::Triple::arm:
1930 case llvm::Triple::armeb:
1931 if (Value == "-mthumb")
1932 // -mthumb has already been processed in ComputeLLVMTriple()
1933 // recognize but skip over here.
1934 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001935 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001936 case llvm::Triple::mips:
1937 case llvm::Triple::mipsel:
1938 case llvm::Triple::mips64:
1939 case llvm::Triple::mips64el:
1940 if (Value == "--trap") {
1941 CmdArgs.push_back("-target-feature");
1942 CmdArgs.push_back("+use-tcc-in-div");
1943 continue;
1944 }
1945 if (Value == "--break") {
1946 CmdArgs.push_back("-target-feature");
1947 CmdArgs.push_back("-use-tcc-in-div");
1948 continue;
1949 }
1950 if (Value.startswith("-msoft-float")) {
1951 CmdArgs.push_back("-target-feature");
1952 CmdArgs.push_back("+soft-float");
1953 continue;
1954 }
1955 if (Value.startswith("-mhard-float")) {
1956 CmdArgs.push_back("-target-feature");
1957 CmdArgs.push_back("-soft-float");
1958 continue;
1959 }
1960
1961 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1962 .Case("-mips1", "+mips1")
1963 .Case("-mips2", "+mips2")
1964 .Case("-mips3", "+mips3")
1965 .Case("-mips4", "+mips4")
1966 .Case("-mips5", "+mips5")
1967 .Case("-mips32", "+mips32")
1968 .Case("-mips32r2", "+mips32r2")
1969 .Case("-mips32r3", "+mips32r3")
1970 .Case("-mips32r5", "+mips32r5")
1971 .Case("-mips32r6", "+mips32r6")
1972 .Case("-mips64", "+mips64")
1973 .Case("-mips64r2", "+mips64r2")
1974 .Case("-mips64r3", "+mips64r3")
1975 .Case("-mips64r5", "+mips64r5")
1976 .Case("-mips64r6", "+mips64r6")
1977 .Default(nullptr);
1978 if (MipsTargetFeature)
1979 continue;
1980 }
1981
1982 if (Value == "-force_cpusubtype_ALL") {
1983 // Do nothing, this is the default and we don't support anything else.
1984 } else if (Value == "-L") {
1985 CmdArgs.push_back("-msave-temp-labels");
1986 } else if (Value == "--fatal-warnings") {
1987 CmdArgs.push_back("-massembler-fatal-warnings");
1988 } else if (Value == "--noexecstack") {
1989 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001990 } else if (Value.startswith("-compress-debug-sections") ||
1991 Value.startswith("--compress-debug-sections") ||
1992 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00001993 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001994 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00001995 } else if (Value == "-mrelax-relocations=yes" ||
1996 Value == "--mrelax-relocations=yes") {
1997 UseRelaxRelocations = true;
1998 } else if (Value == "-mrelax-relocations=no" ||
1999 Value == "--mrelax-relocations=no") {
2000 UseRelaxRelocations = false;
2001 } else if (Value.startswith("-I")) {
2002 CmdArgs.push_back(Value.data());
2003 // We need to consume the next argument if the current arg is a plain
2004 // -I. The next arg will be the include directory.
2005 if (Value == "-I")
2006 TakeNextArg = true;
2007 } else if (Value.startswith("-gdwarf-")) {
2008 // "-gdwarf-N" options are not cc1as options.
2009 unsigned DwarfVersion = DwarfVersionNum(Value);
2010 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2011 CmdArgs.push_back(Value.data());
2012 } else {
2013 RenderDebugEnablingArgs(Args, CmdArgs,
2014 codegenoptions::LimitedDebugInfo,
2015 DwarfVersion, llvm::DebuggerKind::Default);
2016 }
2017 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2018 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2019 // Do nothing, we'll validate it later.
2020 } else if (Value == "-defsym") {
2021 if (A->getNumValues() != 2) {
2022 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2023 break;
2024 }
2025 const char *S = A->getValue(1);
2026 auto Pair = StringRef(S).split('=');
2027 auto Sym = Pair.first;
2028 auto SVal = Pair.second;
2029
2030 if (Sym.empty() || SVal.empty()) {
2031 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2032 break;
2033 }
2034 int64_t IVal;
2035 if (SVal.getAsInteger(0, IVal)) {
2036 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2037 break;
2038 }
2039 CmdArgs.push_back(Value.data());
2040 TakeNextArg = true;
2041 } else {
2042 D.Diag(diag::err_drv_unsupported_option_argument)
2043 << A->getOption().getName() << Value;
2044 }
2045 }
2046 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002047 if (UseRelaxRelocations)
2048 CmdArgs.push_back("--mrelax-relocations");
2049 if (MipsTargetFeature != nullptr) {
2050 CmdArgs.push_back("-target-feature");
2051 CmdArgs.push_back(MipsTargetFeature);
2052 }
2053}
2054
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002055static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2056 bool OFastEnabled, const ArgList &Args,
2057 ArgStringList &CmdArgs) {
2058 // Handle various floating point optimization flags, mapping them to the
2059 // appropriate LLVM code generation flags. This is complicated by several
2060 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002061 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002062 // LLVM flags based on the final state.
2063 bool HonorINFs = true;
2064 bool HonorNaNs = true;
2065 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2066 bool MathErrno = TC.IsMathErrnoDefault();
2067 bool AssociativeMath = false;
2068 bool ReciprocalMath = false;
2069 bool SignedZeros = true;
2070 bool TrappingMath = true;
2071 StringRef DenormalFPMath = "";
2072 StringRef FPContract = "";
2073
2074 for (const Arg *A : Args) {
2075 switch (A->getOption().getID()) {
2076 // If this isn't an FP option skip the claim below
2077 default: continue;
2078
2079 // Options controlling individual features
2080 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2081 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2082 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2083 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2084 case options::OPT_fmath_errno: MathErrno = true; break;
2085 case options::OPT_fno_math_errno: MathErrno = false; break;
2086 case options::OPT_fassociative_math: AssociativeMath = true; break;
2087 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2088 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2089 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2090 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2091 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2092 case options::OPT_ftrapping_math: TrappingMath = true; break;
2093 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2094
2095 case options::OPT_fdenormal_fp_math_EQ:
2096 DenormalFPMath = A->getValue();
2097 break;
2098
2099 // Validate and pass through -fp-contract option.
2100 case options::OPT_ffp_contract: {
2101 StringRef Val = A->getValue();
2102 if (Val == "fast" || Val == "on" || Val == "off")
2103 FPContract = Val;
2104 else
2105 D.Diag(diag::err_drv_unsupported_option_argument)
2106 << A->getOption().getName() << Val;
2107 break;
2108 }
2109
2110 case options::OPT_ffinite_math_only:
2111 HonorINFs = false;
2112 HonorNaNs = false;
2113 break;
2114 case options::OPT_fno_finite_math_only:
2115 HonorINFs = true;
2116 HonorNaNs = true;
2117 break;
2118
2119 case options::OPT_funsafe_math_optimizations:
2120 AssociativeMath = true;
2121 ReciprocalMath = true;
2122 SignedZeros = false;
2123 TrappingMath = false;
2124 break;
2125 case options::OPT_fno_unsafe_math_optimizations:
2126 AssociativeMath = false;
2127 ReciprocalMath = false;
2128 SignedZeros = true;
2129 TrappingMath = true;
2130 // -fno_unsafe_math_optimizations restores default denormal handling
2131 DenormalFPMath = "";
2132 break;
2133
2134 case options::OPT_Ofast:
2135 // If -Ofast is the optimization level, then -ffast-math should be enabled
2136 if (!OFastEnabled)
2137 continue;
2138 LLVM_FALLTHROUGH;
2139 case options::OPT_ffast_math:
2140 HonorINFs = false;
2141 HonorNaNs = false;
2142 MathErrno = false;
2143 AssociativeMath = true;
2144 ReciprocalMath = true;
2145 SignedZeros = false;
2146 TrappingMath = false;
2147 // If fast-math is set then set the fp-contract mode to fast.
2148 FPContract = "fast";
2149 break;
2150 case options::OPT_fno_fast_math:
2151 HonorINFs = true;
2152 HonorNaNs = true;
2153 // Turning on -ffast-math (with either flag) removes the need for
2154 // MathErrno. However, turning *off* -ffast-math merely restores the
2155 // toolchain default (which may be false).
2156 MathErrno = TC.IsMathErrnoDefault();
2157 AssociativeMath = false;
2158 ReciprocalMath = false;
2159 SignedZeros = true;
2160 TrappingMath = true;
2161 // -fno_fast_math restores default denormal and fpcontract handling
2162 DenormalFPMath = "";
2163 FPContract = "";
2164 break;
2165 }
2166
2167 // If we handled this option claim it
2168 A->claim();
2169 }
2170
2171 if (!HonorINFs)
2172 CmdArgs.push_back("-menable-no-infs");
2173
2174 if (!HonorNaNs)
2175 CmdArgs.push_back("-menable-no-nans");
2176
2177 if (MathErrno)
2178 CmdArgs.push_back("-fmath-errno");
2179
2180 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2181 !TrappingMath)
2182 CmdArgs.push_back("-menable-unsafe-fp-math");
2183
2184 if (!SignedZeros)
2185 CmdArgs.push_back("-fno-signed-zeros");
2186
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002187 if (AssociativeMath && !SignedZeros && !TrappingMath)
2188 CmdArgs.push_back("-mreassociate");
2189
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002190 if (ReciprocalMath)
2191 CmdArgs.push_back("-freciprocal-math");
2192
2193 if (!TrappingMath)
2194 CmdArgs.push_back("-fno-trapping-math");
2195
2196 if (!DenormalFPMath.empty())
2197 CmdArgs.push_back(
2198 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2199
2200 if (!FPContract.empty())
2201 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2202
2203 ParseMRecip(D, Args, CmdArgs);
2204
2205 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2206 // individual features enabled by -ffast-math instead of the option itself as
2207 // that's consistent with gcc's behaviour.
2208 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2209 ReciprocalMath && !SignedZeros && !TrappingMath)
2210 CmdArgs.push_back("-ffast-math");
2211
2212 // Handle __FINITE_MATH_ONLY__ similarly.
2213 if (!HonorINFs && !HonorNaNs)
2214 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002215
2216 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2217 CmdArgs.push_back("-mfpmath");
2218 CmdArgs.push_back(A->getValue());
2219 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002220
2221 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002222 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2223 options::OPT_fstrict_float_cast_overflow, false))
2224 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002225}
2226
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002227static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2228 const llvm::Triple &Triple,
2229 const InputInfo &Input) {
2230 // Enable region store model by default.
2231 CmdArgs.push_back("-analyzer-store=region");
2232
2233 // Treat blocks as analysis entry points.
2234 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2235
2236 CmdArgs.push_back("-analyzer-eagerly-assume");
2237
2238 // Add default argument set.
2239 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2240 CmdArgs.push_back("-analyzer-checker=core");
2241 CmdArgs.push_back("-analyzer-checker=apiModeling");
2242
2243 if (!Triple.isWindowsMSVCEnvironment()) {
2244 CmdArgs.push_back("-analyzer-checker=unix");
2245 } else {
2246 // Enable "unix" checkers that also work on Windows.
2247 CmdArgs.push_back("-analyzer-checker=unix.API");
2248 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2249 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2250 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2251 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2252 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2253 }
2254
2255 // Disable some unix checkers for PS4.
2256 if (Triple.isPS4CPU()) {
2257 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2258 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2259 }
2260
2261 if (Triple.isOSDarwin())
2262 CmdArgs.push_back("-analyzer-checker=osx");
2263
2264 CmdArgs.push_back("-analyzer-checker=deadcode");
2265
2266 if (types::isCXX(Input.getType()))
2267 CmdArgs.push_back("-analyzer-checker=cplusplus");
2268
2269 if (!Triple.isPS4CPU()) {
2270 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2271 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2272 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2273 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2274 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2275 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2276 }
2277
2278 // Default nullability checks.
2279 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2280 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2281 }
2282
2283 // Set the output format. The default is plist, for (lame) historical reasons.
2284 CmdArgs.push_back("-analyzer-output");
2285 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2286 CmdArgs.push_back(A->getValue());
2287 else
2288 CmdArgs.push_back("plist");
2289
2290 // Disable the presentation of standard compiler warnings when using
2291 // --analyze. We only want to show static analyzer diagnostics or frontend
2292 // errors.
2293 CmdArgs.push_back("-w");
2294
2295 // Add -Xanalyzer arguments when running as analyzer.
2296 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2297}
2298
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002299static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002300 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002301 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2302
2303 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2304 // doesn't even have a stack!
2305 if (EffectiveTriple.isNVPTX())
2306 return;
2307
2308 // -stack-protector=0 is default.
2309 unsigned StackProtectorLevel = 0;
2310 unsigned DefaultStackProtectorLevel =
2311 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2312
2313 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2314 options::OPT_fstack_protector_all,
2315 options::OPT_fstack_protector_strong,
2316 options::OPT_fstack_protector)) {
2317 if (A->getOption().matches(options::OPT_fstack_protector))
2318 StackProtectorLevel =
2319 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2320 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2321 StackProtectorLevel = LangOptions::SSPStrong;
2322 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2323 StackProtectorLevel = LangOptions::SSPReq;
2324 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002325 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002326 }
2327
2328 if (StackProtectorLevel) {
2329 CmdArgs.push_back("-stack-protector");
2330 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2331 }
2332
2333 // --param ssp-buffer-size=
2334 for (const Arg *A : Args.filtered(options::OPT__param)) {
2335 StringRef Str(A->getValue());
2336 if (Str.startswith("ssp-buffer-size=")) {
2337 if (StackProtectorLevel) {
2338 CmdArgs.push_back("-stack-protector-buffer-size");
2339 // FIXME: Verify the argument is a valid integer.
2340 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2341 }
2342 A->claim();
2343 }
2344 }
2345}
2346
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002347static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2348 const unsigned ForwardedArguments[] = {
2349 options::OPT_cl_opt_disable,
2350 options::OPT_cl_strict_aliasing,
2351 options::OPT_cl_single_precision_constant,
2352 options::OPT_cl_finite_math_only,
2353 options::OPT_cl_kernel_arg_info,
2354 options::OPT_cl_unsafe_math_optimizations,
2355 options::OPT_cl_fast_relaxed_math,
2356 options::OPT_cl_mad_enable,
2357 options::OPT_cl_no_signed_zeros,
2358 options::OPT_cl_denorms_are_zero,
2359 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002360 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002361 };
2362
2363 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2364 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2365 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2366 }
2367
2368 for (const auto &Arg : ForwardedArguments)
2369 if (const auto *A = Args.getLastArg(Arg))
2370 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2371}
2372
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002373static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2374 ArgStringList &CmdArgs) {
2375 bool ARCMTEnabled = false;
2376 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2377 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2378 options::OPT_ccc_arcmt_modify,
2379 options::OPT_ccc_arcmt_migrate)) {
2380 ARCMTEnabled = true;
2381 switch (A->getOption().getID()) {
2382 default: llvm_unreachable("missed a case");
2383 case options::OPT_ccc_arcmt_check:
2384 CmdArgs.push_back("-arcmt-check");
2385 break;
2386 case options::OPT_ccc_arcmt_modify:
2387 CmdArgs.push_back("-arcmt-modify");
2388 break;
2389 case options::OPT_ccc_arcmt_migrate:
2390 CmdArgs.push_back("-arcmt-migrate");
2391 CmdArgs.push_back("-mt-migrate-directory");
2392 CmdArgs.push_back(A->getValue());
2393
2394 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2395 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2396 break;
2397 }
2398 }
2399 } else {
2400 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2401 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2402 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2403 }
2404
2405 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2406 if (ARCMTEnabled)
2407 D.Diag(diag::err_drv_argument_not_allowed_with)
2408 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2409
2410 CmdArgs.push_back("-mt-migrate-directory");
2411 CmdArgs.push_back(A->getValue());
2412
2413 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2414 options::OPT_objcmt_migrate_subscripting,
2415 options::OPT_objcmt_migrate_property)) {
2416 // None specified, means enable them all.
2417 CmdArgs.push_back("-objcmt-migrate-literals");
2418 CmdArgs.push_back("-objcmt-migrate-subscripting");
2419 CmdArgs.push_back("-objcmt-migrate-property");
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 }
2425 } else {
2426 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2427 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2428 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2429 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2430 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2431 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2432 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2433 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2434 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2435 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2436 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2437 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2438 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2439 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2440 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2441 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2442 }
2443}
2444
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002445static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2446 const ArgList &Args, ArgStringList &CmdArgs) {
2447 // -fbuiltin is default unless -mkernel is used.
2448 bool UseBuiltins =
2449 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2450 !Args.hasArg(options::OPT_mkernel));
2451 if (!UseBuiltins)
2452 CmdArgs.push_back("-fno-builtin");
2453
2454 // -ffreestanding implies -fno-builtin.
2455 if (Args.hasArg(options::OPT_ffreestanding))
2456 UseBuiltins = false;
2457
2458 // Process the -fno-builtin-* options.
2459 for (const auto &Arg : Args) {
2460 const Option &O = Arg->getOption();
2461 if (!O.matches(options::OPT_fno_builtin_))
2462 continue;
2463
2464 Arg->claim();
2465
2466 // If -fno-builtin is specified, then there's no need to pass the option to
2467 // the frontend.
2468 if (!UseBuiltins)
2469 continue;
2470
2471 StringRef FuncName = Arg->getValue();
2472 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2473 }
2474
2475 // le32-specific flags:
2476 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2477 // by default.
2478 if (TC.getArch() == llvm::Triple::le32)
2479 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002480}
2481
Adrian Prantl70599032018-02-09 18:43:10 +00002482void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2483 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2484 llvm::sys::path::append(Result, "org.llvm.clang.");
2485 appendUserToPath(Result);
2486 llvm::sys::path::append(Result, "ModuleCache");
2487}
2488
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002489static void RenderModulesOptions(Compilation &C, const Driver &D,
2490 const ArgList &Args, const InputInfo &Input,
2491 const InputInfo &Output,
2492 ArgStringList &CmdArgs, bool &HaveModules) {
2493 // -fmodules enables the use of precompiled modules (off by default).
2494 // Users can pass -fno-cxx-modules to turn off modules support for
2495 // C++/Objective-C++ programs.
2496 bool HaveClangModules = false;
2497 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2498 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2499 options::OPT_fno_cxx_modules, true);
2500 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2501 CmdArgs.push_back("-fmodules");
2502 HaveClangModules = true;
2503 }
2504 }
2505
2506 HaveModules = HaveClangModules;
2507 if (Args.hasArg(options::OPT_fmodules_ts)) {
2508 CmdArgs.push_back("-fmodules-ts");
2509 HaveModules = true;
2510 }
2511
2512 // -fmodule-maps enables implicit reading of module map files. By default,
2513 // this is enabled if we are using Clang's flavor of precompiled modules.
2514 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2515 options::OPT_fno_implicit_module_maps, HaveClangModules))
2516 CmdArgs.push_back("-fimplicit-module-maps");
2517
2518 // -fmodules-decluse checks that modules used are declared so (off by default)
2519 if (Args.hasFlag(options::OPT_fmodules_decluse,
2520 options::OPT_fno_modules_decluse, false))
2521 CmdArgs.push_back("-fmodules-decluse");
2522
2523 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2524 // all #included headers are part of modules.
2525 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2526 options::OPT_fno_modules_strict_decluse, false))
2527 CmdArgs.push_back("-fmodules-strict-decluse");
2528
2529 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002530 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002531 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2532 options::OPT_fno_implicit_modules, HaveClangModules)) {
2533 if (HaveModules)
2534 CmdArgs.push_back("-fno-implicit-modules");
2535 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002536 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002537 // -fmodule-cache-path specifies where our implicitly-built module files
2538 // should be written.
2539 SmallString<128> Path;
2540 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2541 Path = A->getValue();
2542
2543 if (C.isForDiagnostics()) {
2544 // When generating crash reports, we want to emit the modules along with
2545 // the reproduction sources, so we ignore any provided module path.
2546 Path = Output.getFilename();
2547 llvm::sys::path::replace_extension(Path, ".cache");
2548 llvm::sys::path::append(Path, "modules");
2549 } else if (Path.empty()) {
2550 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002551 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002552 }
2553
2554 const char Arg[] = "-fmodules-cache-path=";
2555 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2556 CmdArgs.push_back(Args.MakeArgString(Path));
2557 }
2558
2559 if (HaveModules) {
2560 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2561 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2562 CmdArgs.push_back(Args.MakeArgString(
2563 std::string("-fprebuilt-module-path=") + A->getValue()));
2564 A->claim();
2565 }
2566 }
2567
2568 // -fmodule-name specifies the module that is currently being built (or
2569 // used for header checking by -fmodule-maps).
2570 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2571
2572 // -fmodule-map-file can be used to specify files containing module
2573 // definitions.
2574 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2575
2576 // -fbuiltin-module-map can be used to load the clang
2577 // builtin headers modulemap file.
2578 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2579 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2580 llvm::sys::path::append(BuiltinModuleMap, "include");
2581 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2582 if (llvm::sys::fs::exists(BuiltinModuleMap))
2583 CmdArgs.push_back(
2584 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2585 }
2586
2587 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2588 // names to precompiled module files (the module is loaded only if used).
2589 // The -fmodule-file=<file> form can be used to unconditionally load
2590 // precompiled module files (whether used or not).
2591 if (HaveModules)
2592 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2593 else
2594 Args.ClaimAllArgs(options::OPT_fmodule_file);
2595
2596 // When building modules and generating crashdumps, we need to dump a module
2597 // dependency VFS alongside the output.
2598 if (HaveClangModules && C.isForDiagnostics()) {
2599 SmallString<128> VFSDir(Output.getFilename());
2600 llvm::sys::path::replace_extension(VFSDir, ".cache");
2601 // Add the cache directory as a temp so the crash diagnostics pick it up.
2602 C.addTempFile(Args.MakeArgString(VFSDir));
2603
2604 llvm::sys::path::append(VFSDir, "vfs");
2605 CmdArgs.push_back("-module-dependency-dir");
2606 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2607 }
2608
2609 if (HaveClangModules)
2610 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2611
2612 // Pass through all -fmodules-ignore-macro arguments.
2613 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2614 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2615 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2616
2617 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2618
2619 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2620 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2621 D.Diag(diag::err_drv_argument_not_allowed_with)
2622 << A->getAsString(Args) << "-fbuild-session-timestamp";
2623
2624 llvm::sys::fs::file_status Status;
2625 if (llvm::sys::fs::status(A->getValue(), Status))
2626 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2627 CmdArgs.push_back(
2628 Args.MakeArgString("-fbuild-session-timestamp=" +
2629 Twine((uint64_t)Status.getLastModificationTime()
2630 .time_since_epoch()
2631 .count())));
2632 }
2633
2634 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2635 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2636 options::OPT_fbuild_session_file))
2637 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2638
2639 Args.AddLastArg(CmdArgs,
2640 options::OPT_fmodules_validate_once_per_build_session);
2641 }
2642
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002643 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2644 options::OPT_fno_modules_validate_system_headers,
2645 ImplicitModules))
2646 CmdArgs.push_back("-fmodules-validate-system-headers");
2647
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002648 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2649}
2650
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002651static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2652 ArgStringList &CmdArgs) {
2653 // -fsigned-char is default.
2654 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2655 options::OPT_fno_signed_char,
2656 options::OPT_funsigned_char,
2657 options::OPT_fno_unsigned_char)) {
2658 if (A->getOption().matches(options::OPT_funsigned_char) ||
2659 A->getOption().matches(options::OPT_fno_signed_char)) {
2660 CmdArgs.push_back("-fno-signed-char");
2661 }
2662 } else if (!isSignedCharDefault(T)) {
2663 CmdArgs.push_back("-fno-signed-char");
2664 }
2665
Richard Smith3a8244d2018-05-01 05:02:45 +00002666 if (Args.hasFlag(options::OPT_fchar8__t, options::OPT_fno_char8__t, false))
2667 CmdArgs.push_back("-fchar8_t");
2668
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002669 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2670 options::OPT_fno_short_wchar)) {
2671 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2672 CmdArgs.push_back("-fwchar-type=short");
2673 CmdArgs.push_back("-fno-signed-wchar");
2674 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002675 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002676 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002677 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2678 T.getOS() == llvm::Triple::OpenBSD))
2679 CmdArgs.push_back("-fno-signed-wchar");
2680 else
2681 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002682 }
2683 }
2684}
2685
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002686static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2687 const llvm::Triple &T, const ArgList &Args,
2688 ObjCRuntime &Runtime, bool InferCovariantReturns,
2689 const InputInfo &Input, ArgStringList &CmdArgs) {
2690 const llvm::Triple::ArchType Arch = TC.getArch();
2691
2692 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2693 // is the default. Except for deployment target of 10.5, next runtime is
2694 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2695 if (Runtime.isNonFragile()) {
2696 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2697 options::OPT_fno_objc_legacy_dispatch,
2698 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2699 if (TC.UseObjCMixedDispatch())
2700 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2701 else
2702 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2703 }
2704 }
2705
2706 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2707 // to do Array/Dictionary subscripting by default.
2708 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2709 !T.isMacOSXVersionLT(10, 7) &&
2710 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2711 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2712
2713 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2714 // NOTE: This logic is duplicated in ToolChains.cpp.
2715 if (isObjCAutoRefCount(Args)) {
2716 TC.CheckObjCARC();
2717
2718 CmdArgs.push_back("-fobjc-arc");
2719
2720 // FIXME: It seems like this entire block, and several around it should be
2721 // wrapped in isObjC, but for now we just use it here as this is where it
2722 // was being used previously.
2723 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2724 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2725 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2726 else
2727 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2728 }
2729
2730 // Allow the user to enable full exceptions code emission.
2731 // We default off for Objective-C, on for Objective-C++.
2732 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2733 options::OPT_fno_objc_arc_exceptions,
2734 /*default=*/types::isCXX(Input.getType())))
2735 CmdArgs.push_back("-fobjc-arc-exceptions");
2736 }
2737
2738 // Silence warning for full exception code emission options when explicitly
2739 // set to use no ARC.
2740 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2741 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2742 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2743 }
2744
2745 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2746 // rewriter.
2747 if (InferCovariantReturns)
2748 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2749
2750 // Pass down -fobjc-weak or -fno-objc-weak if present.
2751 if (types::isObjC(Input.getType())) {
2752 auto WeakArg =
2753 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2754 if (!WeakArg) {
2755 // nothing to do
2756 } else if (!Runtime.allowsWeak()) {
2757 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2758 D.Diag(diag::err_objc_weak_unsupported);
2759 } else {
2760 WeakArg->render(Args, CmdArgs);
2761 }
2762 }
2763}
2764
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002765static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2766 ArgStringList &CmdArgs) {
2767 bool CaretDefault = true;
2768 bool ColumnDefault = true;
2769
2770 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2771 options::OPT__SLASH_diagnostics_column,
2772 options::OPT__SLASH_diagnostics_caret)) {
2773 switch (A->getOption().getID()) {
2774 case options::OPT__SLASH_diagnostics_caret:
2775 CaretDefault = true;
2776 ColumnDefault = true;
2777 break;
2778 case options::OPT__SLASH_diagnostics_column:
2779 CaretDefault = false;
2780 ColumnDefault = true;
2781 break;
2782 case options::OPT__SLASH_diagnostics_classic:
2783 CaretDefault = false;
2784 ColumnDefault = false;
2785 break;
2786 }
2787 }
2788
2789 // -fcaret-diagnostics is default.
2790 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2791 options::OPT_fno_caret_diagnostics, CaretDefault))
2792 CmdArgs.push_back("-fno-caret-diagnostics");
2793
2794 // -fdiagnostics-fixit-info is default, only pass non-default.
2795 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2796 options::OPT_fno_diagnostics_fixit_info))
2797 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2798
2799 // Enable -fdiagnostics-show-option by default.
2800 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2801 options::OPT_fno_diagnostics_show_option))
2802 CmdArgs.push_back("-fdiagnostics-show-option");
2803
2804 if (const Arg *A =
2805 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2806 CmdArgs.push_back("-fdiagnostics-show-category");
2807 CmdArgs.push_back(A->getValue());
2808 }
2809
2810 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2811 options::OPT_fno_diagnostics_show_hotness, false))
2812 CmdArgs.push_back("-fdiagnostics-show-hotness");
2813
2814 if (const Arg *A =
2815 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2816 std::string Opt =
2817 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2818 CmdArgs.push_back(Args.MakeArgString(Opt));
2819 }
2820
2821 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2822 CmdArgs.push_back("-fdiagnostics-format");
2823 CmdArgs.push_back(A->getValue());
2824 }
2825
2826 if (const Arg *A = Args.getLastArg(
2827 options::OPT_fdiagnostics_show_note_include_stack,
2828 options::OPT_fno_diagnostics_show_note_include_stack)) {
2829 const Option &O = A->getOption();
2830 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2831 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2832 else
2833 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2834 }
2835
2836 // Color diagnostics are parsed by the driver directly from argv and later
2837 // re-parsed to construct this job; claim any possible color diagnostic here
2838 // to avoid warn_drv_unused_argument and diagnose bad
2839 // OPT_fdiagnostics_color_EQ values.
2840 for (const Arg *A : Args) {
2841 const Option &O = A->getOption();
2842 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2843 !O.matches(options::OPT_fdiagnostics_color) &&
2844 !O.matches(options::OPT_fno_color_diagnostics) &&
2845 !O.matches(options::OPT_fno_diagnostics_color) &&
2846 !O.matches(options::OPT_fdiagnostics_color_EQ))
2847 continue;
2848
2849 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2850 StringRef Value(A->getValue());
2851 if (Value != "always" && Value != "never" && Value != "auto")
2852 D.Diag(diag::err_drv_clang_unsupported)
2853 << ("-fdiagnostics-color=" + Value).str();
2854 }
2855 A->claim();
2856 }
2857
2858 if (D.getDiags().getDiagnosticOptions().ShowColors)
2859 CmdArgs.push_back("-fcolor-diagnostics");
2860
2861 if (Args.hasArg(options::OPT_fansi_escape_codes))
2862 CmdArgs.push_back("-fansi-escape-codes");
2863
2864 if (!Args.hasFlag(options::OPT_fshow_source_location,
2865 options::OPT_fno_show_source_location))
2866 CmdArgs.push_back("-fno-show-source-location");
2867
2868 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2869 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2870
2871 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2872 ColumnDefault))
2873 CmdArgs.push_back("-fno-show-column");
2874
2875 if (!Args.hasFlag(options::OPT_fspell_checking,
2876 options::OPT_fno_spell_checking))
2877 CmdArgs.push_back("-fno-spell-checking");
2878}
2879
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002880static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2881 const llvm::Triple &T, const ArgList &Args,
2882 bool EmitCodeView, bool IsWindowsMSVC,
2883 ArgStringList &CmdArgs,
2884 codegenoptions::DebugInfoKind &DebugInfoKind,
2885 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002886 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002887 options::OPT_fno_debug_info_for_profiling, false) &&
2888 checkDebugInfoOption(
2889 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002890 CmdArgs.push_back("-fdebug-info-for-profiling");
2891
2892 // The 'g' groups options involve a somewhat intricate sequence of decisions
2893 // about what to pass from the driver to the frontend, but by the time they
2894 // reach cc1 they've been factored into three well-defined orthogonal choices:
2895 // * what level of debug info to generate
2896 // * what dwarf version to write
2897 // * what debugger tuning to use
2898 // This avoids having to monkey around further in cc1 other than to disable
2899 // codeview if not running in a Windows environment. Perhaps even that
2900 // decision should be made in the driver as well though.
2901 unsigned DWARFVersion = 0;
2902 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2903
2904 bool SplitDWARFInlining =
2905 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2906 options::OPT_fno_split_dwarf_inlining, true);
2907
2908 Args.ClaimAllArgs(options::OPT_g_Group);
2909
2910 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2911
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002912 if (SplitDWARFArg && !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
2913 SplitDWARFArg = nullptr;
2914 SplitDWARFInlining = false;
2915 }
2916
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002917 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002918 if (checkDebugInfoOption(A, Args, D, TC)) {
2919 // If the last option explicitly specified a debug-info level, use it.
2920 if (A->getOption().matches(options::OPT_gN_Group)) {
2921 DebugInfoKind = DebugLevelToInfoKind(*A);
2922 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2923 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2924 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2925 // This gets a bit more complicated if you've disabled inline info in
2926 // the skeleton CUs (SplitDWARFInlining) - then there's value in
2927 // composing split-dwarf and line-tables-only, so let those compose
2928 // naturally in that case. And if you just turned off debug info,
2929 // (-gsplit-dwarf -g0) - do that.
2930 if (SplitDWARFArg) {
2931 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2932 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2933 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2934 SplitDWARFInlining))
2935 SplitDWARFArg = nullptr;
2936 } else if (SplitDWARFInlining)
2937 DebugInfoKind = codegenoptions::NoDebugInfo;
2938 }
2939 } else {
2940 // For any other 'g' option, use Limited.
2941 DebugInfoKind = codegenoptions::LimitedDebugInfo;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002942 }
2943 } else {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002944 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2945 }
2946 }
2947
2948 // If a debugger tuning argument appeared, remember it.
2949 if (const Arg *A =
2950 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002951 if (checkDebugInfoOption(A, Args, D, TC)) {
2952 if (A->getOption().matches(options::OPT_glldb))
2953 DebuggerTuning = llvm::DebuggerKind::LLDB;
2954 else if (A->getOption().matches(options::OPT_gsce))
2955 DebuggerTuning = llvm::DebuggerKind::SCE;
2956 else
2957 DebuggerTuning = llvm::DebuggerKind::GDB;
2958 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002959 }
2960
2961 // If a -gdwarf argument appeared, remember it.
2962 if (const Arg *A =
2963 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2964 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002965 if (checkDebugInfoOption(A, Args, D, TC))
2966 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002967
2968 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2969 // argument parsing.
Reid Kleckner54af3e72018-02-26 22:55:33 +00002970 if (EmitCodeView) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002971 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
2972 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
2973 if (EmitCodeView) {
2974 // DWARFVersion remains at 0 if no explicit choice was made.
2975 CmdArgs.push_back("-gcodeview");
2976 }
2977 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002978 }
2979
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002980 if (!EmitCodeView && DWARFVersion == 0 &&
2981 DebugInfoKind != codegenoptions::NoDebugInfo)
2982 DWARFVersion = TC.GetDefaultDwarfVersion();
2983
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002984 // We ignore flag -gstrict-dwarf for now.
2985 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2986 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2987
Alexey Bataevb83b4e42018-07-27 19:45:14 +00002988 // Column info is included by default for everything except SCE and
2989 // CodeView. Clang doesn't track end columns, just starting columns, which,
2990 // in theory, is fine for CodeView (and PDB). In practice, however, the
2991 // Microsoft debuggers don't handle missing end columns well, so it's better
2992 // not to include any column info.
2993 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
2994 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002995 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00002996 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00002997 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002998 CmdArgs.push_back("-dwarf-column-info");
2999
3000 // FIXME: Move backend command line options to the module.
3001 // If -gline-tables-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003002 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3003 if (checkDebugInfoOption(A, Args, D, TC)) {
3004 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly) {
3005 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3006 CmdArgs.push_back("-dwarf-ext-refs");
3007 CmdArgs.push_back("-fmodule-format=obj");
3008 }
3009 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003010
3011 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3012 // splitting and extraction.
3013 // FIXME: Currently only works on Linux.
3014 if (T.isOSLinux()) {
3015 if (!SplitDWARFInlining)
3016 CmdArgs.push_back("-fno-split-dwarf-inlining");
3017
3018 if (SplitDWARFArg) {
3019 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3020 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3021 CmdArgs.push_back("-enable-split-dwarf");
3022 }
3023 }
3024
3025 // After we've dealt with all combinations of things that could
3026 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3027 // figure out if we need to "upgrade" it to standalone debug info.
3028 // We parse these two '-f' options whether or not they will be used,
3029 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3030 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3031 options::OPT_fno_standalone_debug,
3032 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003033 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3034 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003035 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3036 DebugInfoKind = codegenoptions::FullDebugInfo;
3037
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003038 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3039 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003040 // Source embedding is a vendor extension to DWARF v5. By now we have
3041 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003042 // fallen back to the target default, so if this is still not at least 5
3043 // we emit an error.
3044 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003045 if (DWARFVersion < 5)
3046 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003047 << A->getAsString(Args) << "-gdwarf-5";
3048 else if (checkDebugInfoOption(A, Args, D, TC))
3049 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003050 }
3051
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003052 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3053 DebuggerTuning);
3054
3055 // -fdebug-macro turns on macro debug info generation.
3056 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3057 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003058 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3059 D, TC))
3060 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003061
3062 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003063 const auto *PubnamesArg =
3064 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3065 options::OPT_gpubnames, options::OPT_gno_pubnames);
3066 if (SplitDWARFArg ||
3067 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3068 if (!PubnamesArg ||
3069 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3070 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3071 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3072 options::OPT_gpubnames)
3073 ? "-gpubnames"
3074 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003075
3076 // -gdwarf-aranges turns on the emission of the aranges section in the
3077 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003078 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003079 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3080 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3081 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3082 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003083 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003084 CmdArgs.push_back("-generate-arange-section");
3085 }
3086
3087 if (Args.hasFlag(options::OPT_fdebug_types_section,
3088 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003089 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003090 D.Diag(diag::err_drv_unsupported_opt_for_target)
3091 << Args.getLastArg(options::OPT_fdebug_types_section)
3092 ->getAsString(Args)
3093 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003094 } else if (checkDebugInfoOption(
3095 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3096 TC)) {
3097 CmdArgs.push_back("-mllvm");
3098 CmdArgs.push_back("-generate-type-units");
3099 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003100 }
3101
Paul Robinson1787f812017-09-28 18:37:02 +00003102 // Decide how to render forward declarations of template instantiations.
3103 // SCE wants full descriptions, others just get them in the name.
3104 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3105 CmdArgs.push_back("-debug-forward-template-params");
3106
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003107 // Do we need to explicitly import anonymous namespaces into the parent
3108 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003109 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3110 CmdArgs.push_back("-dwarf-explicit-import");
3111
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003112 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003113}
3114
David L. Jonesf561aba2017-03-08 01:02:16 +00003115void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3116 const InputInfo &Output, const InputInfoList &Inputs,
3117 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003118 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003119 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3120 const std::string &TripleStr = Triple.getTriple();
3121
3122 bool KernelOrKext =
3123 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3124 const Driver &D = getToolChain().getDriver();
3125 ArgStringList CmdArgs;
3126
3127 // Check number of inputs for sanity. We need at least one input.
3128 assert(Inputs.size() >= 1 && "Must have at least one input.");
3129 const InputInfo &Input = Inputs[0];
Yaxun Liu398612b2018-05-08 21:02:12 +00003130 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003131 // device-side compilations). OpenMP device jobs also take the host IR as a
3132 // second input. All other jobs are expected to have exactly one
3133 // input.
3134 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003135 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003136 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Yaxun Liu398612b2018-05-08 21:02:12 +00003137 assert((IsCuda || IsHIP || (IsOpenMPDevice && Inputs.size() == 2) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003138 Inputs.size() == 1) &&
3139 "Unable to handle multiple inputs.");
3140
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003141 const llvm::Triple *AuxTriple =
3142 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3143
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003144 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3145 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3146 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003147 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003148
Yaxun Liu398612b2018-05-08 21:02:12 +00003149 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3150 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3151 // Windows), we need to pass Windows-specific flags to cc1.
3152 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003153 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3154 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3155 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3156 }
3157
3158 // C++ is not supported for IAMCU.
3159 if (IsIAMCU && types::isCXX(Input.getType()))
3160 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3161
3162 // Invoke ourselves in -cc1 mode.
3163 //
3164 // FIXME: Implement custom jobs for internal actions.
3165 CmdArgs.push_back("-cc1");
3166
3167 // Add the "effective" target triple.
3168 CmdArgs.push_back("-triple");
3169 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3170
3171 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3172 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3173 Args.ClaimAllArgs(options::OPT_MJ);
3174 }
3175
Yaxun Liu398612b2018-05-08 21:02:12 +00003176 if (IsCuda || IsHIP) {
3177 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3178 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003179 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003180 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3181 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003182 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3183 ->getTriple()
3184 .normalize();
3185 else
Yaxun Liu398612b2018-05-08 21:02:12 +00003186 NormalizedTriple =
3187 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3188 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3189 ->getTriple()
3190 .normalize();
David L. Jonesf561aba2017-03-08 01:02:16 +00003191
3192 CmdArgs.push_back("-aux-triple");
3193 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3194 }
3195
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003196 if (IsOpenMPDevice) {
3197 // We have to pass the triple of the host if compiling for an OpenMP device.
3198 std::string NormalizedTriple =
3199 C.getSingleOffloadToolChain<Action::OFK_Host>()
3200 ->getTriple()
3201 .normalize();
3202 CmdArgs.push_back("-aux-triple");
3203 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3204 }
3205
David L. Jonesf561aba2017-03-08 01:02:16 +00003206 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3207 Triple.getArch() == llvm::Triple::thumb)) {
3208 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3209 unsigned Version;
3210 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3211 if (Version < 7)
3212 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3213 << TripleStr;
3214 }
3215
3216 // Push all default warning arguments that are specific to
3217 // the given target. These come before user provided warning options
3218 // are provided.
3219 getToolChain().addClangWarningOptions(CmdArgs);
3220
3221 // Select the appropriate action.
3222 RewriteKind rewriteKind = RK_None;
3223
3224 if (isa<AnalyzeJobAction>(JA)) {
3225 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3226 CmdArgs.push_back("-analyze");
3227 } else if (isa<MigrateJobAction>(JA)) {
3228 CmdArgs.push_back("-migrate");
3229 } else if (isa<PreprocessJobAction>(JA)) {
3230 if (Output.getType() == types::TY_Dependencies)
3231 CmdArgs.push_back("-Eonly");
3232 else {
3233 CmdArgs.push_back("-E");
3234 if (Args.hasArg(options::OPT_rewrite_objc) &&
3235 !Args.hasArg(options::OPT_g_Group))
3236 CmdArgs.push_back("-P");
3237 }
3238 } else if (isa<AssembleJobAction>(JA)) {
3239 CmdArgs.push_back("-emit-obj");
3240
3241 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3242
3243 // Also ignore explicit -force_cpusubtype_ALL option.
3244 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3245 } else if (isa<PrecompileJobAction>(JA)) {
3246 // Use PCH if the user requested it.
3247 bool UsePCH = D.CCCUsePCH;
3248
3249 if (JA.getType() == types::TY_Nothing)
3250 CmdArgs.push_back("-fsyntax-only");
3251 else if (JA.getType() == types::TY_ModuleFile)
3252 CmdArgs.push_back("-emit-module-interface");
3253 else if (UsePCH)
3254 CmdArgs.push_back("-emit-pch");
3255 else
3256 CmdArgs.push_back("-emit-pth");
3257 } else if (isa<VerifyPCHJobAction>(JA)) {
3258 CmdArgs.push_back("-verify-pch");
3259 } else {
3260 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3261 "Invalid action for clang tool.");
3262 if (JA.getType() == types::TY_Nothing) {
3263 CmdArgs.push_back("-fsyntax-only");
3264 } else if (JA.getType() == types::TY_LLVM_IR ||
3265 JA.getType() == types::TY_LTO_IR) {
3266 CmdArgs.push_back("-emit-llvm");
3267 } else if (JA.getType() == types::TY_LLVM_BC ||
3268 JA.getType() == types::TY_LTO_BC) {
3269 CmdArgs.push_back("-emit-llvm-bc");
3270 } else if (JA.getType() == types::TY_PP_Asm) {
3271 CmdArgs.push_back("-S");
3272 } else if (JA.getType() == types::TY_AST) {
3273 CmdArgs.push_back("-emit-pch");
3274 } else if (JA.getType() == types::TY_ModuleFile) {
3275 CmdArgs.push_back("-module-file-info");
3276 } else if (JA.getType() == types::TY_RewrittenObjC) {
3277 CmdArgs.push_back("-rewrite-objc");
3278 rewriteKind = RK_NonFragile;
3279 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3280 CmdArgs.push_back("-rewrite-objc");
3281 rewriteKind = RK_Fragile;
3282 } else {
3283 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3284 }
3285
3286 // Preserve use-list order by default when emitting bitcode, so that
3287 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3288 // same result as running passes here. For LTO, we don't need to preserve
3289 // the use-list order, since serialization to bitcode is part of the flow.
3290 if (JA.getType() == types::TY_LLVM_BC)
3291 CmdArgs.push_back("-emit-llvm-uselists");
3292
Artem Belevichecb178b2018-03-21 22:22:59 +00003293 // Device-side jobs do not support LTO.
3294 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3295 JA.isDeviceOffloading(Action::OFK_Host));
3296
3297 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003298 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3299
Paul Robinsond23f2a82017-07-13 21:25:47 +00003300 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3301 // does not support LTO unit features (CFI, whole program vtable opt)
3302 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003303 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003304 D.getLTOMode() == LTOK_Full)
3305 CmdArgs.push_back("-flto-unit");
3306 }
3307 }
3308
3309 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3310 if (!types::isLLVMIR(Input.getType()))
3311 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3312 << "-x ir";
3313 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3314 }
3315
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003316 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003317 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3318
David L. Jonesf561aba2017-03-08 01:02:16 +00003319 // Embed-bitcode option.
3320 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3321 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3322 // Add flags implied by -fembed-bitcode.
3323 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3324 // Disable all llvm IR level optimizations.
3325 CmdArgs.push_back("-disable-llvm-passes");
3326 }
3327 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3328 CmdArgs.push_back("-fembed-bitcode=marker");
3329
3330 // We normally speed up the clang process a bit by skipping destructors at
3331 // exit, but when we're generating diagnostics we can rely on some of the
3332 // cleanup.
3333 if (!C.isForDiagnostics())
3334 CmdArgs.push_back("-disable-free");
3335
David L. Jonesf561aba2017-03-08 01:02:16 +00003336#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003337 const bool IsAssertBuild = false;
3338#else
3339 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003340#endif
3341
Eric Fiselier123c7492018-02-07 18:36:51 +00003342 // Disable the verification pass in -asserts builds.
3343 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003344 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003345
3346 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003347 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3348 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003349 CmdArgs.push_back("-discard-value-names");
3350
David L. Jonesf561aba2017-03-08 01:02:16 +00003351 // Set the main file name, so that debug info works even with
3352 // -save-temps.
3353 CmdArgs.push_back("-main-file-name");
3354 CmdArgs.push_back(getBaseInputName(Args, Input));
3355
3356 // Some flags which affect the language (via preprocessor
3357 // defines).
3358 if (Args.hasArg(options::OPT_static))
3359 CmdArgs.push_back("-static-define");
3360
Martin Storsjo434ef832018-08-06 19:48:44 +00003361 if (Args.hasArg(options::OPT_municode))
3362 CmdArgs.push_back("-DUNICODE");
3363
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003364 if (isa<AnalyzeJobAction>(JA))
3365 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003366
3367 CheckCodeGenerationOptions(D, Args);
3368
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003369 unsigned FunctionAlignment = ParseFunctionAlignment(getToolChain(), Args);
3370 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3371 if (FunctionAlignment) {
3372 CmdArgs.push_back("-function-alignment");
3373 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3374 }
3375
David L. Jonesf561aba2017-03-08 01:02:16 +00003376 llvm::Reloc::Model RelocationModel;
3377 unsigned PICLevel;
3378 bool IsPIE;
3379 std::tie(RelocationModel, PICLevel, IsPIE) =
3380 ParsePICArgs(getToolChain(), Args);
3381
3382 const char *RMName = RelocationModelName(RelocationModel);
3383
3384 if ((RelocationModel == llvm::Reloc::ROPI ||
3385 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3386 types::isCXX(Input.getType()) &&
3387 !Args.hasArg(options::OPT_fallow_unsupported))
3388 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3389
3390 if (RMName) {
3391 CmdArgs.push_back("-mrelocation-model");
3392 CmdArgs.push_back(RMName);
3393 }
3394 if (PICLevel > 0) {
3395 CmdArgs.push_back("-pic-level");
3396 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3397 if (IsPIE)
3398 CmdArgs.push_back("-pic-is-pie");
3399 }
3400
3401 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3402 CmdArgs.push_back("-meabi");
3403 CmdArgs.push_back(A->getValue());
3404 }
3405
3406 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003407 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3408 if (!getToolChain().isThreadModelSupported(A->getValue()))
3409 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3410 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003411 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003412 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003413 else
3414 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3415
3416 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3417
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003418 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3419 options::OPT_fno_merge_all_constants, false))
3420 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003421
Manoj Guptada08f6a2018-07-19 00:44:52 +00003422 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3423 options::OPT_fdelete_null_pointer_checks, false))
3424 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3425
David L. Jonesf561aba2017-03-08 01:02:16 +00003426 // LLVM Code Generator Options.
3427
3428 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3429 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3430 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3431 options::OPT_frewrite_map_file_EQ)) {
3432 StringRef Map = A->getValue();
3433 if (!llvm::sys::fs::exists(Map)) {
3434 D.Diag(diag::err_drv_no_such_file) << Map;
3435 } else {
3436 CmdArgs.push_back("-frewrite-map-file");
3437 CmdArgs.push_back(A->getValue());
3438 A->claim();
3439 }
3440 }
3441 }
3442
3443 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3444 StringRef v = A->getValue();
3445 CmdArgs.push_back("-mllvm");
3446 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3447 A->claim();
3448 }
3449
3450 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3451 true))
3452 CmdArgs.push_back("-fno-jump-tables");
3453
Dehao Chen5e97f232017-08-24 21:37:33 +00003454 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3455 options::OPT_fno_profile_sample_accurate, false))
3456 CmdArgs.push_back("-fprofile-sample-accurate");
3457
David L. Jonesf561aba2017-03-08 01:02:16 +00003458 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3459 options::OPT_fno_preserve_as_comments, true))
3460 CmdArgs.push_back("-fno-preserve-as-comments");
3461
3462 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3463 CmdArgs.push_back("-mregparm");
3464 CmdArgs.push_back(A->getValue());
3465 }
3466
3467 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3468 options::OPT_freg_struct_return)) {
3469 if (getToolChain().getArch() != llvm::Triple::x86) {
3470 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003471 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003472 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3473 CmdArgs.push_back("-fpcc-struct-return");
3474 } else {
3475 assert(A->getOption().matches(options::OPT_freg_struct_return));
3476 CmdArgs.push_back("-freg-struct-return");
3477 }
3478 }
3479
3480 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3481 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3482
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003483 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003484 CmdArgs.push_back("-mdisable-fp-elim");
3485 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3486 options::OPT_fno_zero_initialized_in_bss))
3487 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3488
3489 bool OFastEnabled = isOptimizationLevelFast(Args);
3490 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3491 // enabled. This alias option is being used to simplify the hasFlag logic.
3492 OptSpecifier StrictAliasingAliasOption =
3493 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3494 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3495 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003496 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003497 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3498 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3499 CmdArgs.push_back("-relaxed-aliasing");
3500 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3501 options::OPT_fno_struct_path_tbaa))
3502 CmdArgs.push_back("-no-struct-path-tbaa");
3503 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3504 false))
3505 CmdArgs.push_back("-fstrict-enums");
3506 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3507 true))
3508 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003509 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3510 options::OPT_fno_allow_editor_placeholders, false))
3511 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003512 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3513 options::OPT_fno_strict_vtable_pointers,
3514 false))
3515 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003516 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3517 options::OPT_fno_force_emit_vtables,
3518 false))
3519 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003520 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3521 options::OPT_fno_optimize_sibling_calls))
3522 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003523 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003524 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003525 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003526
Wei Mi9b3d6272017-10-16 16:50:27 +00003527 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3528 options::OPT_fno_fine_grained_bitfield_accesses);
3529
David L. Jonesf561aba2017-03-08 01:02:16 +00003530 // Handle segmented stacks.
3531 if (Args.hasArg(options::OPT_fsplit_stack))
3532 CmdArgs.push_back("-split-stacks");
3533
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003534 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003535
3536 // Decide whether to use verbose asm. Verbose assembly is the default on
3537 // toolchains which have the integrated assembler on by default.
3538 bool IsIntegratedAssemblerDefault =
3539 getToolChain().IsIntegratedAssemblerDefault();
3540 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3541 IsIntegratedAssemblerDefault) ||
3542 Args.hasArg(options::OPT_dA))
3543 CmdArgs.push_back("-masm-verbose");
3544
Peter Collingbourned86ca942018-06-14 00:03:41 +00003545 if (!getToolChain().useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003546 CmdArgs.push_back("-no-integrated-as");
3547
3548 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3549 CmdArgs.push_back("-mdebug-pass");
3550 CmdArgs.push_back("Structure");
3551 }
3552 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3553 CmdArgs.push_back("-mdebug-pass");
3554 CmdArgs.push_back("Arguments");
3555 }
3556
3557 // Enable -mconstructor-aliases except on darwin, where we have to work around
3558 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3559 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003560 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003561 CmdArgs.push_back("-mconstructor-aliases");
3562
3563 // Darwin's kernel doesn't support guard variables; just die if we
3564 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003565 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003566 CmdArgs.push_back("-fforbid-guard-variables");
3567
3568 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3569 false)) {
3570 CmdArgs.push_back("-mms-bitfields");
3571 }
3572
3573 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3574 options::OPT_mno_pie_copy_relocations,
3575 false)) {
3576 CmdArgs.push_back("-mpie-copy-relocations");
3577 }
3578
Sriraman Tallam5c651482017-11-07 19:37:51 +00003579 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3580 CmdArgs.push_back("-fno-plt");
3581 }
3582
Vedant Kumardf502592017-09-12 22:51:53 +00003583 // -fhosted is default.
3584 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3585 // use Freestanding.
3586 bool Freestanding =
3587 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3588 KernelOrKext;
3589 if (Freestanding)
3590 CmdArgs.push_back("-ffreestanding");
3591
David L. Jonesf561aba2017-03-08 01:02:16 +00003592 // This is a coarse approximation of what llvm-gcc actually does, both
3593 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3594 // complicated ways.
3595 bool AsynchronousUnwindTables =
3596 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3597 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003598 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003599 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003600 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003601 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3602 AsynchronousUnwindTables))
3603 CmdArgs.push_back("-munwind-tables");
3604
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003605 getToolChain().addClangTargetOptions(Args, CmdArgs,
3606 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003607
3608 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3609 CmdArgs.push_back("-mlimit-float-precision");
3610 CmdArgs.push_back(A->getValue());
3611 }
3612
3613 // FIXME: Handle -mtune=.
3614 (void)Args.hasArg(options::OPT_mtune_EQ);
3615
3616 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3617 CmdArgs.push_back("-mcode-model");
3618 CmdArgs.push_back(A->getValue());
3619 }
3620
3621 // Add the target cpu
3622 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3623 if (!CPU.empty()) {
3624 CmdArgs.push_back("-target-cpu");
3625 CmdArgs.push_back(Args.MakeArgString(CPU));
3626 }
3627
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003628 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003629
David L. Jonesf561aba2017-03-08 01:02:16 +00003630 // These two are potentially updated by AddClangCLArgs.
3631 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3632 bool EmitCodeView = false;
3633
3634 // Add clang-cl arguments.
3635 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003636 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003637 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
Reid Kleckner54af3e72018-02-26 22:55:33 +00003638 else
3639 EmitCodeView = Args.hasArg(options::OPT_gcodeview);
David L. Jonesf561aba2017-03-08 01:02:16 +00003640
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003641 const Arg *SplitDWARFArg = nullptr;
3642 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3643 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3644
3645 // Add the split debug info name to the command lines here so we
3646 // can propagate it to the backend.
3647 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3648 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3649 isa<BackendJobAction>(JA));
3650 const char *SplitDWARFOut;
3651 if (SplitDWARF) {
3652 CmdArgs.push_back("-split-dwarf-file");
3653 SplitDWARFOut = SplitDebugName(Args, Input);
3654 CmdArgs.push_back(SplitDWARFOut);
3655 }
3656
David L. Jonesf561aba2017-03-08 01:02:16 +00003657 // Pass the linker version in use.
3658 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3659 CmdArgs.push_back("-target-linker-version");
3660 CmdArgs.push_back(A->getValue());
3661 }
3662
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003663 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003664 CmdArgs.push_back("-momit-leaf-frame-pointer");
3665
3666 // Explicitly error on some things we know we don't support and can't just
3667 // ignore.
3668 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3669 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003670 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003671 getToolChain().getArch() == llvm::Triple::x86) {
3672 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3673 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3674 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3675 << Unsupported->getOption().getName();
3676 }
Eric Christopher758aad72017-03-21 22:06:18 +00003677 // The faltivec option has been superseded by the maltivec option.
3678 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3679 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3680 << Unsupported->getOption().getName()
3681 << "please use -maltivec and include altivec.h explicitly";
3682 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3683 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3684 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003685 }
3686
3687 Args.AddAllArgs(CmdArgs, options::OPT_v);
3688 Args.AddLastArg(CmdArgs, options::OPT_H);
3689 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3690 CmdArgs.push_back("-header-include-file");
3691 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3692 : "-");
3693 }
3694 Args.AddLastArg(CmdArgs, options::OPT_P);
3695 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3696
3697 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3698 CmdArgs.push_back("-diagnostic-log-file");
3699 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3700 : "-");
3701 }
3702
David L. Jonesf561aba2017-03-08 01:02:16 +00003703 bool UseSeparateSections = isUseSeparateSections(Triple);
3704
3705 if (Args.hasFlag(options::OPT_ffunction_sections,
3706 options::OPT_fno_function_sections, UseSeparateSections)) {
3707 CmdArgs.push_back("-ffunction-sections");
3708 }
3709
3710 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3711 UseSeparateSections)) {
3712 CmdArgs.push_back("-fdata-sections");
3713 }
3714
3715 if (!Args.hasFlag(options::OPT_funique_section_names,
3716 options::OPT_fno_unique_section_names, true))
3717 CmdArgs.push_back("-fno-unique-section-names");
3718
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003719 if (auto *A = Args.getLastArg(
3720 options::OPT_finstrument_functions,
3721 options::OPT_finstrument_functions_after_inlining,
3722 options::OPT_finstrument_function_entry_bare))
3723 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003724
Artem Belevichc30bcad2018-01-24 17:41:02 +00003725 // NVPTX doesn't support PGO or coverage. There's no runtime support for
3726 // sampling, overhead of call arc collection is way too high and there's no
3727 // way to collect the output.
3728 if (!Triple.isNVPTX())
3729 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003730
Richard Smithf667ad52017-08-26 01:04:35 +00003731 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3732 ABICompatArg->render(Args, CmdArgs);
3733
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003734 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
3735 if (RawTriple.isPS4CPU()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003736 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00003737 PS4cpu::addSanitizerArgs(getToolChain(), CmdArgs);
3738 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003739
3740 // Pass options for controlling the default header search paths.
3741 if (Args.hasArg(options::OPT_nostdinc)) {
3742 CmdArgs.push_back("-nostdsysteminc");
3743 CmdArgs.push_back("-nobuiltininc");
3744 } else {
3745 if (Args.hasArg(options::OPT_nostdlibinc))
3746 CmdArgs.push_back("-nostdsysteminc");
3747 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3748 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3749 }
3750
3751 // Pass the path to compiler resource files.
3752 CmdArgs.push_back("-resource-dir");
3753 CmdArgs.push_back(D.ResourceDir.c_str());
3754
3755 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3756
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003757 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003758
3759 // Add preprocessing options like -I, -D, etc. if we are using the
3760 // preprocessor.
3761 //
3762 // FIXME: Support -fpreprocessed
3763 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3764 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3765
3766 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3767 // that "The compiler can only warn and ignore the option if not recognized".
3768 // When building with ccache, it will pass -D options to clang even on
3769 // preprocessed inputs and configure concludes that -fPIC is not supported.
3770 Args.ClaimAllArgs(options::OPT_D);
3771
3772 // Manually translate -O4 to -O3; let clang reject others.
3773 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3774 if (A->getOption().matches(options::OPT_O4)) {
3775 CmdArgs.push_back("-O3");
3776 D.Diag(diag::warn_O4_is_O3);
3777 } else {
3778 A->render(Args, CmdArgs);
3779 }
3780 }
3781
3782 // Warn about ignored options to clang.
3783 for (const Arg *A :
3784 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3785 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3786 A->claim();
3787 }
3788
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003789 for (const Arg *A :
3790 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3791 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3792 A->claim();
3793 }
3794
David L. Jonesf561aba2017-03-08 01:02:16 +00003795 claimNoWarnArgs(Args);
3796
3797 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3798
3799 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3800 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3801 CmdArgs.push_back("-pedantic");
3802 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3803 Args.AddLastArg(CmdArgs, options::OPT_w);
3804
Leonard Chanf921d852018-06-04 16:07:52 +00003805 // Fixed point flags
3806 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
3807 /*Default=*/false))
3808 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
3809
David L. Jonesf561aba2017-03-08 01:02:16 +00003810 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3811 // (-ansi is equivalent to -std=c89 or -std=c++98).
3812 //
3813 // If a std is supplied, only add -trigraphs if it follows the
3814 // option.
3815 bool ImplyVCPPCXXVer = false;
3816 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3817 if (Std->getOption().matches(options::OPT_ansi))
3818 if (types::isCXX(InputType))
3819 CmdArgs.push_back("-std=c++98");
3820 else
3821 CmdArgs.push_back("-std=c89");
3822 else
3823 Std->render(Args, CmdArgs);
3824
3825 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3826 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3827 options::OPT_ftrigraphs,
3828 options::OPT_fno_trigraphs))
3829 if (A != Std)
3830 A->render(Args, CmdArgs);
3831 } else {
3832 // Honor -std-default.
3833 //
3834 // FIXME: Clang doesn't correctly handle -std= when the input language
3835 // doesn't match. For the time being just ignore this for C++ inputs;
3836 // eventually we want to do all the standard defaulting here instead of
3837 // splitting it between the driver and clang -cc1.
3838 if (!types::isCXX(InputType))
3839 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3840 /*Joined=*/true);
3841 else if (IsWindowsMSVC)
3842 ImplyVCPPCXXVer = true;
3843
3844 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3845 options::OPT_fno_trigraphs);
3846 }
3847
3848 // GCC's behavior for -Wwrite-strings is a bit strange:
3849 // * In C, this "warning flag" changes the types of string literals from
3850 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3851 // for the discarded qualifier.
3852 // * In C++, this is just a normal warning flag.
3853 //
3854 // Implementing this warning correctly in C is hard, so we follow GCC's
3855 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3856 // a non-const char* in C, rather than using this crude hack.
3857 if (!types::isCXX(InputType)) {
3858 // FIXME: This should behave just like a warning flag, and thus should also
3859 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3860 Arg *WriteStrings =
3861 Args.getLastArg(options::OPT_Wwrite_strings,
3862 options::OPT_Wno_write_strings, options::OPT_w);
3863 if (WriteStrings &&
3864 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3865 CmdArgs.push_back("-fconst-strings");
3866 }
3867
3868 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3869 // during C++ compilation, which it is by default. GCC keeps this define even
3870 // in the presence of '-w', match this behavior bug-for-bug.
3871 if (types::isCXX(InputType) &&
3872 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3873 true)) {
3874 CmdArgs.push_back("-fdeprecated-macro");
3875 }
3876
3877 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3878 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3879 if (Asm->getOption().matches(options::OPT_fasm))
3880 CmdArgs.push_back("-fgnu-keywords");
3881 else
3882 CmdArgs.push_back("-fno-gnu-keywords");
3883 }
3884
3885 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3886 CmdArgs.push_back("-fno-dwarf-directory-asm");
3887
3888 if (ShouldDisableAutolink(Args, getToolChain()))
3889 CmdArgs.push_back("-fno-autolink");
3890
3891 // Add in -fdebug-compilation-dir if necessary.
3892 addDebugCompDirArg(Args, CmdArgs);
3893
Paul Robinson9b292b42018-07-10 15:15:24 +00003894 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003895
3896 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3897 options::OPT_ftemplate_depth_EQ)) {
3898 CmdArgs.push_back("-ftemplate-depth");
3899 CmdArgs.push_back(A->getValue());
3900 }
3901
3902 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3903 CmdArgs.push_back("-foperator-arrow-depth");
3904 CmdArgs.push_back(A->getValue());
3905 }
3906
3907 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3908 CmdArgs.push_back("-fconstexpr-depth");
3909 CmdArgs.push_back(A->getValue());
3910 }
3911
3912 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3913 CmdArgs.push_back("-fconstexpr-steps");
3914 CmdArgs.push_back(A->getValue());
3915 }
3916
3917 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3918 CmdArgs.push_back("-fbracket-depth");
3919 CmdArgs.push_back(A->getValue());
3920 }
3921
3922 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3923 options::OPT_Wlarge_by_value_copy_def)) {
3924 if (A->getNumValues()) {
3925 StringRef bytes = A->getValue();
3926 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3927 } else
3928 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3929 }
3930
3931 if (Args.hasArg(options::OPT_relocatable_pch))
3932 CmdArgs.push_back("-relocatable-pch");
3933
3934 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3935 CmdArgs.push_back("-fconstant-string-class");
3936 CmdArgs.push_back(A->getValue());
3937 }
3938
3939 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3940 CmdArgs.push_back("-ftabstop");
3941 CmdArgs.push_back(A->getValue());
3942 }
3943
Sean Eveson5110d4f2018-01-08 13:42:26 +00003944 if (Args.hasFlag(options::OPT_fstack_size_section,
3945 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3946 CmdArgs.push_back("-fstack-size-section");
3947
David L. Jonesf561aba2017-03-08 01:02:16 +00003948 CmdArgs.push_back("-ferror-limit");
3949 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3950 CmdArgs.push_back(A->getValue());
3951 else
3952 CmdArgs.push_back("19");
3953
3954 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3955 CmdArgs.push_back("-fmacro-backtrace-limit");
3956 CmdArgs.push_back(A->getValue());
3957 }
3958
3959 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3960 CmdArgs.push_back("-ftemplate-backtrace-limit");
3961 CmdArgs.push_back(A->getValue());
3962 }
3963
3964 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3965 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3966 CmdArgs.push_back(A->getValue());
3967 }
3968
3969 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3970 CmdArgs.push_back("-fspell-checking-limit");
3971 CmdArgs.push_back(A->getValue());
3972 }
3973
3974 // Pass -fmessage-length=.
3975 CmdArgs.push_back("-fmessage-length");
3976 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3977 CmdArgs.push_back(A->getValue());
3978 } else {
3979 // If -fmessage-length=N was not specified, determine whether this is a
3980 // terminal and, if so, implicitly define -fmessage-length appropriately.
3981 unsigned N = llvm::sys::Process::StandardErrColumns();
3982 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3983 }
3984
3985 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3986 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3987 options::OPT_fvisibility_ms_compat)) {
3988 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3989 CmdArgs.push_back("-fvisibility");
3990 CmdArgs.push_back(A->getValue());
3991 } else {
3992 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3993 CmdArgs.push_back("-fvisibility");
3994 CmdArgs.push_back("hidden");
3995 CmdArgs.push_back("-ftype-visibility");
3996 CmdArgs.push_back("default");
3997 }
3998 }
3999
4000 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4001
4002 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4003
David L. Jonesf561aba2017-03-08 01:02:16 +00004004 // Forward -f (flag) options which we can pass directly.
4005 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4006 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004007 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004008 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004009 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4010 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004011 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004012
David L. Jonesf561aba2017-03-08 01:02:16 +00004013 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004014 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004015 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004016
David L. Jonesf561aba2017-03-08 01:02:16 +00004017 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4018 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4019
4020 // Forward flags for OpenMP. We don't do this if the current action is an
4021 // device offloading action other than OpenMP.
4022 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4023 options::OPT_fno_openmp, false) &&
4024 (JA.isDeviceOffloading(Action::OFK_None) ||
4025 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004026 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004027 case Driver::OMPRT_OMP:
4028 case Driver::OMPRT_IOMP5:
4029 // Clang can generate useful OpenMP code for these two runtime libraries.
4030 CmdArgs.push_back("-fopenmp");
4031
4032 // If no option regarding the use of TLS in OpenMP codegeneration is
4033 // given, decide a default based on the target. Otherwise rely on the
4034 // options and pass the right information to the frontend.
4035 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4036 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4037 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004038 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4039 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004040 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Carlo Bertolli79712092018-02-28 20:48:35 +00004041
4042 // When in OpenMP offloading mode with NVPTX target, forward
4043 // cuda-mode flag
4044 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_cuda_mode,
4045 options::OPT_fno_openmp_cuda_mode);
David L. Jonesf561aba2017-03-08 01:02:16 +00004046 break;
4047 default:
4048 // By default, if Clang doesn't know how to generate useful OpenMP code
4049 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4050 // down to the actual compilation.
4051 // FIXME: It would be better to have a mode which *only* omits IR
4052 // generation based on the OpenMP support so that we get consistent
4053 // semantic analysis, etc.
4054 break;
4055 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004056 } else {
4057 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4058 options::OPT_fno_openmp_simd);
4059 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004060 }
4061
4062 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4063 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4064
Dean Michael Berris835832d2017-03-30 00:29:36 +00004065 const XRayArgs &XRay = getToolChain().getXRayArgs();
4066 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
4067
David L. Jonesf561aba2017-03-08 01:02:16 +00004068 if (getToolChain().SupportsProfiling())
4069 Args.AddLastArg(CmdArgs, options::OPT_pg);
4070
4071 if (getToolChain().SupportsProfiling())
4072 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4073
4074 // -flax-vector-conversions is default.
4075 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4076 options::OPT_fno_lax_vector_conversions))
4077 CmdArgs.push_back("-fno-lax-vector-conversions");
4078
4079 if (Args.getLastArg(options::OPT_fapple_kext) ||
4080 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4081 CmdArgs.push_back("-fapple-kext");
4082
4083 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4084 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4085 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4086 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4087 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4088
4089 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4090 CmdArgs.push_back("-ftrapv-handler");
4091 CmdArgs.push_back(A->getValue());
4092 }
4093
4094 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4095
4096 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4097 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4098 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4099 if (A->getOption().matches(options::OPT_fwrapv))
4100 CmdArgs.push_back("-fwrapv");
4101 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4102 options::OPT_fno_strict_overflow)) {
4103 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4104 CmdArgs.push_back("-fwrapv");
4105 }
4106
4107 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4108 options::OPT_fno_reroll_loops))
4109 if (A->getOption().matches(options::OPT_freroll_loops))
4110 CmdArgs.push_back("-freroll-loops");
4111
4112 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4113 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4114 options::OPT_fno_unroll_loops);
4115
4116 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4117
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004118 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004119
4120 // Translate -mstackrealign
4121 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4122 false))
4123 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4124
4125 if (Args.hasArg(options::OPT_mstack_alignment)) {
4126 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4127 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4128 }
4129
4130 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4131 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4132
4133 if (!Size.empty())
4134 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4135 else
4136 CmdArgs.push_back("-mstack-probe-size=0");
4137 }
4138
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004139 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4140 options::OPT_mno_stack_arg_probe, true))
4141 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4142
David L. Jonesf561aba2017-03-08 01:02:16 +00004143 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4144 options::OPT_mno_restrict_it)) {
4145 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004146 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004147 CmdArgs.push_back("-arm-restrict-it");
4148 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004149 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004150 CmdArgs.push_back("-arm-no-restrict-it");
4151 }
4152 } else if (Triple.isOSWindows() &&
4153 (Triple.getArch() == llvm::Triple::arm ||
4154 Triple.getArch() == llvm::Triple::thumb)) {
4155 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004156 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004157 CmdArgs.push_back("-arm-restrict-it");
4158 }
4159
4160 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004161 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004162
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004163 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4164 CmdArgs.push_back(
4165 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4166 }
4167
David L. Jonesf561aba2017-03-08 01:02:16 +00004168 // Forward -f options with positive and negative forms; we translate
4169 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004170 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004171 StringRef fname = A->getValue();
4172 if (!llvm::sys::fs::exists(fname))
4173 D.Diag(diag::err_drv_no_such_file) << fname;
4174 else
4175 A->render(Args, CmdArgs);
4176 }
4177
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004178 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004179
4180 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4181 options::OPT_fno_assume_sane_operator_new))
4182 CmdArgs.push_back("-fno-assume-sane-operator-new");
4183
4184 // -fblocks=0 is default.
4185 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4186 getToolChain().IsBlocksDefault()) ||
4187 (Args.hasArg(options::OPT_fgnu_runtime) &&
4188 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4189 !Args.hasArg(options::OPT_fno_blocks))) {
4190 CmdArgs.push_back("-fblocks");
4191
4192 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4193 !getToolChain().hasBlocksRuntime())
4194 CmdArgs.push_back("-fblocks-runtime-optional");
4195 }
4196
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004197 // -fencode-extended-block-signature=1 is default.
4198 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4199 CmdArgs.push_back("-fencode-extended-block-signature");
4200
David L. Jonesf561aba2017-03-08 01:02:16 +00004201 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4202 false) &&
4203 types::isCXX(InputType)) {
4204 CmdArgs.push_back("-fcoroutines-ts");
4205 }
4206
Aaron Ballman61736552017-10-21 20:28:58 +00004207 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4208 options::OPT_fno_double_square_bracket_attributes);
4209
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004210 bool HaveModules = false;
4211 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004212
4213 // -faccess-control is default.
4214 if (Args.hasFlag(options::OPT_fno_access_control,
4215 options::OPT_faccess_control, false))
4216 CmdArgs.push_back("-fno-access-control");
4217
4218 // -felide-constructors is the default.
4219 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4220 options::OPT_felide_constructors, false))
4221 CmdArgs.push_back("-fno-elide-constructors");
4222
4223 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4224
4225 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004226 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004227 CmdArgs.push_back("-fno-rtti");
4228
4229 // -fshort-enums=0 is default for all architectures except Hexagon.
4230 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4231 getToolChain().getArch() == llvm::Triple::hexagon))
4232 CmdArgs.push_back("-fshort-enums");
4233
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004234 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004235
4236 // -fuse-cxa-atexit is default.
4237 if (!Args.hasFlag(
4238 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004239 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004240 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004241 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004242 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4243 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004244 KernelOrKext)
4245 CmdArgs.push_back("-fno-use-cxa-atexit");
4246
Akira Hatanaka617e2612018-04-17 18:41:52 +00004247 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4248 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004249 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004250 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4251
David L. Jonesf561aba2017-03-08 01:02:16 +00004252 // -fms-extensions=0 is default.
4253 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4254 IsWindowsMSVC))
4255 CmdArgs.push_back("-fms-extensions");
4256
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004257 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004258 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004259 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004260 CmdArgs.push_back("-fuse-line-directives");
4261
4262 // -fms-compatibility=0 is default.
4263 if (Args.hasFlag(options::OPT_fms_compatibility,
4264 options::OPT_fno_ms_compatibility,
4265 (IsWindowsMSVC &&
4266 Args.hasFlag(options::OPT_fms_extensions,
4267 options::OPT_fno_ms_extensions, true))))
4268 CmdArgs.push_back("-fms-compatibility");
4269
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004270 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004271 if (!MSVT.empty())
4272 CmdArgs.push_back(
4273 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4274
4275 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4276 if (ImplyVCPPCXXVer) {
4277 StringRef LanguageStandard;
4278 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4279 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4280 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004281 .Case("c++17", "-std=c++17")
4282 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004283 .Default("");
4284 if (LanguageStandard.empty())
4285 D.Diag(clang::diag::warn_drv_unused_argument)
4286 << StdArg->getAsString(Args);
4287 }
4288
4289 if (LanguageStandard.empty()) {
4290 if (IsMSVC2015Compatible)
4291 LanguageStandard = "-std=c++14";
4292 else
4293 LanguageStandard = "-std=c++11";
4294 }
4295
4296 CmdArgs.push_back(LanguageStandard.data());
4297 }
4298
4299 // -fno-borland-extensions is default.
4300 if (Args.hasFlag(options::OPT_fborland_extensions,
4301 options::OPT_fno_borland_extensions, false))
4302 CmdArgs.push_back("-fborland-extensions");
4303
4304 // -fno-declspec is default, except for PS4.
4305 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004306 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004307 CmdArgs.push_back("-fdeclspec");
4308 else if (Args.hasArg(options::OPT_fno_declspec))
4309 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4310
4311 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4312 // than 19.
4313 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4314 options::OPT_fno_threadsafe_statics,
4315 !IsWindowsMSVC || IsMSVC2015Compatible))
4316 CmdArgs.push_back("-fno-threadsafe-statics");
4317
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004318 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004319 // Many old Windows SDK versions require this to parse.
4320 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4321 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004322 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4323 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4324 CmdArgs.push_back("-fdelayed-template-parsing");
4325
4326 // -fgnu-keywords default varies depending on language; only pass if
4327 // specified.
4328 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4329 options::OPT_fno_gnu_keywords))
4330 A->render(Args, CmdArgs);
4331
4332 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4333 false))
4334 CmdArgs.push_back("-fgnu89-inline");
4335
4336 if (Args.hasArg(options::OPT_fno_inline))
4337 CmdArgs.push_back("-fno-inline");
4338
4339 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4340 options::OPT_finline_hint_functions,
4341 options::OPT_fno_inline_functions))
4342 InlineArg->render(Args, CmdArgs);
4343
4344 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4345 options::OPT_fno_experimental_new_pass_manager);
4346
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004347 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4348 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4349 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004350
4351 if (Args.hasFlag(options::OPT_fapplication_extension,
4352 options::OPT_fno_application_extension, false))
4353 CmdArgs.push_back("-fapplication-extension");
4354
4355 // Handle GCC-style exception args.
4356 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004357 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004358 CmdArgs);
4359
Martell Malonec950c652017-11-29 07:25:12 +00004360 // Handle exception personalities
4361 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4362 options::OPT_fseh_exceptions,
4363 options::OPT_fdwarf_exceptions);
4364 if (A) {
4365 const Option &Opt = A->getOption();
4366 if (Opt.matches(options::OPT_fsjlj_exceptions))
4367 CmdArgs.push_back("-fsjlj-exceptions");
4368 if (Opt.matches(options::OPT_fseh_exceptions))
4369 CmdArgs.push_back("-fseh-exceptions");
4370 if (Opt.matches(options::OPT_fdwarf_exceptions))
4371 CmdArgs.push_back("-fdwarf-exceptions");
4372 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004373 switch (getToolChain().GetExceptionModel(Args)) {
4374 default:
4375 break;
4376 case llvm::ExceptionHandling::DwarfCFI:
4377 CmdArgs.push_back("-fdwarf-exceptions");
4378 break;
4379 case llvm::ExceptionHandling::SjLj:
4380 CmdArgs.push_back("-fsjlj-exceptions");
4381 break;
4382 case llvm::ExceptionHandling::WinEH:
4383 CmdArgs.push_back("-fseh-exceptions");
4384 break;
Martell Malonec950c652017-11-29 07:25:12 +00004385 }
4386 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004387
4388 // C++ "sane" operator new.
4389 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4390 options::OPT_fno_assume_sane_operator_new))
4391 CmdArgs.push_back("-fno-assume-sane-operator-new");
4392
4393 // -frelaxed-template-template-args is off by default, as it is a severe
4394 // breaking change until a corresponding change to template partial ordering
4395 // is provided.
4396 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4397 options::OPT_fno_relaxed_template_template_args, false))
4398 CmdArgs.push_back("-frelaxed-template-template-args");
4399
4400 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4401 // most platforms.
4402 if (Args.hasFlag(options::OPT_fsized_deallocation,
4403 options::OPT_fno_sized_deallocation, false))
4404 CmdArgs.push_back("-fsized-deallocation");
4405
4406 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4407 // by default.
4408 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4409 options::OPT_fno_aligned_allocation,
4410 options::OPT_faligned_new_EQ)) {
4411 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4412 CmdArgs.push_back("-fno-aligned-allocation");
4413 else
4414 CmdArgs.push_back("-faligned-allocation");
4415 }
4416
4417 // The default new alignment can be specified using a dedicated option or via
4418 // a GCC-compatible option that also turns on aligned allocation.
4419 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4420 options::OPT_faligned_new_EQ))
4421 CmdArgs.push_back(
4422 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4423
4424 // -fconstant-cfstrings is default, and may be subject to argument translation
4425 // on Darwin.
4426 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4427 options::OPT_fno_constant_cfstrings) ||
4428 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4429 options::OPT_mno_constant_cfstrings))
4430 CmdArgs.push_back("-fno-constant-cfstrings");
4431
David L. Jonesf561aba2017-03-08 01:02:16 +00004432 // -fno-pascal-strings is default, only pass non-default.
4433 if (Args.hasFlag(options::OPT_fpascal_strings,
4434 options::OPT_fno_pascal_strings, false))
4435 CmdArgs.push_back("-fpascal-strings");
4436
4437 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4438 // -fno-pack-struct doesn't apply to -fpack-struct=.
4439 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4440 std::string PackStructStr = "-fpack-struct=";
4441 PackStructStr += A->getValue();
4442 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4443 } else if (Args.hasFlag(options::OPT_fpack_struct,
4444 options::OPT_fno_pack_struct, false)) {
4445 CmdArgs.push_back("-fpack-struct=1");
4446 }
4447
4448 // Handle -fmax-type-align=N and -fno-type-align
4449 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4450 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4451 if (!SkipMaxTypeAlign) {
4452 std::string MaxTypeAlignStr = "-fmax-type-align=";
4453 MaxTypeAlignStr += A->getValue();
4454 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4455 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004456 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004457 if (!SkipMaxTypeAlign) {
4458 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4459 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4460 }
4461 }
4462
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004463 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4464 CmdArgs.push_back("-Qn");
4465
David L. Jonesf561aba2017-03-08 01:02:16 +00004466 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004467 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004468 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4469 !NoCommonDefault))
4470 CmdArgs.push_back("-fno-common");
4471
4472 // -fsigned-bitfields is default, and clang doesn't yet support
4473 // -funsigned-bitfields.
4474 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4475 options::OPT_funsigned_bitfields))
4476 D.Diag(diag::warn_drv_clang_unsupported)
4477 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4478
4479 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4480 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4481 D.Diag(diag::err_drv_clang_unsupported)
4482 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4483
4484 // -finput_charset=UTF-8 is default. Reject others
4485 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4486 StringRef value = inputCharset->getValue();
4487 if (!value.equals_lower("utf-8"))
4488 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4489 << value;
4490 }
4491
4492 // -fexec_charset=UTF-8 is default. Reject others
4493 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4494 StringRef value = execCharset->getValue();
4495 if (!value.equals_lower("utf-8"))
4496 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4497 << value;
4498 }
4499
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004500 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004501
4502 // -fno-asm-blocks is default.
4503 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4504 false))
4505 CmdArgs.push_back("-fasm-blocks");
4506
4507 // -fgnu-inline-asm is default.
4508 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4509 options::OPT_fno_gnu_inline_asm, true))
4510 CmdArgs.push_back("-fno-gnu-inline-asm");
4511
4512 // Enable vectorization per default according to the optimization level
4513 // selected. For optimization levels that want vectorization we use the alias
4514 // option to simplify the hasFlag logic.
4515 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4516 OptSpecifier VectorizeAliasOption =
4517 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4518 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4519 options::OPT_fno_vectorize, EnableVec))
4520 CmdArgs.push_back("-vectorize-loops");
4521
4522 // -fslp-vectorize is enabled based on the optimization level selected.
4523 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4524 OptSpecifier SLPVectAliasOption =
4525 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4526 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4527 options::OPT_fno_slp_vectorize, EnableSLPVec))
4528 CmdArgs.push_back("-vectorize-slp");
4529
Craig Topper9a724aa2017-12-11 21:09:19 +00004530 ParseMPreferVectorWidth(D, Args, CmdArgs);
4531
David L. Jonesf561aba2017-03-08 01:02:16 +00004532 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4533 A->render(Args, CmdArgs);
4534
4535 if (Arg *A = Args.getLastArg(
4536 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4537 A->render(Args, CmdArgs);
4538
4539 // -fdollars-in-identifiers default varies depending on platform and
4540 // language; only pass if specified.
4541 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4542 options::OPT_fno_dollars_in_identifiers)) {
4543 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4544 CmdArgs.push_back("-fdollars-in-identifiers");
4545 else
4546 CmdArgs.push_back("-fno-dollars-in-identifiers");
4547 }
4548
4549 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4550 // practical purposes.
4551 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4552 options::OPT_fno_unit_at_a_time)) {
4553 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4554 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4555 }
4556
4557 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4558 options::OPT_fno_apple_pragma_pack, false))
4559 CmdArgs.push_back("-fapple-pragma-pack");
4560
David L. Jonesf561aba2017-03-08 01:02:16 +00004561 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004562 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004563 options::OPT_fno_save_optimization_record, false)) {
4564 CmdArgs.push_back("-opt-record-file");
4565
4566 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4567 if (A) {
4568 CmdArgs.push_back(A->getValue());
4569 } else {
4570 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004571
4572 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4573 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4574 F = FinalOutput->getValue();
4575 }
4576
4577 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004578 // Use the input filename.
4579 F = llvm::sys::path::stem(Input.getBaseInput());
4580
4581 // If we're compiling for an offload architecture (i.e. a CUDA device),
4582 // we need to make the file name for the device compilation different
4583 // from the host compilation.
4584 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4585 !JA.isDeviceOffloading(Action::OFK_Host)) {
4586 llvm::sys::path::replace_extension(F, "");
4587 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4588 Triple.normalize());
4589 F += "-";
4590 F += JA.getOffloadingArch();
4591 }
4592 }
4593
4594 llvm::sys::path::replace_extension(F, "opt.yaml");
4595 CmdArgs.push_back(Args.MakeArgString(F));
4596 }
4597 }
4598
Richard Smith86a3ef52017-06-09 21:24:02 +00004599 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4600 options::OPT_fno_rewrite_imports, false);
4601 if (RewriteImports)
4602 CmdArgs.push_back("-frewrite-imports");
4603
David L. Jonesf561aba2017-03-08 01:02:16 +00004604 // Enable rewrite includes if the user's asked for it or if we're generating
4605 // diagnostics.
4606 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4607 // nice to enable this when doing a crashdump for modules as well.
4608 if (Args.hasFlag(options::OPT_frewrite_includes,
4609 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004610 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004611 CmdArgs.push_back("-frewrite-includes");
4612
4613 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4614 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4615 options::OPT_traditional_cpp)) {
4616 if (isa<PreprocessJobAction>(JA))
4617 CmdArgs.push_back("-traditional-cpp");
4618 else
4619 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4620 }
4621
4622 Args.AddLastArg(CmdArgs, options::OPT_dM);
4623 Args.AddLastArg(CmdArgs, options::OPT_dD);
4624
4625 // Handle serialized diagnostics.
4626 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4627 CmdArgs.push_back("-serialize-diagnostic-file");
4628 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4629 }
4630
4631 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4632 CmdArgs.push_back("-fretain-comments-from-system-headers");
4633
4634 // Forward -fcomment-block-commands to -cc1.
4635 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4636 // Forward -fparse-all-comments to -cc1.
4637 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4638
4639 // Turn -fplugin=name.so into -load name.so
4640 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4641 CmdArgs.push_back("-load");
4642 CmdArgs.push_back(A->getValue());
4643 A->claim();
4644 }
4645
4646 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00004647 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
4648 if (!StatsFile.empty())
4649 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00004650
4651 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4652 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004653 // -finclude-default-header flag is for preprocessor,
4654 // do not pass it to other cc1 commands when save-temps is enabled
4655 if (C.getDriver().isSaveTempsEnabled() &&
4656 !isa<PreprocessJobAction>(JA)) {
4657 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4658 Arg->claim();
4659 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4660 CmdArgs.push_back(Arg->getValue());
4661 }
4662 }
4663 else {
4664 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4665 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004666 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4667 A->claim();
4668
4669 // We translate this by hand to the -cc1 argument, since nightly test uses
4670 // it and developers have been trained to spell it with -mllvm. Both
4671 // spellings are now deprecated and should be removed.
4672 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4673 CmdArgs.push_back("-disable-llvm-optzns");
4674 } else {
4675 A->render(Args, CmdArgs);
4676 }
4677 }
4678
4679 // With -save-temps, we want to save the unoptimized bitcode output from the
4680 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4681 // by the frontend.
4682 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4683 // has slightly different breakdown between stages.
4684 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4685 // pristine IR generated by the frontend. Ideally, a new compile action should
4686 // be added so both IR can be captured.
4687 if (C.getDriver().isSaveTempsEnabled() &&
4688 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4689 isa<CompileJobAction>(JA))
4690 CmdArgs.push_back("-disable-llvm-passes");
4691
4692 if (Output.getType() == types::TY_Dependencies) {
4693 // Handled with other dependency code.
4694 } else if (Output.isFilename()) {
4695 CmdArgs.push_back("-o");
4696 CmdArgs.push_back(Output.getFilename());
4697 } else {
4698 assert(Output.isNothing() && "Invalid output.");
4699 }
4700
4701 addDashXForInput(Args, Input, CmdArgs);
4702
4703 if (Input.isFilename())
4704 CmdArgs.push_back(Input.getFilename());
4705 else
4706 Input.getInputArg().renderAsInput(Args, CmdArgs);
4707
4708 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4709
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004710 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004711
4712 // Optionally embed the -cc1 level arguments into the debug info, for build
4713 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004714 // Also record command line arguments into the debug info if
4715 // -grecord-gcc-switches options is set on.
4716 // By default, -gno-record-gcc-switches is set on and no recording.
4717 if (getToolChain().UseDwarfDebugFlags() ||
4718 Args.hasFlag(options::OPT_grecord_gcc_switches,
4719 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004720 ArgStringList OriginalArgs;
4721 for (const auto &Arg : Args)
4722 Arg->render(Args, OriginalArgs);
4723
4724 SmallString<256> Flags;
4725 Flags += Exec;
4726 for (const char *OriginalArg : OriginalArgs) {
4727 SmallString<128> EscapedArg;
4728 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4729 Flags += " ";
4730 Flags += EscapedArg;
4731 }
4732 CmdArgs.push_back("-dwarf-debug-flags");
4733 CmdArgs.push_back(Args.MakeArgString(Flags));
4734 }
4735
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004736 if (IsCuda) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004737 // Host-side cuda compilation receives all device-side outputs in a single
4738 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004739 if (Inputs.size() > 1) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00004740 assert(Inputs.size() == 2 && "More than one GPU binary!");
4741 CmdArgs.push_back("-fcuda-include-gpubinary");
4742 CmdArgs.push_back(Inputs[1].getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00004743 }
4744
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004745 if (Args.hasFlag(options::OPT_fcuda_rdc, options::OPT_fno_cuda_rdc, false))
4746 CmdArgs.push_back("-fcuda-rdc");
Artem Belevich679dafe2018-05-09 23:10:09 +00004747 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
4748 options::OPT_fno_cuda_short_ptr, false))
4749 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00004750 }
4751
David L. Jonesf561aba2017-03-08 01:02:16 +00004752 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4753 // to specify the result of the compile phase on the host, so the meaningful
4754 // device declarations can be identified. Also, -fopenmp-is-device is passed
4755 // along to tell the frontend that it is generating code for a device, so that
4756 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004757 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004758 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004759 if (Inputs.size() == 2) {
4760 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4761 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4762 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004763 }
4764
4765 // For all the host OpenMP offloading compile jobs we need to pass the targets
4766 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00004767 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004768 SmallString<128> TargetInfo("-fopenmp-targets=");
4769
4770 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4771 assert(Tgts && Tgts->getNumValues() &&
4772 "OpenMP offloading has to have targets specified.");
4773 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4774 if (i)
4775 TargetInfo += ',';
4776 // We need to get the string from the triple because it may be not exactly
4777 // the same as the one we get directly from the arguments.
4778 llvm::Triple T(Tgts->getValue(i));
4779 TargetInfo += T.getTriple();
4780 }
4781 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4782 }
4783
4784 bool WholeProgramVTables =
4785 Args.hasFlag(options::OPT_fwhole_program_vtables,
4786 options::OPT_fno_whole_program_vtables, false);
4787 if (WholeProgramVTables) {
4788 if (!D.isUsingLTO())
4789 D.Diag(diag::err_drv_argument_only_allowed_with)
4790 << "-fwhole-program-vtables"
4791 << "-flto";
4792 CmdArgs.push_back("-fwhole-program-vtables");
4793 }
4794
Amara Emerson4ee9f822018-01-26 00:27:22 +00004795 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
4796 options::OPT_fno_experimental_isel)) {
4797 CmdArgs.push_back("-mllvm");
4798 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
4799 CmdArgs.push_back("-global-isel=1");
4800
4801 // GISel is on by default on AArch64 -O0, so don't bother adding
4802 // the fallback remarks for it. Other combinations will add a warning of
4803 // some kind.
4804 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
4805 bool IsOptLevelSupported = false;
4806
4807 Arg *A = Args.getLastArg(options::OPT_O_Group);
4808 if (Triple.getArch() == llvm::Triple::aarch64) {
4809 if (!A || A->getOption().matches(options::OPT_O0))
4810 IsOptLevelSupported = true;
4811 }
4812 if (!IsArchSupported || !IsOptLevelSupported) {
4813 CmdArgs.push_back("-mllvm");
4814 CmdArgs.push_back("-global-isel-abort=2");
4815
4816 if (!IsArchSupported)
4817 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
4818 else
4819 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
4820 }
4821 } else {
4822 CmdArgs.push_back("-global-isel=0");
4823 }
4824 }
4825
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00004826 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
4827 options::OPT_fno_force_enable_int128)) {
4828 if (A->getOption().matches(options::OPT_fforce_enable_int128))
4829 CmdArgs.push_back("-fforce-enable-int128");
4830 }
4831
Peter Collingbourne54d13b42018-05-30 03:40:04 +00004832 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
4833 options::OPT_fno_complete_member_pointers, false))
4834 CmdArgs.push_back("-fcomplete-member-pointers");
4835
Erik Pilkington5a559e62018-08-21 17:24:06 +00004836 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
4837 options::OPT_fno_cxx_static_destructors, true))
4838 CmdArgs.push_back("-fno-c++-static-destructors");
4839
Jessica Paquette36a25672018-06-29 18:06:10 +00004840 if (Arg *A = Args.getLastArg(options::OPT_moutline,
4841 options::OPT_mno_outline)) {
4842 if (A->getOption().matches(options::OPT_moutline)) {
4843 // We only support -moutline in AArch64 right now. If we're not compiling
4844 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
4845 // proper mllvm flags.
4846 if (Triple.getArch() != llvm::Triple::aarch64) {
4847 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
4848 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00004849 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00004850 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004851 }
Jessica Paquette36a25672018-06-29 18:06:10 +00004852 } else {
4853 // Disable all outlining behaviour.
4854 CmdArgs.push_back("-mllvm");
4855 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00004856 }
4857 }
4858
Peter Collingbourne14b468b2018-07-18 00:27:07 +00004859 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Peter Collingbournefaf300f2018-08-24 20:38:15 +00004860 (getToolChain().getTriple().isOSBinFormatELF() ||
4861 getToolChain().getTriple().isOSBinFormatCOFF()) &&
Peter Collingbourne14b468b2018-07-18 00:27:07 +00004862 getToolChain().useIntegratedAs()))
4863 CmdArgs.push_back("-faddrsig");
4864
David L. Jonesf561aba2017-03-08 01:02:16 +00004865 // Finally add the compile command to the compilation.
4866 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4867 Output.getType() == types::TY_Object &&
4868 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4869 auto CLCommand =
4870 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4871 C.addCommand(llvm::make_unique<FallbackCommand>(
4872 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4873 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4874 isa<PrecompileJobAction>(JA)) {
4875 // In /fallback builds, run the main compilation even if the pch generation
4876 // fails, so that the main compilation's fallback to cl.exe runs.
4877 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4878 CmdArgs, Inputs));
4879 } else {
4880 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4881 }
4882
David L. Jonesf561aba2017-03-08 01:02:16 +00004883 if (Arg *A = Args.getLastArg(options::OPT_pg))
4884 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4885 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4886 << A->getAsString(Args);
4887
4888 // Claim some arguments which clang supports automatically.
4889
4890 // -fpch-preprocess is used with gcc to add a special marker in the output to
4891 // include the PCH file. Clang's PTH solution is completely transparent, so we
4892 // do not need to deal with it at all.
4893 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4894
4895 // Claim some arguments which clang doesn't support, but we don't
4896 // care to warn the user about.
4897 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4898 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4899
4900 // Disable warnings for clang -E -emit-llvm foo.c
4901 Args.ClaimAllArgs(options::OPT_emit_llvm);
4902}
4903
4904Clang::Clang(const ToolChain &TC)
4905 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4906 // as it is for other tools. Some operations on a Tool actually test
4907 // whether that tool is Clang based on the Tool's Name as a string.
4908 : Tool("clang", "clang frontend", TC, RF_Full) {}
4909
4910Clang::~Clang() {}
4911
4912/// Add options related to the Objective-C runtime/ABI.
4913///
4914/// Returns true if the runtime is non-fragile.
4915ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4916 ArgStringList &cmdArgs,
4917 RewriteKind rewriteKind) const {
4918 // Look for the controlling runtime option.
4919 Arg *runtimeArg =
4920 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4921 options::OPT_fobjc_runtime_EQ);
4922
4923 // Just forward -fobjc-runtime= to the frontend. This supercedes
4924 // options about fragility.
4925 if (runtimeArg &&
4926 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4927 ObjCRuntime runtime;
4928 StringRef value = runtimeArg->getValue();
4929 if (runtime.tryParse(value)) {
4930 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4931 << value;
4932 }
David Chisnall404bbcb2018-05-22 10:13:06 +00004933 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
4934 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnall93ce0182018-08-10 12:53:13 +00004935 if (!getToolChain().getTriple().isOSBinFormatELF() &&
4936 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00004937 getToolChain().getDriver().Diag(
4938 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
4939 << runtime.getVersion().getMajor();
4940 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004941
4942 runtimeArg->render(args, cmdArgs);
4943 return runtime;
4944 }
4945
4946 // Otherwise, we'll need the ABI "version". Version numbers are
4947 // slightly confusing for historical reasons:
4948 // 1 - Traditional "fragile" ABI
4949 // 2 - Non-fragile ABI, version 1
4950 // 3 - Non-fragile ABI, version 2
4951 unsigned objcABIVersion = 1;
4952 // If -fobjc-abi-version= is present, use that to set the version.
4953 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4954 StringRef value = abiArg->getValue();
4955 if (value == "1")
4956 objcABIVersion = 1;
4957 else if (value == "2")
4958 objcABIVersion = 2;
4959 else if (value == "3")
4960 objcABIVersion = 3;
4961 else
4962 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4963 } else {
4964 // Otherwise, determine if we are using the non-fragile ABI.
4965 bool nonFragileABIIsDefault =
4966 (rewriteKind == RK_NonFragile ||
4967 (rewriteKind == RK_None &&
4968 getToolChain().IsObjCNonFragileABIDefault()));
4969 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4970 options::OPT_fno_objc_nonfragile_abi,
4971 nonFragileABIIsDefault)) {
4972// Determine the non-fragile ABI version to use.
4973#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4974 unsigned nonFragileABIVersion = 1;
4975#else
4976 unsigned nonFragileABIVersion = 2;
4977#endif
4978
4979 if (Arg *abiArg =
4980 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4981 StringRef value = abiArg->getValue();
4982 if (value == "1")
4983 nonFragileABIVersion = 1;
4984 else if (value == "2")
4985 nonFragileABIVersion = 2;
4986 else
4987 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4988 << value;
4989 }
4990
4991 objcABIVersion = 1 + nonFragileABIVersion;
4992 } else {
4993 objcABIVersion = 1;
4994 }
4995 }
4996
4997 // We don't actually care about the ABI version other than whether
4998 // it's non-fragile.
4999 bool isNonFragile = objcABIVersion != 1;
5000
5001 // If we have no runtime argument, ask the toolchain for its default runtime.
5002 // However, the rewriter only really supports the Mac runtime, so assume that.
5003 ObjCRuntime runtime;
5004 if (!runtimeArg) {
5005 switch (rewriteKind) {
5006 case RK_None:
5007 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5008 break;
5009 case RK_Fragile:
5010 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5011 break;
5012 case RK_NonFragile:
5013 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5014 break;
5015 }
5016
5017 // -fnext-runtime
5018 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5019 // On Darwin, make this use the default behavior for the toolchain.
5020 if (getToolChain().getTriple().isOSDarwin()) {
5021 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5022
5023 // Otherwise, build for a generic macosx port.
5024 } else {
5025 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5026 }
5027
5028 // -fgnu-runtime
5029 } else {
5030 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5031 // Legacy behaviour is to target the gnustep runtime if we are in
5032 // non-fragile mode or the GCC runtime in fragile mode.
5033 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005034 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005035 else
5036 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5037 }
5038
5039 cmdArgs.push_back(
5040 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5041 return runtime;
5042}
5043
5044static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5045 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5046 I += HaveDash;
5047 return !HaveDash;
5048}
5049
5050namespace {
5051struct EHFlags {
5052 bool Synch = false;
5053 bool Asynch = false;
5054 bool NoUnwindC = false;
5055};
5056} // end anonymous namespace
5057
5058/// /EH controls whether to run destructor cleanups when exceptions are
5059/// thrown. There are three modifiers:
5060/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5061/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5062/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5063/// - c: Assume that extern "C" functions are implicitly nounwind.
5064/// The default is /EHs-c-, meaning cleanups are disabled.
5065static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5066 EHFlags EH;
5067
5068 std::vector<std::string> EHArgs =
5069 Args.getAllArgValues(options::OPT__SLASH_EH);
5070 for (auto EHVal : EHArgs) {
5071 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5072 switch (EHVal[I]) {
5073 case 'a':
5074 EH.Asynch = maybeConsumeDash(EHVal, I);
5075 if (EH.Asynch)
5076 EH.Synch = false;
5077 continue;
5078 case 'c':
5079 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5080 continue;
5081 case 's':
5082 EH.Synch = maybeConsumeDash(EHVal, I);
5083 if (EH.Synch)
5084 EH.Asynch = false;
5085 continue;
5086 default:
5087 break;
5088 }
5089 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5090 break;
5091 }
5092 }
5093 // The /GX, /GX- flags are only processed if there are not /EH flags.
5094 // The default is that /GX is not specified.
5095 if (EHArgs.empty() &&
5096 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5097 /*default=*/false)) {
5098 EH.Synch = true;
5099 EH.NoUnwindC = true;
5100 }
5101
5102 return EH;
5103}
5104
5105void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5106 ArgStringList &CmdArgs,
5107 codegenoptions::DebugInfoKind *DebugInfoKind,
5108 bool *EmitCodeView) const {
5109 unsigned RTOptionID = options::OPT__SLASH_MT;
5110
5111 if (Args.hasArg(options::OPT__SLASH_LDd))
5112 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5113 // but defining _DEBUG is sticky.
5114 RTOptionID = options::OPT__SLASH_MTd;
5115
5116 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5117 RTOptionID = A->getOption().getID();
5118
5119 StringRef FlagForCRT;
5120 switch (RTOptionID) {
5121 case options::OPT__SLASH_MD:
5122 if (Args.hasArg(options::OPT__SLASH_LDd))
5123 CmdArgs.push_back("-D_DEBUG");
5124 CmdArgs.push_back("-D_MT");
5125 CmdArgs.push_back("-D_DLL");
5126 FlagForCRT = "--dependent-lib=msvcrt";
5127 break;
5128 case options::OPT__SLASH_MDd:
5129 CmdArgs.push_back("-D_DEBUG");
5130 CmdArgs.push_back("-D_MT");
5131 CmdArgs.push_back("-D_DLL");
5132 FlagForCRT = "--dependent-lib=msvcrtd";
5133 break;
5134 case options::OPT__SLASH_MT:
5135 if (Args.hasArg(options::OPT__SLASH_LDd))
5136 CmdArgs.push_back("-D_DEBUG");
5137 CmdArgs.push_back("-D_MT");
5138 CmdArgs.push_back("-flto-visibility-public-std");
5139 FlagForCRT = "--dependent-lib=libcmt";
5140 break;
5141 case options::OPT__SLASH_MTd:
5142 CmdArgs.push_back("-D_DEBUG");
5143 CmdArgs.push_back("-D_MT");
5144 CmdArgs.push_back("-flto-visibility-public-std");
5145 FlagForCRT = "--dependent-lib=libcmtd";
5146 break;
5147 default:
5148 llvm_unreachable("Unexpected option ID.");
5149 }
5150
5151 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5152 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5153 } else {
5154 CmdArgs.push_back(FlagForCRT.data());
5155
5156 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5157 // users want. The /Za flag to cl.exe turns this off, but it's not
5158 // implemented in clang.
5159 CmdArgs.push_back("--dependent-lib=oldnames");
5160 }
5161
Erich Keane425f48d2018-05-04 15:58:31 +00005162 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5163 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005164
5165 // This controls whether or not we emit RTTI data for polymorphic types.
5166 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5167 /*default=*/false))
5168 CmdArgs.push_back("-fno-rtti-data");
5169
5170 // This controls whether or not we emit stack-protector instrumentation.
5171 // In MSVC, Buffer Security Check (/GS) is on by default.
5172 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5173 /*default=*/true)) {
5174 CmdArgs.push_back("-stack-protector");
5175 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5176 }
5177
5178 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5179 if (Arg *DebugInfoArg =
5180 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5181 options::OPT_gline_tables_only)) {
5182 *EmitCodeView = true;
5183 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5184 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5185 else
5186 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5187 CmdArgs.push_back("-gcodeview");
5188 } else {
5189 *EmitCodeView = false;
5190 }
5191
5192 const Driver &D = getToolChain().getDriver();
5193 EHFlags EH = parseClangCLEHFlags(D, Args);
5194 if (EH.Synch || EH.Asynch) {
5195 if (types::isCXX(InputType))
5196 CmdArgs.push_back("-fcxx-exceptions");
5197 CmdArgs.push_back("-fexceptions");
5198 }
5199 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5200 CmdArgs.push_back("-fexternc-nounwind");
5201
5202 // /EP should expand to -E -P.
5203 if (Args.hasArg(options::OPT__SLASH_EP)) {
5204 CmdArgs.push_back("-E");
5205 CmdArgs.push_back("-P");
5206 }
5207
5208 unsigned VolatileOptionID;
5209 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5210 getToolChain().getArch() == llvm::Triple::x86)
5211 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5212 else
5213 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5214
5215 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5216 VolatileOptionID = A->getOption().getID();
5217
5218 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5219 CmdArgs.push_back("-fms-volatile");
5220
5221 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5222 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5223 if (MostGeneralArg && BestCaseArg)
5224 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5225 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5226
5227 if (MostGeneralArg) {
5228 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5229 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5230 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5231
5232 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5233 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5234 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5235 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5236 << FirstConflict->getAsString(Args)
5237 << SecondConflict->getAsString(Args);
5238
5239 if (SingleArg)
5240 CmdArgs.push_back("-fms-memptr-rep=single");
5241 else if (MultipleArg)
5242 CmdArgs.push_back("-fms-memptr-rep=multiple");
5243 else
5244 CmdArgs.push_back("-fms-memptr-rep=virtual");
5245 }
5246
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005247 // Parse the default calling convention options.
5248 if (Arg *CCArg =
5249 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005250 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5251 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005252 unsigned DCCOptId = CCArg->getOption().getID();
5253 const char *DCCFlag = nullptr;
5254 bool ArchSupported = true;
5255 llvm::Triple::ArchType Arch = getToolChain().getArch();
5256 switch (DCCOptId) {
5257 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005258 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005259 break;
5260 case options::OPT__SLASH_Gr:
5261 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005262 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005263 break;
5264 case options::OPT__SLASH_Gz:
5265 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005266 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005267 break;
5268 case options::OPT__SLASH_Gv:
5269 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005270 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005271 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005272 case options::OPT__SLASH_Gregcall:
5273 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5274 DCCFlag = "-fdefault-calling-conv=regcall";
5275 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005276 }
5277
5278 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5279 if (ArchSupported && DCCFlag)
5280 CmdArgs.push_back(DCCFlag);
5281 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005282
5283 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5284 A->render(Args, CmdArgs);
5285
5286 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5287 CmdArgs.push_back("-fdiagnostics-format");
5288 if (Args.hasArg(options::OPT__SLASH_fallback))
5289 CmdArgs.push_back("msvc-fallback");
5290 else
5291 CmdArgs.push_back("msvc");
5292 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005293
Hans Wennborga912e3e2018-08-10 09:49:21 +00005294 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5295 SmallVector<StringRef, 1> SplitArgs;
5296 StringRef(A->getValue()).split(SplitArgs, ",");
5297 bool Instrument = false;
5298 bool NoChecks = false;
5299 for (StringRef Arg : SplitArgs) {
5300 if (Arg.equals_lower("cf"))
5301 Instrument = true;
5302 else if (Arg.equals_lower("cf-"))
5303 Instrument = false;
5304 else if (Arg.equals_lower("nochecks"))
5305 NoChecks = true;
5306 else if (Arg.equals_lower("nochecks-"))
5307 NoChecks = false;
5308 else
5309 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5310 }
5311 // Currently there's no support emitting CFG instrumentation; the flag only
5312 // emits the table of address-taken functions.
5313 if (Instrument || NoChecks)
5314 CmdArgs.push_back("-cfguard");
5315 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005316}
5317
5318visualstudio::Compiler *Clang::getCLFallback() const {
5319 if (!CLFallback)
5320 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5321 return CLFallback.get();
5322}
5323
5324
5325const char *Clang::getBaseInputName(const ArgList &Args,
5326 const InputInfo &Input) {
5327 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5328}
5329
5330const char *Clang::getBaseInputStem(const ArgList &Args,
5331 const InputInfoList &Inputs) {
5332 const char *Str = getBaseInputName(Args, Inputs[0]);
5333
5334 if (const char *End = strrchr(Str, '.'))
5335 return Args.MakeArgString(std::string(Str, End));
5336
5337 return Str;
5338}
5339
5340const char *Clang::getDependencyFileName(const ArgList &Args,
5341 const InputInfoList &Inputs) {
5342 // FIXME: Think about this more.
5343 std::string Res;
5344
5345 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5346 std::string Str(OutputOpt->getValue());
5347 Res = Str.substr(0, Str.rfind('.'));
5348 } else {
5349 Res = getBaseInputStem(Args, Inputs);
5350 }
5351 return Args.MakeArgString(Res + ".d");
5352}
5353
5354// Begin ClangAs
5355
5356void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5357 ArgStringList &CmdArgs) const {
5358 StringRef CPUName;
5359 StringRef ABIName;
5360 const llvm::Triple &Triple = getToolChain().getTriple();
5361 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5362
5363 CmdArgs.push_back("-target-abi");
5364 CmdArgs.push_back(ABIName.data());
5365}
5366
5367void ClangAs::AddX86TargetArgs(const ArgList &Args,
5368 ArgStringList &CmdArgs) const {
5369 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5370 StringRef Value = A->getValue();
5371 if (Value == "intel" || Value == "att") {
5372 CmdArgs.push_back("-mllvm");
5373 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5374 } else {
5375 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5376 << A->getOption().getName() << Value;
5377 }
5378 }
5379}
5380
5381void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5382 const InputInfo &Output, const InputInfoList &Inputs,
5383 const ArgList &Args,
5384 const char *LinkingOutput) const {
5385 ArgStringList CmdArgs;
5386
5387 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5388 const InputInfo &Input = Inputs[0];
5389
5390 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5391 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005392 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005393
5394 // Don't warn about "clang -w -c foo.s"
5395 Args.ClaimAllArgs(options::OPT_w);
5396 // and "clang -emit-llvm -c foo.s"
5397 Args.ClaimAllArgs(options::OPT_emit_llvm);
5398
5399 claimNoWarnArgs(Args);
5400
5401 // Invoke ourselves in -cc1as mode.
5402 //
5403 // FIXME: Implement custom jobs for internal actions.
5404 CmdArgs.push_back("-cc1as");
5405
5406 // Add the "effective" target triple.
5407 CmdArgs.push_back("-triple");
5408 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5409
5410 // Set the output mode, we currently only expect to be used as a real
5411 // assembler.
5412 CmdArgs.push_back("-filetype");
5413 CmdArgs.push_back("obj");
5414
5415 // Set the main file name, so that debug info works even with
5416 // -save-temps or preprocessed assembly.
5417 CmdArgs.push_back("-main-file-name");
5418 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5419
5420 // Add the target cpu
5421 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5422 if (!CPU.empty()) {
5423 CmdArgs.push_back("-target-cpu");
5424 CmdArgs.push_back(Args.MakeArgString(CPU));
5425 }
5426
5427 // Add the target features
5428 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5429
5430 // Ignore explicit -force_cpusubtype_ALL option.
5431 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5432
5433 // Pass along any -I options so we get proper .include search paths.
5434 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5435
5436 // Determine the original source input.
5437 const Action *SourceAction = &JA;
5438 while (SourceAction->getKind() != Action::InputClass) {
5439 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5440 SourceAction = SourceAction->getInputs()[0];
5441 }
5442
5443 // Forward -g and handle debug info related flags, assuming we are dealing
5444 // with an actual assembly file.
5445 bool WantDebug = false;
5446 unsigned DwarfVersion = 0;
5447 Args.ClaimAllArgs(options::OPT_g_Group);
5448 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5449 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5450 !A->getOption().matches(options::OPT_ggdb0);
5451 if (WantDebug)
5452 DwarfVersion = DwarfVersionNum(A->getSpelling());
5453 }
5454 if (DwarfVersion == 0)
5455 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5456
5457 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5458
5459 if (SourceAction->getType() == types::TY_Asm ||
5460 SourceAction->getType() == types::TY_PP_Asm) {
5461 // You might think that it would be ok to set DebugInfoKind outside of
5462 // the guard for source type, however there is a test which asserts
5463 // that some assembler invocation receives no -debug-info-kind,
5464 // and it's not clear whether that test is just overly restrictive.
5465 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5466 : codegenoptions::NoDebugInfo);
5467 // Add the -fdebug-compilation-dir flag if needed.
5468 addDebugCompDirArg(Args, CmdArgs);
5469
Paul Robinson9b292b42018-07-10 15:15:24 +00005470 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
5471
David L. Jonesf561aba2017-03-08 01:02:16 +00005472 // Set the AT_producer to the clang version when using the integrated
5473 // assembler on assembly source files.
5474 CmdArgs.push_back("-dwarf-debug-producer");
5475 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5476
5477 // And pass along -I options
5478 Args.AddAllArgs(CmdArgs, options::OPT_I);
5479 }
5480 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5481 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00005482 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005483
David L. Jonesf561aba2017-03-08 01:02:16 +00005484
5485 // Handle -fPIC et al -- the relocation-model affects the assembler
5486 // for some targets.
5487 llvm::Reloc::Model RelocationModel;
5488 unsigned PICLevel;
5489 bool IsPIE;
5490 std::tie(RelocationModel, PICLevel, IsPIE) =
5491 ParsePICArgs(getToolChain(), Args);
5492
5493 const char *RMName = RelocationModelName(RelocationModel);
5494 if (RMName) {
5495 CmdArgs.push_back("-mrelocation-model");
5496 CmdArgs.push_back(RMName);
5497 }
5498
5499 // Optionally embed the -cc1as level arguments into the debug info, for build
5500 // analysis.
5501 if (getToolChain().UseDwarfDebugFlags()) {
5502 ArgStringList OriginalArgs;
5503 for (const auto &Arg : Args)
5504 Arg->render(Args, OriginalArgs);
5505
5506 SmallString<256> Flags;
5507 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5508 Flags += Exec;
5509 for (const char *OriginalArg : OriginalArgs) {
5510 SmallString<128> EscapedArg;
5511 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5512 Flags += " ";
5513 Flags += EscapedArg;
5514 }
5515 CmdArgs.push_back("-dwarf-debug-flags");
5516 CmdArgs.push_back(Args.MakeArgString(Flags));
5517 }
5518
5519 // FIXME: Add -static support, once we have it.
5520
5521 // Add target specific flags.
5522 switch (getToolChain().getArch()) {
5523 default:
5524 break;
5525
5526 case llvm::Triple::mips:
5527 case llvm::Triple::mipsel:
5528 case llvm::Triple::mips64:
5529 case llvm::Triple::mips64el:
5530 AddMIPSTargetArgs(Args, CmdArgs);
5531 break;
5532
5533 case llvm::Triple::x86:
5534 case llvm::Triple::x86_64:
5535 AddX86TargetArgs(Args, CmdArgs);
5536 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005537
5538 case llvm::Triple::arm:
5539 case llvm::Triple::armeb:
5540 case llvm::Triple::thumb:
5541 case llvm::Triple::thumbeb:
5542 // This isn't in AddARMTargetArgs because we want to do this for assembly
5543 // only, not C/C++.
5544 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5545 options::OPT_mno_default_build_attributes, true)) {
5546 CmdArgs.push_back("-mllvm");
5547 CmdArgs.push_back("-arm-add-build-attributes");
5548 }
5549 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005550 }
5551
5552 // Consume all the warning flags. Usually this would be handled more
5553 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5554 // doesn't handle that so rather than warning about unused flags that are
5555 // actually used, we'll lie by omission instead.
5556 // FIXME: Stop lying and consume only the appropriate driver flags
5557 Args.ClaimAllArgs(options::OPT_W_Group);
5558
5559 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5560 getToolChain().getDriver());
5561
5562 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5563
5564 assert(Output.isFilename() && "Unexpected lipo output.");
5565 CmdArgs.push_back("-o");
5566 CmdArgs.push_back(Output.getFilename());
5567
Peter Collingbourne91d02842018-05-22 18:52:37 +00005568 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5569 getToolChain().getTriple().isOSLinux()) {
5570 CmdArgs.push_back("-split-dwarf-file");
5571 CmdArgs.push_back(SplitDebugName(Args, Input));
5572 }
5573
David L. Jonesf561aba2017-03-08 01:02:16 +00005574 assert(Input.isFilename() && "Invalid input.");
5575 CmdArgs.push_back(Input.getFilename());
5576
5577 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5578 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005579}
5580
5581// Begin OffloadBundler
5582
5583void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5584 const InputInfo &Output,
5585 const InputInfoList &Inputs,
5586 const llvm::opt::ArgList &TCArgs,
5587 const char *LinkingOutput) const {
5588 // The version with only one output is expected to refer to a bundling job.
5589 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5590
5591 // The bundling command looks like this:
5592 // clang-offload-bundler -type=bc
5593 // -targets=host-triple,openmp-triple1,openmp-triple2
5594 // -outputs=input_file
5595 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5596
5597 ArgStringList CmdArgs;
5598
5599 // Get the type.
5600 CmdArgs.push_back(TCArgs.MakeArgString(
5601 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5602
5603 assert(JA.getInputs().size() == Inputs.size() &&
5604 "Not have inputs for all dependence actions??");
5605
5606 // Get the targets.
5607 SmallString<128> Triples;
5608 Triples += "-targets=";
5609 for (unsigned I = 0; I < Inputs.size(); ++I) {
5610 if (I)
5611 Triples += ',';
5612
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005613 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005614 Action::OffloadKind CurKind = Action::OFK_Host;
5615 const ToolChain *CurTC = &getToolChain();
5616 const Action *CurDep = JA.getInputs()[I];
5617
5618 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005619 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005620 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005621 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005622 CurKind = A->getOffloadingDeviceKind();
5623 CurTC = TC;
5624 });
5625 }
5626 Triples += Action::GetOffloadKindName(CurKind);
5627 Triples += '-';
5628 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005629 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
5630 Triples += '-';
5631 Triples += CurDep->getOffloadingArch();
5632 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005633 }
5634 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5635
5636 // Get bundled file command.
5637 CmdArgs.push_back(
5638 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5639
5640 // Get unbundled files command.
5641 SmallString<128> UB;
5642 UB += "-inputs=";
5643 for (unsigned I = 0; I < Inputs.size(); ++I) {
5644 if (I)
5645 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005646
5647 // Find ToolChain for this input.
5648 const ToolChain *CurTC = &getToolChain();
5649 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5650 CurTC = nullptr;
5651 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5652 assert(CurTC == nullptr && "Expected one dependence!");
5653 CurTC = TC;
5654 });
5655 }
5656 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005657 }
5658 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5659
5660 // All the inputs are encoded as commands.
5661 C.addCommand(llvm::make_unique<Command>(
5662 JA, *this,
5663 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5664 CmdArgs, None));
5665}
5666
5667void OffloadBundler::ConstructJobMultipleOutputs(
5668 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5669 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5670 const char *LinkingOutput) const {
5671 // The version with multiple outputs is expected to refer to a unbundling job.
5672 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5673
5674 // The unbundling command looks like this:
5675 // clang-offload-bundler -type=bc
5676 // -targets=host-triple,openmp-triple1,openmp-triple2
5677 // -inputs=input_file
5678 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5679 // -unbundle
5680
5681 ArgStringList CmdArgs;
5682
5683 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5684 InputInfo Input = Inputs.front();
5685
5686 // Get the type.
5687 CmdArgs.push_back(TCArgs.MakeArgString(
5688 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5689
5690 // Get the targets.
5691 SmallString<128> Triples;
5692 Triples += "-targets=";
5693 auto DepInfo = UA.getDependentActionsInfo();
5694 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5695 if (I)
5696 Triples += ',';
5697
5698 auto &Dep = DepInfo[I];
5699 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5700 Triples += '-';
5701 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00005702 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
5703 !Dep.DependentBoundArch.empty()) {
5704 Triples += '-';
5705 Triples += Dep.DependentBoundArch;
5706 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005707 }
5708
5709 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5710
5711 // Get bundled file command.
5712 CmdArgs.push_back(
5713 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5714
5715 // Get unbundled files command.
5716 SmallString<128> UB;
5717 UB += "-outputs=";
5718 for (unsigned I = 0; I < Outputs.size(); ++I) {
5719 if (I)
5720 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005721 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005722 }
5723 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5724 CmdArgs.push_back("-unbundle");
5725
5726 // All the inputs are encoded as commands.
5727 C.addCommand(llvm::make_unique<Command>(
5728 JA, *this,
5729 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5730 CmdArgs, None));
5731}