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