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