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