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