blob: 3d374a4c6f5e66e9c261d18db8bbc27fe34d016f [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 }
1764 }
1765
1766 // Set flags to support MCU ABI.
1767 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1768 CmdArgs.push_back("-mfloat-abi");
1769 CmdArgs.push_back("soft");
1770 CmdArgs.push_back("-mstack-alignment=4");
1771 }
1772}
1773
1774void Clang::AddHexagonTargetArgs(const ArgList &Args,
1775 ArgStringList &CmdArgs) const {
1776 CmdArgs.push_back("-mqdsp6-compat");
1777 CmdArgs.push_back("-Wreturn-type");
1778
1779 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001780 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001781 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1782 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001783 }
1784
1785 if (!Args.hasArg(options::OPT_fno_short_enums))
1786 CmdArgs.push_back("-fshort-enums");
1787 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1788 CmdArgs.push_back("-mllvm");
1789 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1790 }
1791 CmdArgs.push_back("-mllvm");
1792 CmdArgs.push_back("-machine-sink-split=0");
1793}
1794
1795void Clang::AddLanaiTargetArgs(const ArgList &Args,
1796 ArgStringList &CmdArgs) const {
1797 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1798 StringRef CPUName = A->getValue();
1799
1800 CmdArgs.push_back("-target-cpu");
1801 CmdArgs.push_back(Args.MakeArgString(CPUName));
1802 }
1803 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1804 StringRef Value = A->getValue();
1805 // Only support mregparm=4 to support old usage. Report error for all other
1806 // cases.
1807 int Mregparm;
1808 if (Value.getAsInteger(10, Mregparm)) {
1809 if (Mregparm != 4) {
1810 getToolChain().getDriver().Diag(
1811 diag::err_drv_unsupported_option_argument)
1812 << A->getOption().getName() << Value;
1813 }
1814 }
1815 }
1816}
1817
1818void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1819 ArgStringList &CmdArgs) const {
1820 // Default to "hidden" visibility.
1821 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1822 options::OPT_fvisibility_ms_compat)) {
1823 CmdArgs.push_back("-fvisibility");
1824 CmdArgs.push_back("hidden");
1825 }
1826}
1827
1828void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1829 StringRef Target, const InputInfo &Output,
1830 const InputInfo &Input, const ArgList &Args) const {
1831 // If this is a dry run, do not create the compilation database file.
1832 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1833 return;
1834
1835 using llvm::yaml::escape;
1836 const Driver &D = getToolChain().getDriver();
1837
1838 if (!CompilationDatabase) {
1839 std::error_code EC;
1840 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1841 if (EC) {
1842 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1843 << EC.message();
1844 return;
1845 }
1846 CompilationDatabase = std::move(File);
1847 }
1848 auto &CDB = *CompilationDatabase;
1849 SmallString<128> Buf;
1850 if (llvm::sys::fs::current_path(Buf))
1851 Buf = ".";
1852 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1853 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1854 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1855 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1856 Buf = "-x";
1857 Buf += types::getTypeName(Input.getType());
1858 CDB << ", \"" << escape(Buf) << "\"";
1859 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1860 Buf = "--sysroot=";
1861 Buf += D.SysRoot;
1862 CDB << ", \"" << escape(Buf) << "\"";
1863 }
1864 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1865 for (auto &A: Args) {
1866 auto &O = A->getOption();
1867 // Skip language selection, which is positional.
1868 if (O.getID() == options::OPT_x)
1869 continue;
1870 // Skip writing dependency output and the compilation database itself.
1871 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1872 continue;
1873 // Skip inputs.
1874 if (O.getKind() == Option::InputClass)
1875 continue;
1876 // All other arguments are quoted and appended.
1877 ArgStringList ASL;
1878 A->render(Args, ASL);
1879 for (auto &it: ASL)
1880 CDB << ", \"" << escape(it) << "\"";
1881 }
1882 Buf = "--target=";
1883 Buf += Target;
1884 CDB << ", \"" << escape(Buf) << "\"]},\n";
1885}
1886
1887static void CollectArgsForIntegratedAssembler(Compilation &C,
1888 const ArgList &Args,
1889 ArgStringList &CmdArgs,
1890 const Driver &D) {
1891 if (UseRelaxAll(C, Args))
1892 CmdArgs.push_back("-mrelax-all");
1893
1894 // Only default to -mincremental-linker-compatible if we think we are
1895 // targeting the MSVC linker.
1896 bool DefaultIncrementalLinkerCompatible =
1897 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
1898 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
1899 options::OPT_mno_incremental_linker_compatible,
1900 DefaultIncrementalLinkerCompatible))
1901 CmdArgs.push_back("-mincremental-linker-compatible");
1902
1903 switch (C.getDefaultToolChain().getArch()) {
1904 case llvm::Triple::arm:
1905 case llvm::Triple::armeb:
1906 case llvm::Triple::thumb:
1907 case llvm::Triple::thumbeb:
1908 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
1909 StringRef Value = A->getValue();
1910 if (Value == "always" || Value == "never" || Value == "arm" ||
1911 Value == "thumb") {
1912 CmdArgs.push_back("-mllvm");
1913 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
1914 } else {
1915 D.Diag(diag::err_drv_unsupported_option_argument)
1916 << A->getOption().getName() << Value;
1917 }
1918 }
1919 break;
1920 default:
1921 break;
1922 }
1923
1924 // When passing -I arguments to the assembler we sometimes need to
1925 // unconditionally take the next argument. For example, when parsing
1926 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
1927 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
1928 // arg after parsing the '-I' arg.
1929 bool TakeNextArg = false;
1930
Petr Hosek5668d832017-11-22 01:38:31 +00001931 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00001932 const char *MipsTargetFeature = nullptr;
1933 for (const Arg *A :
1934 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
1935 A->claim();
1936
1937 for (StringRef Value : A->getValues()) {
1938 if (TakeNextArg) {
1939 CmdArgs.push_back(Value.data());
1940 TakeNextArg = false;
1941 continue;
1942 }
1943
1944 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
1945 Value == "-mbig-obj")
1946 continue; // LLVM handles bigobj automatically
1947
1948 switch (C.getDefaultToolChain().getArch()) {
1949 default:
1950 break;
Peter Smith3947cb32017-11-20 13:43:55 +00001951 case llvm::Triple::thumb:
1952 case llvm::Triple::thumbeb:
1953 case llvm::Triple::arm:
1954 case llvm::Triple::armeb:
1955 if (Value == "-mthumb")
1956 // -mthumb has already been processed in ComputeLLVMTriple()
1957 // recognize but skip over here.
1958 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00001959 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00001960 case llvm::Triple::mips:
1961 case llvm::Triple::mipsel:
1962 case llvm::Triple::mips64:
1963 case llvm::Triple::mips64el:
1964 if (Value == "--trap") {
1965 CmdArgs.push_back("-target-feature");
1966 CmdArgs.push_back("+use-tcc-in-div");
1967 continue;
1968 }
1969 if (Value == "--break") {
1970 CmdArgs.push_back("-target-feature");
1971 CmdArgs.push_back("-use-tcc-in-div");
1972 continue;
1973 }
1974 if (Value.startswith("-msoft-float")) {
1975 CmdArgs.push_back("-target-feature");
1976 CmdArgs.push_back("+soft-float");
1977 continue;
1978 }
1979 if (Value.startswith("-mhard-float")) {
1980 CmdArgs.push_back("-target-feature");
1981 CmdArgs.push_back("-soft-float");
1982 continue;
1983 }
1984
1985 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
1986 .Case("-mips1", "+mips1")
1987 .Case("-mips2", "+mips2")
1988 .Case("-mips3", "+mips3")
1989 .Case("-mips4", "+mips4")
1990 .Case("-mips5", "+mips5")
1991 .Case("-mips32", "+mips32")
1992 .Case("-mips32r2", "+mips32r2")
1993 .Case("-mips32r3", "+mips32r3")
1994 .Case("-mips32r5", "+mips32r5")
1995 .Case("-mips32r6", "+mips32r6")
1996 .Case("-mips64", "+mips64")
1997 .Case("-mips64r2", "+mips64r2")
1998 .Case("-mips64r3", "+mips64r3")
1999 .Case("-mips64r5", "+mips64r5")
2000 .Case("-mips64r6", "+mips64r6")
2001 .Default(nullptr);
2002 if (MipsTargetFeature)
2003 continue;
2004 }
2005
2006 if (Value == "-force_cpusubtype_ALL") {
2007 // Do nothing, this is the default and we don't support anything else.
2008 } else if (Value == "-L") {
2009 CmdArgs.push_back("-msave-temp-labels");
2010 } else if (Value == "--fatal-warnings") {
2011 CmdArgs.push_back("-massembler-fatal-warnings");
2012 } else if (Value == "--noexecstack") {
2013 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002014 } else if (Value.startswith("-compress-debug-sections") ||
2015 Value.startswith("--compress-debug-sections") ||
2016 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002017 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002018 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002019 } else if (Value == "-mrelax-relocations=yes" ||
2020 Value == "--mrelax-relocations=yes") {
2021 UseRelaxRelocations = true;
2022 } else if (Value == "-mrelax-relocations=no" ||
2023 Value == "--mrelax-relocations=no") {
2024 UseRelaxRelocations = false;
2025 } else if (Value.startswith("-I")) {
2026 CmdArgs.push_back(Value.data());
2027 // We need to consume the next argument if the current arg is a plain
2028 // -I. The next arg will be the include directory.
2029 if (Value == "-I")
2030 TakeNextArg = true;
2031 } else if (Value.startswith("-gdwarf-")) {
2032 // "-gdwarf-N" options are not cc1as options.
2033 unsigned DwarfVersion = DwarfVersionNum(Value);
2034 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2035 CmdArgs.push_back(Value.data());
2036 } else {
2037 RenderDebugEnablingArgs(Args, CmdArgs,
2038 codegenoptions::LimitedDebugInfo,
2039 DwarfVersion, llvm::DebuggerKind::Default);
2040 }
2041 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2042 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2043 // Do nothing, we'll validate it later.
2044 } else if (Value == "-defsym") {
2045 if (A->getNumValues() != 2) {
2046 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2047 break;
2048 }
2049 const char *S = A->getValue(1);
2050 auto Pair = StringRef(S).split('=');
2051 auto Sym = Pair.first;
2052 auto SVal = Pair.second;
2053
2054 if (Sym.empty() || SVal.empty()) {
2055 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2056 break;
2057 }
2058 int64_t IVal;
2059 if (SVal.getAsInteger(0, IVal)) {
2060 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2061 break;
2062 }
2063 CmdArgs.push_back(Value.data());
2064 TakeNextArg = true;
2065 } else {
2066 D.Diag(diag::err_drv_unsupported_option_argument)
2067 << A->getOption().getName() << Value;
2068 }
2069 }
2070 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002071 if (UseRelaxRelocations)
2072 CmdArgs.push_back("--mrelax-relocations");
2073 if (MipsTargetFeature != nullptr) {
2074 CmdArgs.push_back("-target-feature");
2075 CmdArgs.push_back(MipsTargetFeature);
2076 }
2077}
2078
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002079static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2080 bool OFastEnabled, const ArgList &Args,
2081 ArgStringList &CmdArgs) {
2082 // Handle various floating point optimization flags, mapping them to the
2083 // appropriate LLVM code generation flags. This is complicated by several
2084 // "umbrella" flags, so we do this by stepping through the flags incrementally
2085 // adjusting what we think is enabled/disabled, then at the end settting the
2086 // LLVM flags based on the final state.
2087 bool HonorINFs = true;
2088 bool HonorNaNs = true;
2089 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2090 bool MathErrno = TC.IsMathErrnoDefault();
2091 bool AssociativeMath = false;
2092 bool ReciprocalMath = false;
2093 bool SignedZeros = true;
2094 bool TrappingMath = true;
2095 StringRef DenormalFPMath = "";
2096 StringRef FPContract = "";
2097
2098 for (const Arg *A : Args) {
2099 switch (A->getOption().getID()) {
2100 // If this isn't an FP option skip the claim below
2101 default: continue;
2102
2103 // Options controlling individual features
2104 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2105 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2106 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2107 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2108 case options::OPT_fmath_errno: MathErrno = true; break;
2109 case options::OPT_fno_math_errno: MathErrno = false; break;
2110 case options::OPT_fassociative_math: AssociativeMath = true; break;
2111 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2112 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2113 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2114 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2115 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2116 case options::OPT_ftrapping_math: TrappingMath = true; break;
2117 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2118
2119 case options::OPT_fdenormal_fp_math_EQ:
2120 DenormalFPMath = A->getValue();
2121 break;
2122
2123 // Validate and pass through -fp-contract option.
2124 case options::OPT_ffp_contract: {
2125 StringRef Val = A->getValue();
2126 if (Val == "fast" || Val == "on" || Val == "off")
2127 FPContract = Val;
2128 else
2129 D.Diag(diag::err_drv_unsupported_option_argument)
2130 << A->getOption().getName() << Val;
2131 break;
2132 }
2133
2134 case options::OPT_ffinite_math_only:
2135 HonorINFs = false;
2136 HonorNaNs = false;
2137 break;
2138 case options::OPT_fno_finite_math_only:
2139 HonorINFs = true;
2140 HonorNaNs = true;
2141 break;
2142
2143 case options::OPT_funsafe_math_optimizations:
2144 AssociativeMath = true;
2145 ReciprocalMath = true;
2146 SignedZeros = false;
2147 TrappingMath = false;
2148 break;
2149 case options::OPT_fno_unsafe_math_optimizations:
2150 AssociativeMath = false;
2151 ReciprocalMath = false;
2152 SignedZeros = true;
2153 TrappingMath = true;
2154 // -fno_unsafe_math_optimizations restores default denormal handling
2155 DenormalFPMath = "";
2156 break;
2157
2158 case options::OPT_Ofast:
2159 // If -Ofast is the optimization level, then -ffast-math should be enabled
2160 if (!OFastEnabled)
2161 continue;
2162 LLVM_FALLTHROUGH;
2163 case options::OPT_ffast_math:
2164 HonorINFs = false;
2165 HonorNaNs = false;
2166 MathErrno = false;
2167 AssociativeMath = true;
2168 ReciprocalMath = true;
2169 SignedZeros = false;
2170 TrappingMath = false;
2171 // If fast-math is set then set the fp-contract mode to fast.
2172 FPContract = "fast";
2173 break;
2174 case options::OPT_fno_fast_math:
2175 HonorINFs = true;
2176 HonorNaNs = true;
2177 // Turning on -ffast-math (with either flag) removes the need for
2178 // MathErrno. However, turning *off* -ffast-math merely restores the
2179 // toolchain default (which may be false).
2180 MathErrno = TC.IsMathErrnoDefault();
2181 AssociativeMath = false;
2182 ReciprocalMath = false;
2183 SignedZeros = true;
2184 TrappingMath = true;
2185 // -fno_fast_math restores default denormal and fpcontract handling
2186 DenormalFPMath = "";
2187 FPContract = "";
2188 break;
2189 }
2190
2191 // If we handled this option claim it
2192 A->claim();
2193 }
2194
2195 if (!HonorINFs)
2196 CmdArgs.push_back("-menable-no-infs");
2197
2198 if (!HonorNaNs)
2199 CmdArgs.push_back("-menable-no-nans");
2200
2201 if (MathErrno)
2202 CmdArgs.push_back("-fmath-errno");
2203
2204 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2205 !TrappingMath)
2206 CmdArgs.push_back("-menable-unsafe-fp-math");
2207
2208 if (!SignedZeros)
2209 CmdArgs.push_back("-fno-signed-zeros");
2210
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002211 if (AssociativeMath && !SignedZeros && !TrappingMath)
2212 CmdArgs.push_back("-mreassociate");
2213
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002214 if (ReciprocalMath)
2215 CmdArgs.push_back("-freciprocal-math");
2216
2217 if (!TrappingMath)
2218 CmdArgs.push_back("-fno-trapping-math");
2219
2220 if (!DenormalFPMath.empty())
2221 CmdArgs.push_back(
2222 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2223
2224 if (!FPContract.empty())
2225 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2226
2227 ParseMRecip(D, Args, CmdArgs);
2228
2229 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2230 // individual features enabled by -ffast-math instead of the option itself as
2231 // that's consistent with gcc's behaviour.
2232 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2233 ReciprocalMath && !SignedZeros && !TrappingMath)
2234 CmdArgs.push_back("-ffast-math");
2235
2236 // Handle __FINITE_MATH_ONLY__ similarly.
2237 if (!HonorINFs && !HonorNaNs)
2238 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002239
2240 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2241 CmdArgs.push_back("-mfpmath");
2242 CmdArgs.push_back(A->getValue());
2243 }
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002244}
2245
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002246static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2247 const llvm::Triple &Triple,
2248 const InputInfo &Input) {
2249 // Enable region store model by default.
2250 CmdArgs.push_back("-analyzer-store=region");
2251
2252 // Treat blocks as analysis entry points.
2253 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2254
2255 CmdArgs.push_back("-analyzer-eagerly-assume");
2256
2257 // Add default argument set.
2258 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2259 CmdArgs.push_back("-analyzer-checker=core");
2260 CmdArgs.push_back("-analyzer-checker=apiModeling");
2261
2262 if (!Triple.isWindowsMSVCEnvironment()) {
2263 CmdArgs.push_back("-analyzer-checker=unix");
2264 } else {
2265 // Enable "unix" checkers that also work on Windows.
2266 CmdArgs.push_back("-analyzer-checker=unix.API");
2267 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2268 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2269 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2270 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2271 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2272 }
2273
2274 // Disable some unix checkers for PS4.
2275 if (Triple.isPS4CPU()) {
2276 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2277 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2278 }
2279
2280 if (Triple.isOSDarwin())
2281 CmdArgs.push_back("-analyzer-checker=osx");
2282
2283 CmdArgs.push_back("-analyzer-checker=deadcode");
2284
2285 if (types::isCXX(Input.getType()))
2286 CmdArgs.push_back("-analyzer-checker=cplusplus");
2287
2288 if (!Triple.isPS4CPU()) {
2289 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2290 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2291 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2292 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2293 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2294 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2295 }
2296
2297 // Default nullability checks.
2298 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2299 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2300 }
2301
2302 // Set the output format. The default is plist, for (lame) historical reasons.
2303 CmdArgs.push_back("-analyzer-output");
2304 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2305 CmdArgs.push_back(A->getValue());
2306 else
2307 CmdArgs.push_back("plist");
2308
2309 // Disable the presentation of standard compiler warnings when using
2310 // --analyze. We only want to show static analyzer diagnostics or frontend
2311 // errors.
2312 CmdArgs.push_back("-w");
2313
2314 // Add -Xanalyzer arguments when running as analyzer.
2315 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2316}
2317
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002318static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002319 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002320 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2321
2322 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2323 // doesn't even have a stack!
2324 if (EffectiveTriple.isNVPTX())
2325 return;
2326
2327 // -stack-protector=0 is default.
2328 unsigned StackProtectorLevel = 0;
2329 unsigned DefaultStackProtectorLevel =
2330 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2331
2332 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2333 options::OPT_fstack_protector_all,
2334 options::OPT_fstack_protector_strong,
2335 options::OPT_fstack_protector)) {
2336 if (A->getOption().matches(options::OPT_fstack_protector))
2337 StackProtectorLevel =
2338 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2339 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2340 StackProtectorLevel = LangOptions::SSPStrong;
2341 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2342 StackProtectorLevel = LangOptions::SSPReq;
2343 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002344 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002345 }
2346
2347 if (StackProtectorLevel) {
2348 CmdArgs.push_back("-stack-protector");
2349 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2350 }
2351
2352 // --param ssp-buffer-size=
2353 for (const Arg *A : Args.filtered(options::OPT__param)) {
2354 StringRef Str(A->getValue());
2355 if (Str.startswith("ssp-buffer-size=")) {
2356 if (StackProtectorLevel) {
2357 CmdArgs.push_back("-stack-protector-buffer-size");
2358 // FIXME: Verify the argument is a valid integer.
2359 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2360 }
2361 A->claim();
2362 }
2363 }
2364}
2365
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002366static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2367 const unsigned ForwardedArguments[] = {
2368 options::OPT_cl_opt_disable,
2369 options::OPT_cl_strict_aliasing,
2370 options::OPT_cl_single_precision_constant,
2371 options::OPT_cl_finite_math_only,
2372 options::OPT_cl_kernel_arg_info,
2373 options::OPT_cl_unsafe_math_optimizations,
2374 options::OPT_cl_fast_relaxed_math,
2375 options::OPT_cl_mad_enable,
2376 options::OPT_cl_no_signed_zeros,
2377 options::OPT_cl_denorms_are_zero,
2378 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2379 };
2380
2381 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2382 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2383 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2384 }
2385
2386 for (const auto &Arg : ForwardedArguments)
2387 if (const auto *A = Args.getLastArg(Arg))
2388 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2389}
2390
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002391static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2392 ArgStringList &CmdArgs) {
2393 bool ARCMTEnabled = false;
2394 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2395 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2396 options::OPT_ccc_arcmt_modify,
2397 options::OPT_ccc_arcmt_migrate)) {
2398 ARCMTEnabled = true;
2399 switch (A->getOption().getID()) {
2400 default: llvm_unreachable("missed a case");
2401 case options::OPT_ccc_arcmt_check:
2402 CmdArgs.push_back("-arcmt-check");
2403 break;
2404 case options::OPT_ccc_arcmt_modify:
2405 CmdArgs.push_back("-arcmt-modify");
2406 break;
2407 case options::OPT_ccc_arcmt_migrate:
2408 CmdArgs.push_back("-arcmt-migrate");
2409 CmdArgs.push_back("-mt-migrate-directory");
2410 CmdArgs.push_back(A->getValue());
2411
2412 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2413 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2414 break;
2415 }
2416 }
2417 } else {
2418 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2419 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2420 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2421 }
2422
2423 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2424 if (ARCMTEnabled)
2425 D.Diag(diag::err_drv_argument_not_allowed_with)
2426 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2427
2428 CmdArgs.push_back("-mt-migrate-directory");
2429 CmdArgs.push_back(A->getValue());
2430
2431 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2432 options::OPT_objcmt_migrate_subscripting,
2433 options::OPT_objcmt_migrate_property)) {
2434 // None specified, means enable them all.
2435 CmdArgs.push_back("-objcmt-migrate-literals");
2436 CmdArgs.push_back("-objcmt-migrate-subscripting");
2437 CmdArgs.push_back("-objcmt-migrate-property");
2438 } else {
2439 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2440 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2441 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2442 }
2443 } else {
2444 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2445 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2446 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2447 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2448 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2449 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2450 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2451 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2452 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2453 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2454 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2455 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2456 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2457 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2458 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2459 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2460 }
2461}
2462
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002463static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2464 const ArgList &Args, ArgStringList &CmdArgs) {
2465 // -fbuiltin is default unless -mkernel is used.
2466 bool UseBuiltins =
2467 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2468 !Args.hasArg(options::OPT_mkernel));
2469 if (!UseBuiltins)
2470 CmdArgs.push_back("-fno-builtin");
2471
2472 // -ffreestanding implies -fno-builtin.
2473 if (Args.hasArg(options::OPT_ffreestanding))
2474 UseBuiltins = false;
2475
2476 // Process the -fno-builtin-* options.
2477 for (const auto &Arg : Args) {
2478 const Option &O = Arg->getOption();
2479 if (!O.matches(options::OPT_fno_builtin_))
2480 continue;
2481
2482 Arg->claim();
2483
2484 // If -fno-builtin is specified, then there's no need to pass the option to
2485 // the frontend.
2486 if (!UseBuiltins)
2487 continue;
2488
2489 StringRef FuncName = Arg->getValue();
2490 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2491 }
2492
2493 // le32-specific flags:
2494 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2495 // by default.
2496 if (TC.getArch() == llvm::Triple::le32)
2497 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002498}
2499
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002500static void RenderModulesOptions(Compilation &C, const Driver &D,
2501 const ArgList &Args, const InputInfo &Input,
2502 const InputInfo &Output,
2503 ArgStringList &CmdArgs, bool &HaveModules) {
2504 // -fmodules enables the use of precompiled modules (off by default).
2505 // Users can pass -fno-cxx-modules to turn off modules support for
2506 // C++/Objective-C++ programs.
2507 bool HaveClangModules = false;
2508 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2509 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2510 options::OPT_fno_cxx_modules, true);
2511 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2512 CmdArgs.push_back("-fmodules");
2513 HaveClangModules = true;
2514 }
2515 }
2516
2517 HaveModules = HaveClangModules;
2518 if (Args.hasArg(options::OPT_fmodules_ts)) {
2519 CmdArgs.push_back("-fmodules-ts");
2520 HaveModules = true;
2521 }
2522
2523 // -fmodule-maps enables implicit reading of module map files. By default,
2524 // this is enabled if we are using Clang's flavor of precompiled modules.
2525 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2526 options::OPT_fno_implicit_module_maps, HaveClangModules))
2527 CmdArgs.push_back("-fimplicit-module-maps");
2528
2529 // -fmodules-decluse checks that modules used are declared so (off by default)
2530 if (Args.hasFlag(options::OPT_fmodules_decluse,
2531 options::OPT_fno_modules_decluse, false))
2532 CmdArgs.push_back("-fmodules-decluse");
2533
2534 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2535 // all #included headers are part of modules.
2536 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2537 options::OPT_fno_modules_strict_decluse, false))
2538 CmdArgs.push_back("-fmodules-strict-decluse");
2539
2540 // -fno-implicit-modules turns off implicitly compiling modules on demand.
2541 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2542 options::OPT_fno_implicit_modules, HaveClangModules)) {
2543 if (HaveModules)
2544 CmdArgs.push_back("-fno-implicit-modules");
2545 } else if (HaveModules) {
2546 // -fmodule-cache-path specifies where our implicitly-built module files
2547 // should be written.
2548 SmallString<128> Path;
2549 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2550 Path = A->getValue();
2551
2552 if (C.isForDiagnostics()) {
2553 // When generating crash reports, we want to emit the modules along with
2554 // the reproduction sources, so we ignore any provided module path.
2555 Path = Output.getFilename();
2556 llvm::sys::path::replace_extension(Path, ".cache");
2557 llvm::sys::path::append(Path, "modules");
2558 } else if (Path.empty()) {
2559 // No module path was provided: use the default.
2560 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
2561 llvm::sys::path::append(Path, "org.llvm.clang.");
2562 appendUserToPath(Path);
2563 llvm::sys::path::append(Path, "ModuleCache");
2564 }
2565
2566 const char Arg[] = "-fmodules-cache-path=";
2567 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2568 CmdArgs.push_back(Args.MakeArgString(Path));
2569 }
2570
2571 if (HaveModules) {
2572 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2573 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2574 CmdArgs.push_back(Args.MakeArgString(
2575 std::string("-fprebuilt-module-path=") + A->getValue()));
2576 A->claim();
2577 }
2578 }
2579
2580 // -fmodule-name specifies the module that is currently being built (or
2581 // used for header checking by -fmodule-maps).
2582 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2583
2584 // -fmodule-map-file can be used to specify files containing module
2585 // definitions.
2586 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2587
2588 // -fbuiltin-module-map can be used to load the clang
2589 // builtin headers modulemap file.
2590 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2591 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2592 llvm::sys::path::append(BuiltinModuleMap, "include");
2593 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2594 if (llvm::sys::fs::exists(BuiltinModuleMap))
2595 CmdArgs.push_back(
2596 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2597 }
2598
2599 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2600 // names to precompiled module files (the module is loaded only if used).
2601 // The -fmodule-file=<file> form can be used to unconditionally load
2602 // precompiled module files (whether used or not).
2603 if (HaveModules)
2604 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2605 else
2606 Args.ClaimAllArgs(options::OPT_fmodule_file);
2607
2608 // When building modules and generating crashdumps, we need to dump a module
2609 // dependency VFS alongside the output.
2610 if (HaveClangModules && C.isForDiagnostics()) {
2611 SmallString<128> VFSDir(Output.getFilename());
2612 llvm::sys::path::replace_extension(VFSDir, ".cache");
2613 // Add the cache directory as a temp so the crash diagnostics pick it up.
2614 C.addTempFile(Args.MakeArgString(VFSDir));
2615
2616 llvm::sys::path::append(VFSDir, "vfs");
2617 CmdArgs.push_back("-module-dependency-dir");
2618 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2619 }
2620
2621 if (HaveClangModules)
2622 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2623
2624 // Pass through all -fmodules-ignore-macro arguments.
2625 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2626 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2627 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2628
2629 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2630
2631 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2632 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2633 D.Diag(diag::err_drv_argument_not_allowed_with)
2634 << A->getAsString(Args) << "-fbuild-session-timestamp";
2635
2636 llvm::sys::fs::file_status Status;
2637 if (llvm::sys::fs::status(A->getValue(), Status))
2638 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2639 CmdArgs.push_back(
2640 Args.MakeArgString("-fbuild-session-timestamp=" +
2641 Twine((uint64_t)Status.getLastModificationTime()
2642 .time_since_epoch()
2643 .count())));
2644 }
2645
2646 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2647 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2648 options::OPT_fbuild_session_file))
2649 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2650
2651 Args.AddLastArg(CmdArgs,
2652 options::OPT_fmodules_validate_once_per_build_session);
2653 }
2654
2655 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
2656 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2657}
2658
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002659static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2660 ArgStringList &CmdArgs) {
2661 // -fsigned-char is default.
2662 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2663 options::OPT_fno_signed_char,
2664 options::OPT_funsigned_char,
2665 options::OPT_fno_unsigned_char)) {
2666 if (A->getOption().matches(options::OPT_funsigned_char) ||
2667 A->getOption().matches(options::OPT_fno_signed_char)) {
2668 CmdArgs.push_back("-fno-signed-char");
2669 }
2670 } else if (!isSignedCharDefault(T)) {
2671 CmdArgs.push_back("-fno-signed-char");
2672 }
2673
2674 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2675 options::OPT_fno_short_wchar)) {
2676 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2677 CmdArgs.push_back("-fwchar-type=short");
2678 CmdArgs.push_back("-fno-signed-wchar");
2679 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002680 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002681 CmdArgs.push_back("-fwchar-type=int");
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002682 if (IsARM && !(T.isOSWindows() || T.getOS() == llvm::Triple::NetBSD ||
2683 T.getOS() == llvm::Triple::OpenBSD))
2684 CmdArgs.push_back("-fno-signed-wchar");
2685 else
2686 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002687 }
2688 }
2689}
2690
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002691static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2692 const llvm::Triple &T, const ArgList &Args,
2693 ObjCRuntime &Runtime, bool InferCovariantReturns,
2694 const InputInfo &Input, ArgStringList &CmdArgs) {
2695 const llvm::Triple::ArchType Arch = TC.getArch();
2696
2697 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2698 // is the default. Except for deployment target of 10.5, next runtime is
2699 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2700 if (Runtime.isNonFragile()) {
2701 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2702 options::OPT_fno_objc_legacy_dispatch,
2703 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2704 if (TC.UseObjCMixedDispatch())
2705 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2706 else
2707 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2708 }
2709 }
2710
2711 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2712 // to do Array/Dictionary subscripting by default.
2713 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2714 !T.isMacOSXVersionLT(10, 7) &&
2715 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2716 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2717
2718 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2719 // NOTE: This logic is duplicated in ToolChains.cpp.
2720 if (isObjCAutoRefCount(Args)) {
2721 TC.CheckObjCARC();
2722
2723 CmdArgs.push_back("-fobjc-arc");
2724
2725 // FIXME: It seems like this entire block, and several around it should be
2726 // wrapped in isObjC, but for now we just use it here as this is where it
2727 // was being used previously.
2728 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2729 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2730 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2731 else
2732 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2733 }
2734
2735 // Allow the user to enable full exceptions code emission.
2736 // We default off for Objective-C, on for Objective-C++.
2737 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2738 options::OPT_fno_objc_arc_exceptions,
2739 /*default=*/types::isCXX(Input.getType())))
2740 CmdArgs.push_back("-fobjc-arc-exceptions");
2741 }
2742
2743 // Silence warning for full exception code emission options when explicitly
2744 // set to use no ARC.
2745 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2746 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2747 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2748 }
2749
2750 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2751 // rewriter.
2752 if (InferCovariantReturns)
2753 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2754
2755 // Pass down -fobjc-weak or -fno-objc-weak if present.
2756 if (types::isObjC(Input.getType())) {
2757 auto WeakArg =
2758 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2759 if (!WeakArg) {
2760 // nothing to do
2761 } else if (!Runtime.allowsWeak()) {
2762 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2763 D.Diag(diag::err_objc_weak_unsupported);
2764 } else {
2765 WeakArg->render(Args, CmdArgs);
2766 }
2767 }
2768}
2769
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002770static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2771 ArgStringList &CmdArgs) {
2772 bool CaretDefault = true;
2773 bool ColumnDefault = true;
2774
2775 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2776 options::OPT__SLASH_diagnostics_column,
2777 options::OPT__SLASH_diagnostics_caret)) {
2778 switch (A->getOption().getID()) {
2779 case options::OPT__SLASH_diagnostics_caret:
2780 CaretDefault = true;
2781 ColumnDefault = true;
2782 break;
2783 case options::OPT__SLASH_diagnostics_column:
2784 CaretDefault = false;
2785 ColumnDefault = true;
2786 break;
2787 case options::OPT__SLASH_diagnostics_classic:
2788 CaretDefault = false;
2789 ColumnDefault = false;
2790 break;
2791 }
2792 }
2793
2794 // -fcaret-diagnostics is default.
2795 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
2796 options::OPT_fno_caret_diagnostics, CaretDefault))
2797 CmdArgs.push_back("-fno-caret-diagnostics");
2798
2799 // -fdiagnostics-fixit-info is default, only pass non-default.
2800 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
2801 options::OPT_fno_diagnostics_fixit_info))
2802 CmdArgs.push_back("-fno-diagnostics-fixit-info");
2803
2804 // Enable -fdiagnostics-show-option by default.
2805 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
2806 options::OPT_fno_diagnostics_show_option))
2807 CmdArgs.push_back("-fdiagnostics-show-option");
2808
2809 if (const Arg *A =
2810 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
2811 CmdArgs.push_back("-fdiagnostics-show-category");
2812 CmdArgs.push_back(A->getValue());
2813 }
2814
2815 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
2816 options::OPT_fno_diagnostics_show_hotness, false))
2817 CmdArgs.push_back("-fdiagnostics-show-hotness");
2818
2819 if (const Arg *A =
2820 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2821 std::string Opt =
2822 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
2823 CmdArgs.push_back(Args.MakeArgString(Opt));
2824 }
2825
2826 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
2827 CmdArgs.push_back("-fdiagnostics-format");
2828 CmdArgs.push_back(A->getValue());
2829 }
2830
2831 if (const Arg *A = Args.getLastArg(
2832 options::OPT_fdiagnostics_show_note_include_stack,
2833 options::OPT_fno_diagnostics_show_note_include_stack)) {
2834 const Option &O = A->getOption();
2835 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
2836 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
2837 else
2838 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
2839 }
2840
2841 // Color diagnostics are parsed by the driver directly from argv and later
2842 // re-parsed to construct this job; claim any possible color diagnostic here
2843 // to avoid warn_drv_unused_argument and diagnose bad
2844 // OPT_fdiagnostics_color_EQ values.
2845 for (const Arg *A : Args) {
2846 const Option &O = A->getOption();
2847 if (!O.matches(options::OPT_fcolor_diagnostics) &&
2848 !O.matches(options::OPT_fdiagnostics_color) &&
2849 !O.matches(options::OPT_fno_color_diagnostics) &&
2850 !O.matches(options::OPT_fno_diagnostics_color) &&
2851 !O.matches(options::OPT_fdiagnostics_color_EQ))
2852 continue;
2853
2854 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2855 StringRef Value(A->getValue());
2856 if (Value != "always" && Value != "never" && Value != "auto")
2857 D.Diag(diag::err_drv_clang_unsupported)
2858 << ("-fdiagnostics-color=" + Value).str();
2859 }
2860 A->claim();
2861 }
2862
2863 if (D.getDiags().getDiagnosticOptions().ShowColors)
2864 CmdArgs.push_back("-fcolor-diagnostics");
2865
2866 if (Args.hasArg(options::OPT_fansi_escape_codes))
2867 CmdArgs.push_back("-fansi-escape-codes");
2868
2869 if (!Args.hasFlag(options::OPT_fshow_source_location,
2870 options::OPT_fno_show_source_location))
2871 CmdArgs.push_back("-fno-show-source-location");
2872
2873 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
2874 CmdArgs.push_back("-fdiagnostics-absolute-paths");
2875
2876 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
2877 ColumnDefault))
2878 CmdArgs.push_back("-fno-show-column");
2879
2880 if (!Args.hasFlag(options::OPT_fspell_checking,
2881 options::OPT_fno_spell_checking))
2882 CmdArgs.push_back("-fno-spell-checking");
2883}
2884
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002885static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
2886 const llvm::Triple &T, const ArgList &Args,
2887 bool EmitCodeView, bool IsWindowsMSVC,
2888 ArgStringList &CmdArgs,
2889 codegenoptions::DebugInfoKind &DebugInfoKind,
2890 const Arg *&SplitDWARFArg) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002891 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
2892 options::OPT_fno_debug_info_for_profiling, false))
2893 CmdArgs.push_back("-fdebug-info-for-profiling");
2894
2895 // The 'g' groups options involve a somewhat intricate sequence of decisions
2896 // about what to pass from the driver to the frontend, but by the time they
2897 // reach cc1 they've been factored into three well-defined orthogonal choices:
2898 // * what level of debug info to generate
2899 // * what dwarf version to write
2900 // * what debugger tuning to use
2901 // This avoids having to monkey around further in cc1 other than to disable
2902 // codeview if not running in a Windows environment. Perhaps even that
2903 // decision should be made in the driver as well though.
2904 unsigned DWARFVersion = 0;
2905 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
2906
2907 bool SplitDWARFInlining =
2908 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
2909 options::OPT_fno_split_dwarf_inlining, true);
2910
2911 Args.ClaimAllArgs(options::OPT_g_Group);
2912
2913 SplitDWARFArg = Args.getLastArg(options::OPT_gsplit_dwarf);
2914
2915 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
2916 // If the last option explicitly specified a debug-info level, use it.
2917 if (A->getOption().matches(options::OPT_gN_Group)) {
2918 DebugInfoKind = DebugLevelToInfoKind(*A);
2919 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
2920 // But -gsplit-dwarf is not a g_group option, hence we have to check the
2921 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
2922 // This gets a bit more complicated if you've disabled inline info in the
2923 // skeleton CUs (SplitDWARFInlining) - then there's value in composing
2924 // split-dwarf and line-tables-only, so let those compose naturally in
2925 // that case.
2926 // And if you just turned off debug info, (-gsplit-dwarf -g0) - do that.
2927 if (SplitDWARFArg) {
2928 if (A->getIndex() > SplitDWARFArg->getIndex()) {
2929 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
2930 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
2931 SplitDWARFInlining))
2932 SplitDWARFArg = nullptr;
2933 } else if (SplitDWARFInlining)
2934 DebugInfoKind = codegenoptions::NoDebugInfo;
2935 }
2936 } else {
2937 // For any other 'g' option, use Limited.
2938 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2939 }
2940 }
2941
2942 // If a debugger tuning argument appeared, remember it.
2943 if (const Arg *A =
2944 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
2945 if (A->getOption().matches(options::OPT_glldb))
2946 DebuggerTuning = llvm::DebuggerKind::LLDB;
2947 else if (A->getOption().matches(options::OPT_gsce))
2948 DebuggerTuning = llvm::DebuggerKind::SCE;
2949 else
2950 DebuggerTuning = llvm::DebuggerKind::GDB;
2951 }
2952
2953 // If a -gdwarf argument appeared, remember it.
2954 if (const Arg *A =
2955 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2956 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
2957 DWARFVersion = DwarfVersionNum(A->getSpelling());
2958
2959 // Forward -gcodeview. EmitCodeView might have been set by CL-compatibility
2960 // argument parsing.
2961 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
2962 // DWARFVersion remains at 0 if no explicit choice was made.
2963 CmdArgs.push_back("-gcodeview");
2964 } else if (DWARFVersion == 0 &&
2965 DebugInfoKind != codegenoptions::NoDebugInfo) {
2966 DWARFVersion = TC.GetDefaultDwarfVersion();
2967 }
2968
2969 // We ignore flag -gstrict-dwarf for now.
2970 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
2971 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2972
Paul Robinsona8280812017-09-29 21:25:07 +00002973 // Column info is included by default for everything except SCE and CodeView.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002974 // Clang doesn't track end columns, just starting columns, which, in theory,
2975 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2976 // debuggers don't handle missing end columns well, so it's better not to
2977 // include any column info.
2978 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Paul Robinsona8280812017-09-29 21:25:07 +00002979 /*Default=*/!(IsWindowsMSVC && EmitCodeView) &&
2980 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00002981 CmdArgs.push_back("-dwarf-column-info");
2982
2983 // FIXME: Move backend command line options to the module.
2984 // If -gline-tables-only is the last option it wins.
2985 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2986 Args.hasArg(options::OPT_gmodules)) {
2987 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2988 CmdArgs.push_back("-dwarf-ext-refs");
2989 CmdArgs.push_back("-fmodule-format=obj");
2990 }
2991
2992 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2993 // splitting and extraction.
2994 // FIXME: Currently only works on Linux.
2995 if (T.isOSLinux()) {
2996 if (!SplitDWARFInlining)
2997 CmdArgs.push_back("-fno-split-dwarf-inlining");
2998
2999 if (SplitDWARFArg) {
3000 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3001 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3002 CmdArgs.push_back("-enable-split-dwarf");
3003 }
3004 }
3005
3006 // After we've dealt with all combinations of things that could
3007 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3008 // figure out if we need to "upgrade" it to standalone debug info.
3009 // We parse these two '-f' options whether or not they will be used,
3010 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3011 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3012 options::OPT_fno_standalone_debug,
3013 TC.GetDefaultStandaloneDebug());
3014 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3015 DebugInfoKind = codegenoptions::FullDebugInfo;
3016
3017 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3018 DebuggerTuning);
3019
3020 // -fdebug-macro turns on macro debug info generation.
3021 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3022 false))
3023 CmdArgs.push_back("-debug-info-macro");
3024
3025 // -ggnu-pubnames turns on gnu style pubnames in the backend.
Peter Collingbourneb52e2362017-09-12 21:50:41 +00003026 if (Args.hasArg(options::OPT_ggnu_pubnames))
3027 CmdArgs.push_back("-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003028
3029 // -gdwarf-aranges turns on the emission of the aranges section in the
3030 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003031 // Always enabled for SCE tuning.
3032 if (Args.hasArg(options::OPT_gdwarf_aranges) ||
3033 DebuggerTuning == llvm::DebuggerKind::SCE) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003034 CmdArgs.push_back("-backend-option");
3035 CmdArgs.push_back("-generate-arange-section");
3036 }
3037
3038 if (Args.hasFlag(options::OPT_fdebug_types_section,
3039 options::OPT_fno_debug_types_section, false)) {
3040 CmdArgs.push_back("-backend-option");
3041 CmdArgs.push_back("-generate-type-units");
3042 }
3043
Paul Robinson1787f812017-09-28 18:37:02 +00003044 // Decide how to render forward declarations of template instantiations.
3045 // SCE wants full descriptions, others just get them in the name.
3046 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3047 CmdArgs.push_back("-debug-forward-template-params");
3048
Paul Robinsona8280812017-09-29 21:25:07 +00003049 // Do we need to explicitly import anonymous namespaces into the parent scope?
3050 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3051 CmdArgs.push_back("-dwarf-explicit-import");
3052
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003053 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
3054}
3055
David L. Jonesf561aba2017-03-08 01:02:16 +00003056void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3057 const InputInfo &Output, const InputInfoList &Inputs,
3058 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003059 const llvm::Triple &RawTriple = getToolChain().getTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003060 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
3061 const std::string &TripleStr = Triple.getTriple();
3062
3063 bool KernelOrKext =
3064 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3065 const Driver &D = getToolChain().getDriver();
3066 ArgStringList CmdArgs;
3067
3068 // Check number of inputs for sanity. We need at least one input.
3069 assert(Inputs.size() >= 1 && "Must have at least one input.");
3070 const InputInfo &Input = Inputs[0];
3071 // CUDA compilation may have multiple inputs (source file + results of
3072 // device-side compilations). OpenMP device jobs also take the host IR as a
3073 // second input. All other jobs are expected to have exactly one
3074 // input.
3075 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3076 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3077 assert((IsCuda || (IsOpenMPDevice && Inputs.size() == 2) ||
3078 Inputs.size() == 1) &&
3079 "Unable to handle multiple inputs.");
3080
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00003081 const llvm::Triple *AuxTriple =
3082 IsCuda ? getToolChain().getAuxTriple() : nullptr;
3083
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003084 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3085 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3086 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003087 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003088
3089 // Adjust IsWindowsXYZ for CUDA compilations. Even when compiling in device
3090 // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
3091 // pass Windows-specific flags to cc1.
3092 if (IsCuda) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003093 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3094 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3095 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3096 }
3097
3098 // C++ is not supported for IAMCU.
3099 if (IsIAMCU && types::isCXX(Input.getType()))
3100 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3101
3102 // Invoke ourselves in -cc1 mode.
3103 //
3104 // FIXME: Implement custom jobs for internal actions.
3105 CmdArgs.push_back("-cc1");
3106
3107 // Add the "effective" target triple.
3108 CmdArgs.push_back("-triple");
3109 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3110
3111 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3112 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3113 Args.ClaimAllArgs(options::OPT_MJ);
3114 }
3115
3116 if (IsCuda) {
3117 // We have to pass the triple of the host if compiling for a CUDA device and
3118 // vice-versa.
3119 std::string NormalizedTriple;
3120 if (JA.isDeviceOffloading(Action::OFK_Cuda))
3121 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3122 ->getTriple()
3123 .normalize();
3124 else
3125 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3126 ->getTriple()
3127 .normalize();
3128
3129 CmdArgs.push_back("-aux-triple");
3130 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3131 }
3132
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003133 if (IsOpenMPDevice) {
3134 // We have to pass the triple of the host if compiling for an OpenMP device.
3135 std::string NormalizedTriple =
3136 C.getSingleOffloadToolChain<Action::OFK_Host>()
3137 ->getTriple()
3138 .normalize();
3139 CmdArgs.push_back("-aux-triple");
3140 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3141 }
3142
David L. Jonesf561aba2017-03-08 01:02:16 +00003143 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3144 Triple.getArch() == llvm::Triple::thumb)) {
3145 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3146 unsigned Version;
3147 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3148 if (Version < 7)
3149 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3150 << TripleStr;
3151 }
3152
3153 // Push all default warning arguments that are specific to
3154 // the given target. These come before user provided warning options
3155 // are provided.
3156 getToolChain().addClangWarningOptions(CmdArgs);
3157
3158 // Select the appropriate action.
3159 RewriteKind rewriteKind = RK_None;
3160
3161 if (isa<AnalyzeJobAction>(JA)) {
3162 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3163 CmdArgs.push_back("-analyze");
3164 } else if (isa<MigrateJobAction>(JA)) {
3165 CmdArgs.push_back("-migrate");
3166 } else if (isa<PreprocessJobAction>(JA)) {
3167 if (Output.getType() == types::TY_Dependencies)
3168 CmdArgs.push_back("-Eonly");
3169 else {
3170 CmdArgs.push_back("-E");
3171 if (Args.hasArg(options::OPT_rewrite_objc) &&
3172 !Args.hasArg(options::OPT_g_Group))
3173 CmdArgs.push_back("-P");
3174 }
3175 } else if (isa<AssembleJobAction>(JA)) {
3176 CmdArgs.push_back("-emit-obj");
3177
3178 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3179
3180 // Also ignore explicit -force_cpusubtype_ALL option.
3181 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3182 } else if (isa<PrecompileJobAction>(JA)) {
3183 // Use PCH if the user requested it.
3184 bool UsePCH = D.CCCUsePCH;
3185
3186 if (JA.getType() == types::TY_Nothing)
3187 CmdArgs.push_back("-fsyntax-only");
3188 else if (JA.getType() == types::TY_ModuleFile)
3189 CmdArgs.push_back("-emit-module-interface");
3190 else if (UsePCH)
3191 CmdArgs.push_back("-emit-pch");
3192 else
3193 CmdArgs.push_back("-emit-pth");
3194 } else if (isa<VerifyPCHJobAction>(JA)) {
3195 CmdArgs.push_back("-verify-pch");
3196 } else {
3197 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3198 "Invalid action for clang tool.");
3199 if (JA.getType() == types::TY_Nothing) {
3200 CmdArgs.push_back("-fsyntax-only");
3201 } else if (JA.getType() == types::TY_LLVM_IR ||
3202 JA.getType() == types::TY_LTO_IR) {
3203 CmdArgs.push_back("-emit-llvm");
3204 } else if (JA.getType() == types::TY_LLVM_BC ||
3205 JA.getType() == types::TY_LTO_BC) {
3206 CmdArgs.push_back("-emit-llvm-bc");
3207 } else if (JA.getType() == types::TY_PP_Asm) {
3208 CmdArgs.push_back("-S");
3209 } else if (JA.getType() == types::TY_AST) {
3210 CmdArgs.push_back("-emit-pch");
3211 } else if (JA.getType() == types::TY_ModuleFile) {
3212 CmdArgs.push_back("-module-file-info");
3213 } else if (JA.getType() == types::TY_RewrittenObjC) {
3214 CmdArgs.push_back("-rewrite-objc");
3215 rewriteKind = RK_NonFragile;
3216 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3217 CmdArgs.push_back("-rewrite-objc");
3218 rewriteKind = RK_Fragile;
3219 } else {
3220 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3221 }
3222
3223 // Preserve use-list order by default when emitting bitcode, so that
3224 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3225 // same result as running passes here. For LTO, we don't need to preserve
3226 // the use-list order, since serialization to bitcode is part of the flow.
3227 if (JA.getType() == types::TY_LLVM_BC)
3228 CmdArgs.push_back("-emit-llvm-uselists");
3229
3230 if (D.isUsingLTO()) {
3231 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3232
Paul Robinsond23f2a82017-07-13 21:25:47 +00003233 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3234 // does not support LTO unit features (CFI, whole program vtable opt)
3235 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003236 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003237 D.getLTOMode() == LTOK_Full)
3238 CmdArgs.push_back("-flto-unit");
3239 }
3240 }
3241
3242 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3243 if (!types::isLLVMIR(Input.getType()))
3244 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3245 << "-x ir";
3246 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3247 }
3248
3249 // Embed-bitcode option.
3250 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3251 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3252 // Add flags implied by -fembed-bitcode.
3253 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3254 // Disable all llvm IR level optimizations.
3255 CmdArgs.push_back("-disable-llvm-passes");
3256 }
3257 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3258 CmdArgs.push_back("-fembed-bitcode=marker");
3259
3260 // We normally speed up the clang process a bit by skipping destructors at
3261 // exit, but when we're generating diagnostics we can rely on some of the
3262 // cleanup.
3263 if (!C.isForDiagnostics())
3264 CmdArgs.push_back("-disable-free");
3265
3266// Disable the verification pass in -asserts builds.
3267#ifdef NDEBUG
3268 CmdArgs.push_back("-disable-llvm-verifier");
3269 // Discard LLVM value names in -asserts builds.
3270 CmdArgs.push_back("-discard-value-names");
3271#endif
3272
3273 // Set the main file name, so that debug info works even with
3274 // -save-temps.
3275 CmdArgs.push_back("-main-file-name");
3276 CmdArgs.push_back(getBaseInputName(Args, Input));
3277
3278 // Some flags which affect the language (via preprocessor
3279 // defines).
3280 if (Args.hasArg(options::OPT_static))
3281 CmdArgs.push_back("-static-define");
3282
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003283 if (isa<AnalyzeJobAction>(JA))
3284 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003285
3286 CheckCodeGenerationOptions(D, Args);
3287
3288 llvm::Reloc::Model RelocationModel;
3289 unsigned PICLevel;
3290 bool IsPIE;
3291 std::tie(RelocationModel, PICLevel, IsPIE) =
3292 ParsePICArgs(getToolChain(), Args);
3293
3294 const char *RMName = RelocationModelName(RelocationModel);
3295
3296 if ((RelocationModel == llvm::Reloc::ROPI ||
3297 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3298 types::isCXX(Input.getType()) &&
3299 !Args.hasArg(options::OPT_fallow_unsupported))
3300 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3301
3302 if (RMName) {
3303 CmdArgs.push_back("-mrelocation-model");
3304 CmdArgs.push_back(RMName);
3305 }
3306 if (PICLevel > 0) {
3307 CmdArgs.push_back("-pic-level");
3308 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3309 if (IsPIE)
3310 CmdArgs.push_back("-pic-is-pie");
3311 }
3312
3313 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3314 CmdArgs.push_back("-meabi");
3315 CmdArgs.push_back(A->getValue());
3316 }
3317
3318 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003319 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3320 if (!getToolChain().isThreadModelSupported(A->getValue()))
3321 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3322 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003323 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003324 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003325 else
3326 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3327
3328 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3329
3330 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3331 options::OPT_fno_merge_all_constants))
3332 CmdArgs.push_back("-fno-merge-all-constants");
3333
3334 // LLVM Code Generator Options.
3335
3336 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3337 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3338 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3339 options::OPT_frewrite_map_file_EQ)) {
3340 StringRef Map = A->getValue();
3341 if (!llvm::sys::fs::exists(Map)) {
3342 D.Diag(diag::err_drv_no_such_file) << Map;
3343 } else {
3344 CmdArgs.push_back("-frewrite-map-file");
3345 CmdArgs.push_back(A->getValue());
3346 A->claim();
3347 }
3348 }
3349 }
3350
3351 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3352 StringRef v = A->getValue();
3353 CmdArgs.push_back("-mllvm");
3354 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3355 A->claim();
3356 }
3357
3358 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3359 true))
3360 CmdArgs.push_back("-fno-jump-tables");
3361
Dehao Chen5e97f232017-08-24 21:37:33 +00003362 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3363 options::OPT_fno_profile_sample_accurate, false))
3364 CmdArgs.push_back("-fprofile-sample-accurate");
3365
David L. Jonesf561aba2017-03-08 01:02:16 +00003366 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3367 options::OPT_fno_preserve_as_comments, true))
3368 CmdArgs.push_back("-fno-preserve-as-comments");
3369
3370 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3371 CmdArgs.push_back("-mregparm");
3372 CmdArgs.push_back(A->getValue());
3373 }
3374
3375 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3376 options::OPT_freg_struct_return)) {
3377 if (getToolChain().getArch() != llvm::Triple::x86) {
3378 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003379 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003380 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3381 CmdArgs.push_back("-fpcc-struct-return");
3382 } else {
3383 assert(A->getOption().matches(options::OPT_freg_struct_return));
3384 CmdArgs.push_back("-freg-struct-return");
3385 }
3386 }
3387
3388 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3389 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3390
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003391 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003392 CmdArgs.push_back("-mdisable-fp-elim");
3393 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3394 options::OPT_fno_zero_initialized_in_bss))
3395 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3396
3397 bool OFastEnabled = isOptimizationLevelFast(Args);
3398 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3399 // enabled. This alias option is being used to simplify the hasFlag logic.
3400 OptSpecifier StrictAliasingAliasOption =
3401 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3402 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3403 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003404 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003405 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3406 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3407 CmdArgs.push_back("-relaxed-aliasing");
3408 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3409 options::OPT_fno_struct_path_tbaa))
3410 CmdArgs.push_back("-no-struct-path-tbaa");
3411 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3412 false))
3413 CmdArgs.push_back("-fstrict-enums");
3414 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3415 true))
3416 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003417 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3418 options::OPT_fno_allow_editor_placeholders, false))
3419 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003420 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3421 options::OPT_fno_strict_vtable_pointers,
3422 false))
3423 CmdArgs.push_back("-fstrict-vtable-pointers");
3424 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3425 options::OPT_fno_optimize_sibling_calls))
3426 CmdArgs.push_back("-mdisable-tail-calls");
3427
Wei Mi9b3d6272017-10-16 16:50:27 +00003428 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3429 options::OPT_fno_fine_grained_bitfield_accesses);
3430
David L. Jonesf561aba2017-03-08 01:02:16 +00003431 // Handle segmented stacks.
3432 if (Args.hasArg(options::OPT_fsplit_stack))
3433 CmdArgs.push_back("-split-stacks");
3434
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00003435 RenderFloatingPointOptions(getToolChain(), D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003436
3437 // Decide whether to use verbose asm. Verbose assembly is the default on
3438 // toolchains which have the integrated assembler on by default.
3439 bool IsIntegratedAssemblerDefault =
3440 getToolChain().IsIntegratedAssemblerDefault();
3441 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3442 IsIntegratedAssemblerDefault) ||
3443 Args.hasArg(options::OPT_dA))
3444 CmdArgs.push_back("-masm-verbose");
3445
3446 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3447 IsIntegratedAssemblerDefault))
3448 CmdArgs.push_back("-no-integrated-as");
3449
3450 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3451 CmdArgs.push_back("-mdebug-pass");
3452 CmdArgs.push_back("Structure");
3453 }
3454 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3455 CmdArgs.push_back("-mdebug-pass");
3456 CmdArgs.push_back("Arguments");
3457 }
3458
3459 // Enable -mconstructor-aliases except on darwin, where we have to work around
3460 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3461 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003462 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00003463 CmdArgs.push_back("-mconstructor-aliases");
3464
3465 // Darwin's kernel doesn't support guard variables; just die if we
3466 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003467 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00003468 CmdArgs.push_back("-fforbid-guard-variables");
3469
3470 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3471 false)) {
3472 CmdArgs.push_back("-mms-bitfields");
3473 }
3474
3475 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
3476 options::OPT_mno_pie_copy_relocations,
3477 false)) {
3478 CmdArgs.push_back("-mpie-copy-relocations");
3479 }
3480
Sriraman Tallam5c651482017-11-07 19:37:51 +00003481 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
3482 CmdArgs.push_back("-fno-plt");
3483 }
3484
Vedant Kumardf502592017-09-12 22:51:53 +00003485 // -fhosted is default.
3486 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
3487 // use Freestanding.
3488 bool Freestanding =
3489 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3490 KernelOrKext;
3491 if (Freestanding)
3492 CmdArgs.push_back("-ffreestanding");
3493
David L. Jonesf561aba2017-03-08 01:02:16 +00003494 // This is a coarse approximation of what llvm-gcc actually does, both
3495 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3496 // complicated ways.
3497 bool AsynchronousUnwindTables =
3498 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3499 options::OPT_fno_asynchronous_unwind_tables,
Akira Hatanakab72e35a2017-08-03 23:55:42 +00003500 (getToolChain().IsUnwindTablesDefault(Args) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003501 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00003502 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00003503 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3504 AsynchronousUnwindTables))
3505 CmdArgs.push_back("-munwind-tables");
3506
Gheorghe-Teodor Berceaf0f29602017-07-06 16:22:21 +00003507 getToolChain().addClangTargetOptions(Args, CmdArgs,
3508 JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00003509
3510 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3511 CmdArgs.push_back("-mlimit-float-precision");
3512 CmdArgs.push_back(A->getValue());
3513 }
3514
3515 // FIXME: Handle -mtune=.
3516 (void)Args.hasArg(options::OPT_mtune_EQ);
3517
3518 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3519 CmdArgs.push_back("-mcode-model");
3520 CmdArgs.push_back(A->getValue());
3521 }
3522
3523 // Add the target cpu
3524 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3525 if (!CPU.empty()) {
3526 CmdArgs.push_back("-target-cpu");
3527 CmdArgs.push_back(Args.MakeArgString(CPU));
3528 }
3529
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00003530 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003531
David L. Jonesf561aba2017-03-08 01:02:16 +00003532 // These two are potentially updated by AddClangCLArgs.
3533 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
3534 bool EmitCodeView = false;
3535
3536 // Add clang-cl arguments.
3537 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003538 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00003539 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
3540
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003541 const Arg *SplitDWARFArg = nullptr;
3542 RenderDebugOptions(getToolChain(), D, RawTriple, Args, EmitCodeView,
3543 IsWindowsMSVC, CmdArgs, DebugInfoKind, SplitDWARFArg);
3544
3545 // Add the split debug info name to the command lines here so we
3546 // can propagate it to the backend.
3547 bool SplitDWARF = SplitDWARFArg && RawTriple.isOSLinux() &&
3548 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
3549 isa<BackendJobAction>(JA));
3550 const char *SplitDWARFOut;
3551 if (SplitDWARF) {
3552 CmdArgs.push_back("-split-dwarf-file");
3553 SplitDWARFOut = SplitDebugName(Args, Input);
3554 CmdArgs.push_back(SplitDWARFOut);
3555 }
3556
David L. Jonesf561aba2017-03-08 01:02:16 +00003557 // Pass the linker version in use.
3558 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
3559 CmdArgs.push_back("-target-linker-version");
3560 CmdArgs.push_back(A->getValue());
3561 }
3562
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003563 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003564 CmdArgs.push_back("-momit-leaf-frame-pointer");
3565
3566 // Explicitly error on some things we know we don't support and can't just
3567 // ignore.
3568 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
3569 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003570 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
David L. Jonesf561aba2017-03-08 01:02:16 +00003571 getToolChain().getArch() == llvm::Triple::x86) {
3572 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
3573 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
3574 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
3575 << Unsupported->getOption().getName();
3576 }
Eric Christopher758aad72017-03-21 22:06:18 +00003577 // The faltivec option has been superseded by the maltivec option.
3578 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
3579 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3580 << Unsupported->getOption().getName()
3581 << "please use -maltivec and include altivec.h explicitly";
3582 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
3583 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
3584 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00003585 }
3586
3587 Args.AddAllArgs(CmdArgs, options::OPT_v);
3588 Args.AddLastArg(CmdArgs, options::OPT_H);
3589 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
3590 CmdArgs.push_back("-header-include-file");
3591 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
3592 : "-");
3593 }
3594 Args.AddLastArg(CmdArgs, options::OPT_P);
3595 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
3596
3597 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
3598 CmdArgs.push_back("-diagnostic-log-file");
3599 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
3600 : "-");
3601 }
3602
David L. Jonesf561aba2017-03-08 01:02:16 +00003603 bool UseSeparateSections = isUseSeparateSections(Triple);
3604
3605 if (Args.hasFlag(options::OPT_ffunction_sections,
3606 options::OPT_fno_function_sections, UseSeparateSections)) {
3607 CmdArgs.push_back("-ffunction-sections");
3608 }
3609
3610 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
3611 UseSeparateSections)) {
3612 CmdArgs.push_back("-fdata-sections");
3613 }
3614
3615 if (!Args.hasFlag(options::OPT_funique_section_names,
3616 options::OPT_fno_unique_section_names, true))
3617 CmdArgs.push_back("-fno-unique-section-names");
3618
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00003619 if (auto *A = Args.getLastArg(
3620 options::OPT_finstrument_functions,
3621 options::OPT_finstrument_functions_after_inlining,
3622 options::OPT_finstrument_function_entry_bare))
3623 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003624
David L. Jonesf561aba2017-03-08 01:02:16 +00003625 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
3626
Richard Smithf667ad52017-08-26 01:04:35 +00003627 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
3628 ABICompatArg->render(Args, CmdArgs);
3629
David L. Jonesf561aba2017-03-08 01:02:16 +00003630 // Add runtime flag for PS4 when PGO or Coverage are enabled.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003631 if (RawTriple.isPS4CPU())
David L. Jonesf561aba2017-03-08 01:02:16 +00003632 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
3633
3634 // Pass options for controlling the default header search paths.
3635 if (Args.hasArg(options::OPT_nostdinc)) {
3636 CmdArgs.push_back("-nostdsysteminc");
3637 CmdArgs.push_back("-nobuiltininc");
3638 } else {
3639 if (Args.hasArg(options::OPT_nostdlibinc))
3640 CmdArgs.push_back("-nostdsysteminc");
3641 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
3642 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
3643 }
3644
3645 // Pass the path to compiler resource files.
3646 CmdArgs.push_back("-resource-dir");
3647 CmdArgs.push_back(D.ResourceDir.c_str());
3648
3649 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
3650
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00003651 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003652
3653 // Add preprocessing options like -I, -D, etc. if we are using the
3654 // preprocessor.
3655 //
3656 // FIXME: Support -fpreprocessed
3657 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
3658 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
3659
3660 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
3661 // that "The compiler can only warn and ignore the option if not recognized".
3662 // When building with ccache, it will pass -D options to clang even on
3663 // preprocessed inputs and configure concludes that -fPIC is not supported.
3664 Args.ClaimAllArgs(options::OPT_D);
3665
3666 // Manually translate -O4 to -O3; let clang reject others.
3667 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3668 if (A->getOption().matches(options::OPT_O4)) {
3669 CmdArgs.push_back("-O3");
3670 D.Diag(diag::warn_O4_is_O3);
3671 } else {
3672 A->render(Args, CmdArgs);
3673 }
3674 }
3675
3676 // Warn about ignored options to clang.
3677 for (const Arg *A :
3678 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
3679 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
3680 A->claim();
3681 }
3682
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00003683 for (const Arg *A :
3684 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
3685 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
3686 A->claim();
3687 }
3688
David L. Jonesf561aba2017-03-08 01:02:16 +00003689 claimNoWarnArgs(Args);
3690
3691 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
3692
3693 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
3694 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
3695 CmdArgs.push_back("-pedantic");
3696 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
3697 Args.AddLastArg(CmdArgs, options::OPT_w);
3698
3699 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
3700 // (-ansi is equivalent to -std=c89 or -std=c++98).
3701 //
3702 // If a std is supplied, only add -trigraphs if it follows the
3703 // option.
3704 bool ImplyVCPPCXXVer = false;
3705 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
3706 if (Std->getOption().matches(options::OPT_ansi))
3707 if (types::isCXX(InputType))
3708 CmdArgs.push_back("-std=c++98");
3709 else
3710 CmdArgs.push_back("-std=c89");
3711 else
3712 Std->render(Args, CmdArgs);
3713
3714 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3715 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3716 options::OPT_ftrigraphs,
3717 options::OPT_fno_trigraphs))
3718 if (A != Std)
3719 A->render(Args, CmdArgs);
3720 } else {
3721 // Honor -std-default.
3722 //
3723 // FIXME: Clang doesn't correctly handle -std= when the input language
3724 // doesn't match. For the time being just ignore this for C++ inputs;
3725 // eventually we want to do all the standard defaulting here instead of
3726 // splitting it between the driver and clang -cc1.
3727 if (!types::isCXX(InputType))
3728 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3729 /*Joined=*/true);
3730 else if (IsWindowsMSVC)
3731 ImplyVCPPCXXVer = true;
3732
3733 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3734 options::OPT_fno_trigraphs);
3735 }
3736
3737 // GCC's behavior for -Wwrite-strings is a bit strange:
3738 // * In C, this "warning flag" changes the types of string literals from
3739 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3740 // for the discarded qualifier.
3741 // * In C++, this is just a normal warning flag.
3742 //
3743 // Implementing this warning correctly in C is hard, so we follow GCC's
3744 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3745 // a non-const char* in C, rather than using this crude hack.
3746 if (!types::isCXX(InputType)) {
3747 // FIXME: This should behave just like a warning flag, and thus should also
3748 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3749 Arg *WriteStrings =
3750 Args.getLastArg(options::OPT_Wwrite_strings,
3751 options::OPT_Wno_write_strings, options::OPT_w);
3752 if (WriteStrings &&
3753 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3754 CmdArgs.push_back("-fconst-strings");
3755 }
3756
3757 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3758 // during C++ compilation, which it is by default. GCC keeps this define even
3759 // in the presence of '-w', match this behavior bug-for-bug.
3760 if (types::isCXX(InputType) &&
3761 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3762 true)) {
3763 CmdArgs.push_back("-fdeprecated-macro");
3764 }
3765
3766 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3767 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3768 if (Asm->getOption().matches(options::OPT_fasm))
3769 CmdArgs.push_back("-fgnu-keywords");
3770 else
3771 CmdArgs.push_back("-fno-gnu-keywords");
3772 }
3773
3774 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3775 CmdArgs.push_back("-fno-dwarf-directory-asm");
3776
3777 if (ShouldDisableAutolink(Args, getToolChain()))
3778 CmdArgs.push_back("-fno-autolink");
3779
3780 // Add in -fdebug-compilation-dir if necessary.
3781 addDebugCompDirArg(Args, CmdArgs);
3782
3783 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3784 StringRef Map = A->getValue();
3785 if (Map.find('=') == StringRef::npos)
3786 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3787 else
3788 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3789 A->claim();
3790 }
3791
3792 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3793 options::OPT_ftemplate_depth_EQ)) {
3794 CmdArgs.push_back("-ftemplate-depth");
3795 CmdArgs.push_back(A->getValue());
3796 }
3797
3798 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3799 CmdArgs.push_back("-foperator-arrow-depth");
3800 CmdArgs.push_back(A->getValue());
3801 }
3802
3803 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3804 CmdArgs.push_back("-fconstexpr-depth");
3805 CmdArgs.push_back(A->getValue());
3806 }
3807
3808 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3809 CmdArgs.push_back("-fconstexpr-steps");
3810 CmdArgs.push_back(A->getValue());
3811 }
3812
3813 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3814 CmdArgs.push_back("-fbracket-depth");
3815 CmdArgs.push_back(A->getValue());
3816 }
3817
3818 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3819 options::OPT_Wlarge_by_value_copy_def)) {
3820 if (A->getNumValues()) {
3821 StringRef bytes = A->getValue();
3822 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3823 } else
3824 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3825 }
3826
3827 if (Args.hasArg(options::OPT_relocatable_pch))
3828 CmdArgs.push_back("-relocatable-pch");
3829
3830 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3831 CmdArgs.push_back("-fconstant-string-class");
3832 CmdArgs.push_back(A->getValue());
3833 }
3834
3835 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3836 CmdArgs.push_back("-ftabstop");
3837 CmdArgs.push_back(A->getValue());
3838 }
3839
Sean Eveson5110d4f2018-01-08 13:42:26 +00003840 if (Args.hasFlag(options::OPT_fstack_size_section,
3841 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
3842 CmdArgs.push_back("-fstack-size-section");
3843
David L. Jonesf561aba2017-03-08 01:02:16 +00003844 CmdArgs.push_back("-ferror-limit");
3845 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3846 CmdArgs.push_back(A->getValue());
3847 else
3848 CmdArgs.push_back("19");
3849
3850 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3851 CmdArgs.push_back("-fmacro-backtrace-limit");
3852 CmdArgs.push_back(A->getValue());
3853 }
3854
3855 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3856 CmdArgs.push_back("-ftemplate-backtrace-limit");
3857 CmdArgs.push_back(A->getValue());
3858 }
3859
3860 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3861 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3862 CmdArgs.push_back(A->getValue());
3863 }
3864
3865 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3866 CmdArgs.push_back("-fspell-checking-limit");
3867 CmdArgs.push_back(A->getValue());
3868 }
3869
3870 // Pass -fmessage-length=.
3871 CmdArgs.push_back("-fmessage-length");
3872 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3873 CmdArgs.push_back(A->getValue());
3874 } else {
3875 // If -fmessage-length=N was not specified, determine whether this is a
3876 // terminal and, if so, implicitly define -fmessage-length appropriately.
3877 unsigned N = llvm::sys::Process::StandardErrColumns();
3878 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3879 }
3880
3881 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3882 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3883 options::OPT_fvisibility_ms_compat)) {
3884 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3885 CmdArgs.push_back("-fvisibility");
3886 CmdArgs.push_back(A->getValue());
3887 } else {
3888 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3889 CmdArgs.push_back("-fvisibility");
3890 CmdArgs.push_back("hidden");
3891 CmdArgs.push_back("-ftype-visibility");
3892 CmdArgs.push_back("default");
3893 }
3894 }
3895
3896 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3897
3898 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3899
David L. Jonesf561aba2017-03-08 01:02:16 +00003900 // Forward -f (flag) options which we can pass directly.
3901 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3902 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3903 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Brad Smith733fe192017-07-17 00:49:31 +00003904 // Emulated TLS is enabled by default on Android and OpenBSD, and can be enabled
3905 // manually with -femulated-tls.
3906 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isOSOpenBSD() ||
3907 Triple.isWindowsCygwinEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003908 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3909 EmulatedTLSDefault))
3910 CmdArgs.push_back("-femulated-tls");
3911 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003912 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003913 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003914
David L. Jonesf561aba2017-03-08 01:02:16 +00003915 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3916 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3917
3918 // Forward flags for OpenMP. We don't do this if the current action is an
3919 // device offloading action other than OpenMP.
3920 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3921 options::OPT_fno_openmp, false) &&
3922 (JA.isDeviceOffloading(Action::OFK_None) ||
3923 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003924 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003925 case Driver::OMPRT_OMP:
3926 case Driver::OMPRT_IOMP5:
3927 // Clang can generate useful OpenMP code for these two runtime libraries.
3928 CmdArgs.push_back("-fopenmp");
3929
3930 // If no option regarding the use of TLS in OpenMP codegeneration is
3931 // given, decide a default based on the target. Otherwise rely on the
3932 // options and pass the right information to the frontend.
3933 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3934 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3935 CmdArgs.push_back("-fnoopenmp-use-tls");
3936 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3937 break;
3938 default:
3939 // By default, if Clang doesn't know how to generate useful OpenMP code
3940 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3941 // down to the actual compilation.
3942 // FIXME: It would be better to have a mode which *only* omits IR
3943 // generation based on the OpenMP support so that we get consistent
3944 // semantic analysis, etc.
3945 break;
3946 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00003947 } else {
3948 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
3949 options::OPT_fno_openmp_simd);
3950 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00003951 }
3952
3953 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3954 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3955
Dean Michael Berris835832d2017-03-30 00:29:36 +00003956 const XRayArgs &XRay = getToolChain().getXRayArgs();
3957 XRay.addArgs(getToolChain(), Args, CmdArgs, InputType);
3958
David L. Jonesf561aba2017-03-08 01:02:16 +00003959 if (getToolChain().SupportsProfiling())
3960 Args.AddLastArg(CmdArgs, options::OPT_pg);
3961
3962 if (getToolChain().SupportsProfiling())
3963 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3964
3965 // -flax-vector-conversions is default.
3966 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3967 options::OPT_fno_lax_vector_conversions))
3968 CmdArgs.push_back("-fno-lax-vector-conversions");
3969
3970 if (Args.getLastArg(options::OPT_fapple_kext) ||
3971 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3972 CmdArgs.push_back("-fapple-kext");
3973
3974 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3975 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3976 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3977 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3978 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3979
3980 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3981 CmdArgs.push_back("-ftrapv-handler");
3982 CmdArgs.push_back(A->getValue());
3983 }
3984
3985 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3986
3987 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3988 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3989 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3990 if (A->getOption().matches(options::OPT_fwrapv))
3991 CmdArgs.push_back("-fwrapv");
3992 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3993 options::OPT_fno_strict_overflow)) {
3994 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3995 CmdArgs.push_back("-fwrapv");
3996 }
3997
3998 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3999 options::OPT_fno_reroll_loops))
4000 if (A->getOption().matches(options::OPT_freroll_loops))
4001 CmdArgs.push_back("-freroll-loops");
4002
4003 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4004 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4005 options::OPT_fno_unroll_loops);
4006
4007 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4008
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00004009 RenderSSPOptions(getToolChain(), Args, CmdArgs, KernelOrKext);
David L. Jonesf561aba2017-03-08 01:02:16 +00004010
4011 // Translate -mstackrealign
4012 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4013 false))
4014 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4015
4016 if (Args.hasArg(options::OPT_mstack_alignment)) {
4017 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4018 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4019 }
4020
4021 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4022 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4023
4024 if (!Size.empty())
4025 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4026 else
4027 CmdArgs.push_back("-mstack-probe-size=0");
4028 }
4029
David L. Jonesf561aba2017-03-08 01:02:16 +00004030 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4031 options::OPT_mno_restrict_it)) {
4032 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4033 CmdArgs.push_back("-backend-option");
4034 CmdArgs.push_back("-arm-restrict-it");
4035 } else {
4036 CmdArgs.push_back("-backend-option");
4037 CmdArgs.push_back("-arm-no-restrict-it");
4038 }
4039 } else if (Triple.isOSWindows() &&
4040 (Triple.getArch() == llvm::Triple::arm ||
4041 Triple.getArch() == llvm::Triple::thumb)) {
4042 // Windows on ARM expects restricted IT blocks
4043 CmdArgs.push_back("-backend-option");
4044 CmdArgs.push_back("-arm-restrict-it");
4045 }
4046
4047 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004048 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004049
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004050 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4051 CmdArgs.push_back(
4052 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4053 }
4054
David L. Jonesf561aba2017-03-08 01:02:16 +00004055 // Forward -f options with positive and negative forms; we translate
4056 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004057 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004058 StringRef fname = A->getValue();
4059 if (!llvm::sys::fs::exists(fname))
4060 D.Diag(diag::err_drv_no_such_file) << fname;
4061 else
4062 A->render(Args, CmdArgs);
4063 }
4064
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00004065 RenderBuiltinOptions(getToolChain(), RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004066
4067 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4068 options::OPT_fno_assume_sane_operator_new))
4069 CmdArgs.push_back("-fno-assume-sane-operator-new");
4070
4071 // -fblocks=0 is default.
4072 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4073 getToolChain().IsBlocksDefault()) ||
4074 (Args.hasArg(options::OPT_fgnu_runtime) &&
4075 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4076 !Args.hasArg(options::OPT_fno_blocks))) {
4077 CmdArgs.push_back("-fblocks");
4078
4079 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4080 !getToolChain().hasBlocksRuntime())
4081 CmdArgs.push_back("-fblocks-runtime-optional");
4082 }
4083
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004084 // -fencode-extended-block-signature=1 is default.
4085 if (getToolChain().IsEncodeExtendedBlockSignatureDefault())
4086 CmdArgs.push_back("-fencode-extended-block-signature");
4087
David L. Jonesf561aba2017-03-08 01:02:16 +00004088 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4089 false) &&
4090 types::isCXX(InputType)) {
4091 CmdArgs.push_back("-fcoroutines-ts");
4092 }
4093
Aaron Ballman61736552017-10-21 20:28:58 +00004094 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4095 options::OPT_fno_double_square_bracket_attributes);
4096
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004097 bool HaveModules = false;
4098 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004099
4100 // -faccess-control is default.
4101 if (Args.hasFlag(options::OPT_fno_access_control,
4102 options::OPT_faccess_control, false))
4103 CmdArgs.push_back("-fno-access-control");
4104
4105 // -felide-constructors is the default.
4106 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4107 options::OPT_felide_constructors, false))
4108 CmdArgs.push_back("-fno-elide-constructors");
4109
4110 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4111
4112 if (KernelOrKext || (types::isCXX(InputType) &&
4113 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4114 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4115 CmdArgs.push_back("-fno-rtti");
4116
4117 // -fshort-enums=0 is default for all architectures except Hexagon.
4118 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4119 getToolChain().getArch() == llvm::Triple::hexagon))
4120 CmdArgs.push_back("-fshort-enums");
4121
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004122 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004123
4124 // -fuse-cxa-atexit is default.
4125 if (!Args.hasFlag(
4126 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004127 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004128 RawTriple.getOS() != llvm::Triple::Solaris &&
David L. Jonesf561aba2017-03-08 01:02:16 +00004129 getToolChain().getArch() != llvm::Triple::hexagon &&
4130 getToolChain().getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004131 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4132 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004133 KernelOrKext)
4134 CmdArgs.push_back("-fno-use-cxa-atexit");
4135
4136 // -fms-extensions=0 is default.
4137 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4138 IsWindowsMSVC))
4139 CmdArgs.push_back("-fms-extensions");
4140
4141 // -fno-use-line-directives is default.
4142 if (Args.hasFlag(options::OPT_fuse_line_directives,
4143 options::OPT_fno_use_line_directives, false))
4144 CmdArgs.push_back("-fuse-line-directives");
4145
4146 // -fms-compatibility=0 is default.
4147 if (Args.hasFlag(options::OPT_fms_compatibility,
4148 options::OPT_fno_ms_compatibility,
4149 (IsWindowsMSVC &&
4150 Args.hasFlag(options::OPT_fms_extensions,
4151 options::OPT_fno_ms_extensions, true))))
4152 CmdArgs.push_back("-fms-compatibility");
4153
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004154 VersionTuple MSVT = getToolChain().computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004155 if (!MSVT.empty())
4156 CmdArgs.push_back(
4157 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4158
4159 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4160 if (ImplyVCPPCXXVer) {
4161 StringRef LanguageStandard;
4162 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4163 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4164 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004165 .Case("c++17", "-std=c++17")
4166 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004167 .Default("");
4168 if (LanguageStandard.empty())
4169 D.Diag(clang::diag::warn_drv_unused_argument)
4170 << StdArg->getAsString(Args);
4171 }
4172
4173 if (LanguageStandard.empty()) {
4174 if (IsMSVC2015Compatible)
4175 LanguageStandard = "-std=c++14";
4176 else
4177 LanguageStandard = "-std=c++11";
4178 }
4179
4180 CmdArgs.push_back(LanguageStandard.data());
4181 }
4182
4183 // -fno-borland-extensions is default.
4184 if (Args.hasFlag(options::OPT_fborland_extensions,
4185 options::OPT_fno_borland_extensions, false))
4186 CmdArgs.push_back("-fborland-extensions");
4187
4188 // -fno-declspec is default, except for PS4.
4189 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004190 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004191 CmdArgs.push_back("-fdeclspec");
4192 else if (Args.hasArg(options::OPT_fno_declspec))
4193 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4194
4195 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4196 // than 19.
4197 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4198 options::OPT_fno_threadsafe_statics,
4199 !IsWindowsMSVC || IsMSVC2015Compatible))
4200 CmdArgs.push_back("-fno-threadsafe-statics");
4201
Reid Klecknerea2683e2017-08-28 17:59:24 +00004202 // -fno-delayed-template-parsing is default, except when targetting MSVC.
4203 // Many old Windows SDK versions require this to parse.
4204 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4205 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004206 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4207 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4208 CmdArgs.push_back("-fdelayed-template-parsing");
4209
4210 // -fgnu-keywords default varies depending on language; only pass if
4211 // specified.
4212 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4213 options::OPT_fno_gnu_keywords))
4214 A->render(Args, CmdArgs);
4215
4216 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4217 false))
4218 CmdArgs.push_back("-fgnu89-inline");
4219
4220 if (Args.hasArg(options::OPT_fno_inline))
4221 CmdArgs.push_back("-fno-inline");
4222
4223 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4224 options::OPT_finline_hint_functions,
4225 options::OPT_fno_inline_functions))
4226 InlineArg->render(Args, CmdArgs);
4227
4228 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4229 options::OPT_fno_experimental_new_pass_manager);
4230
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004231 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4232 RenderObjCOptions(getToolChain(), D, RawTriple, Args, Runtime,
4233 rewriteKind != RK_None, Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004234
4235 if (Args.hasFlag(options::OPT_fapplication_extension,
4236 options::OPT_fno_application_extension, false))
4237 CmdArgs.push_back("-fapplication-extension");
4238
4239 // Handle GCC-style exception args.
4240 if (!C.getDriver().IsCLMode())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004241 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, Runtime,
David L. Jonesf561aba2017-03-08 01:02:16 +00004242 CmdArgs);
4243
Martell Malonec950c652017-11-29 07:25:12 +00004244 // Handle exception personalities
4245 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4246 options::OPT_fseh_exceptions,
4247 options::OPT_fdwarf_exceptions);
4248 if (A) {
4249 const Option &Opt = A->getOption();
4250 if (Opt.matches(options::OPT_fsjlj_exceptions))
4251 CmdArgs.push_back("-fsjlj-exceptions");
4252 if (Opt.matches(options::OPT_fseh_exceptions))
4253 CmdArgs.push_back("-fseh-exceptions");
4254 if (Opt.matches(options::OPT_fdwarf_exceptions))
4255 CmdArgs.push_back("-fdwarf-exceptions");
4256 } else {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004257 switch (getToolChain().GetExceptionModel(Args)) {
4258 default:
4259 break;
4260 case llvm::ExceptionHandling::DwarfCFI:
4261 CmdArgs.push_back("-fdwarf-exceptions");
4262 break;
4263 case llvm::ExceptionHandling::SjLj:
4264 CmdArgs.push_back("-fsjlj-exceptions");
4265 break;
4266 case llvm::ExceptionHandling::WinEH:
4267 CmdArgs.push_back("-fseh-exceptions");
4268 break;
Martell Malonec950c652017-11-29 07:25:12 +00004269 }
4270 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004271
4272 // C++ "sane" operator new.
4273 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4274 options::OPT_fno_assume_sane_operator_new))
4275 CmdArgs.push_back("-fno-assume-sane-operator-new");
4276
4277 // -frelaxed-template-template-args is off by default, as it is a severe
4278 // breaking change until a corresponding change to template partial ordering
4279 // is provided.
4280 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4281 options::OPT_fno_relaxed_template_template_args, false))
4282 CmdArgs.push_back("-frelaxed-template-template-args");
4283
4284 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4285 // most platforms.
4286 if (Args.hasFlag(options::OPT_fsized_deallocation,
4287 options::OPT_fno_sized_deallocation, false))
4288 CmdArgs.push_back("-fsized-deallocation");
4289
4290 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4291 // by default.
4292 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4293 options::OPT_fno_aligned_allocation,
4294 options::OPT_faligned_new_EQ)) {
4295 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4296 CmdArgs.push_back("-fno-aligned-allocation");
4297 else
4298 CmdArgs.push_back("-faligned-allocation");
4299 }
4300
4301 // The default new alignment can be specified using a dedicated option or via
4302 // a GCC-compatible option that also turns on aligned allocation.
4303 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4304 options::OPT_faligned_new_EQ))
4305 CmdArgs.push_back(
4306 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4307
4308 // -fconstant-cfstrings is default, and may be subject to argument translation
4309 // on Darwin.
4310 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4311 options::OPT_fno_constant_cfstrings) ||
4312 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4313 options::OPT_mno_constant_cfstrings))
4314 CmdArgs.push_back("-fno-constant-cfstrings");
4315
David L. Jonesf561aba2017-03-08 01:02:16 +00004316 // -fno-pascal-strings is default, only pass non-default.
4317 if (Args.hasFlag(options::OPT_fpascal_strings,
4318 options::OPT_fno_pascal_strings, false))
4319 CmdArgs.push_back("-fpascal-strings");
4320
4321 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4322 // -fno-pack-struct doesn't apply to -fpack-struct=.
4323 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4324 std::string PackStructStr = "-fpack-struct=";
4325 PackStructStr += A->getValue();
4326 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4327 } else if (Args.hasFlag(options::OPT_fpack_struct,
4328 options::OPT_fno_pack_struct, false)) {
4329 CmdArgs.push_back("-fpack-struct=1");
4330 }
4331
4332 // Handle -fmax-type-align=N and -fno-type-align
4333 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4334 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4335 if (!SkipMaxTypeAlign) {
4336 std::string MaxTypeAlignStr = "-fmax-type-align=";
4337 MaxTypeAlignStr += A->getValue();
4338 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4339 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004340 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004341 if (!SkipMaxTypeAlign) {
4342 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4343 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4344 }
4345 }
4346
4347 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004348 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004349 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4350 !NoCommonDefault))
4351 CmdArgs.push_back("-fno-common");
4352
4353 // -fsigned-bitfields is default, and clang doesn't yet support
4354 // -funsigned-bitfields.
4355 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4356 options::OPT_funsigned_bitfields))
4357 D.Diag(diag::warn_drv_clang_unsupported)
4358 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4359
4360 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4361 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4362 D.Diag(diag::err_drv_clang_unsupported)
4363 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4364
4365 // -finput_charset=UTF-8 is default. Reject others
4366 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4367 StringRef value = inputCharset->getValue();
4368 if (!value.equals_lower("utf-8"))
4369 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4370 << value;
4371 }
4372
4373 // -fexec_charset=UTF-8 is default. Reject others
4374 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4375 StringRef value = execCharset->getValue();
4376 if (!value.equals_lower("utf-8"))
4377 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4378 << value;
4379 }
4380
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004381 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004382
4383 // -fno-asm-blocks is default.
4384 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4385 false))
4386 CmdArgs.push_back("-fasm-blocks");
4387
4388 // -fgnu-inline-asm is default.
4389 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4390 options::OPT_fno_gnu_inline_asm, true))
4391 CmdArgs.push_back("-fno-gnu-inline-asm");
4392
4393 // Enable vectorization per default according to the optimization level
4394 // selected. For optimization levels that want vectorization we use the alias
4395 // option to simplify the hasFlag logic.
4396 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4397 OptSpecifier VectorizeAliasOption =
4398 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4399 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4400 options::OPT_fno_vectorize, EnableVec))
4401 CmdArgs.push_back("-vectorize-loops");
4402
4403 // -fslp-vectorize is enabled based on the optimization level selected.
4404 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4405 OptSpecifier SLPVectAliasOption =
4406 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4407 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4408 options::OPT_fno_slp_vectorize, EnableSLPVec))
4409 CmdArgs.push_back("-vectorize-slp");
4410
Craig Topper9a724aa2017-12-11 21:09:19 +00004411 ParseMPreferVectorWidth(D, Args, CmdArgs);
4412
David L. Jonesf561aba2017-03-08 01:02:16 +00004413 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4414 A->render(Args, CmdArgs);
4415
4416 if (Arg *A = Args.getLastArg(
4417 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4418 A->render(Args, CmdArgs);
4419
4420 // -fdollars-in-identifiers default varies depending on platform and
4421 // language; only pass if specified.
4422 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4423 options::OPT_fno_dollars_in_identifiers)) {
4424 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4425 CmdArgs.push_back("-fdollars-in-identifiers");
4426 else
4427 CmdArgs.push_back("-fno-dollars-in-identifiers");
4428 }
4429
4430 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4431 // practical purposes.
4432 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4433 options::OPT_fno_unit_at_a_time)) {
4434 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4435 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4436 }
4437
4438 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4439 options::OPT_fno_apple_pragma_pack, false))
4440 CmdArgs.push_back("-fapple-pragma-pack");
4441
David L. Jonesf561aba2017-03-08 01:02:16 +00004442 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00004443 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00004444 options::OPT_fno_save_optimization_record, false)) {
4445 CmdArgs.push_back("-opt-record-file");
4446
4447 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4448 if (A) {
4449 CmdArgs.push_back(A->getValue());
4450 } else {
4451 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00004452
4453 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
4454 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
4455 F = FinalOutput->getValue();
4456 }
4457
4458 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004459 // Use the input filename.
4460 F = llvm::sys::path::stem(Input.getBaseInput());
4461
4462 // If we're compiling for an offload architecture (i.e. a CUDA device),
4463 // we need to make the file name for the device compilation different
4464 // from the host compilation.
4465 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4466 !JA.isDeviceOffloading(Action::OFK_Host)) {
4467 llvm::sys::path::replace_extension(F, "");
4468 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4469 Triple.normalize());
4470 F += "-";
4471 F += JA.getOffloadingArch();
4472 }
4473 }
4474
4475 llvm::sys::path::replace_extension(F, "opt.yaml");
4476 CmdArgs.push_back(Args.MakeArgString(F));
4477 }
4478 }
4479
Richard Smith86a3ef52017-06-09 21:24:02 +00004480 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
4481 options::OPT_fno_rewrite_imports, false);
4482 if (RewriteImports)
4483 CmdArgs.push_back("-frewrite-imports");
4484
David L. Jonesf561aba2017-03-08 01:02:16 +00004485 // Enable rewrite includes if the user's asked for it or if we're generating
4486 // diagnostics.
4487 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4488 // nice to enable this when doing a crashdump for modules as well.
4489 if (Args.hasFlag(options::OPT_frewrite_includes,
4490 options::OPT_fno_rewrite_includes, false) ||
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004491 (C.isForDiagnostics() && (RewriteImports || !HaveModules)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004492 CmdArgs.push_back("-frewrite-includes");
4493
4494 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4495 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4496 options::OPT_traditional_cpp)) {
4497 if (isa<PreprocessJobAction>(JA))
4498 CmdArgs.push_back("-traditional-cpp");
4499 else
4500 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4501 }
4502
4503 Args.AddLastArg(CmdArgs, options::OPT_dM);
4504 Args.AddLastArg(CmdArgs, options::OPT_dD);
4505
4506 // Handle serialized diagnostics.
4507 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4508 CmdArgs.push_back("-serialize-diagnostic-file");
4509 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4510 }
4511
4512 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4513 CmdArgs.push_back("-fretain-comments-from-system-headers");
4514
4515 // Forward -fcomment-block-commands to -cc1.
4516 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4517 // Forward -fparse-all-comments to -cc1.
4518 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4519
4520 // Turn -fplugin=name.so into -load name.so
4521 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4522 CmdArgs.push_back("-load");
4523 CmdArgs.push_back(A->getValue());
4524 A->claim();
4525 }
4526
4527 // Setup statistics file output.
4528 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4529 StringRef SaveStats = A->getValue();
4530
4531 SmallString<128> StatsFile;
4532 bool DoSaveStats = false;
4533 if (SaveStats == "obj") {
4534 if (Output.isFilename()) {
4535 StatsFile.assign(Output.getFilename());
4536 llvm::sys::path::remove_filename(StatsFile);
4537 }
4538 DoSaveStats = true;
4539 } else if (SaveStats == "cwd") {
4540 DoSaveStats = true;
4541 } else {
4542 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4543 }
4544
4545 if (DoSaveStats) {
4546 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4547 llvm::sys::path::append(StatsFile, BaseName);
4548 llvm::sys::path::replace_extension(StatsFile, "stats");
4549 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4550 StatsFile));
4551 }
4552 }
4553
4554 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4555 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004556 // -finclude-default-header flag is for preprocessor,
4557 // do not pass it to other cc1 commands when save-temps is enabled
4558 if (C.getDriver().isSaveTempsEnabled() &&
4559 !isa<PreprocessJobAction>(JA)) {
4560 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4561 Arg->claim();
4562 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4563 CmdArgs.push_back(Arg->getValue());
4564 }
4565 }
4566 else {
4567 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4568 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004569 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4570 A->claim();
4571
4572 // We translate this by hand to the -cc1 argument, since nightly test uses
4573 // it and developers have been trained to spell it with -mllvm. Both
4574 // spellings are now deprecated and should be removed.
4575 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4576 CmdArgs.push_back("-disable-llvm-optzns");
4577 } else {
4578 A->render(Args, CmdArgs);
4579 }
4580 }
4581
4582 // With -save-temps, we want to save the unoptimized bitcode output from the
4583 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4584 // by the frontend.
4585 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4586 // has slightly different breakdown between stages.
4587 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4588 // pristine IR generated by the frontend. Ideally, a new compile action should
4589 // be added so both IR can be captured.
4590 if (C.getDriver().isSaveTempsEnabled() &&
4591 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4592 isa<CompileJobAction>(JA))
4593 CmdArgs.push_back("-disable-llvm-passes");
4594
4595 if (Output.getType() == types::TY_Dependencies) {
4596 // Handled with other dependency code.
4597 } else if (Output.isFilename()) {
4598 CmdArgs.push_back("-o");
4599 CmdArgs.push_back(Output.getFilename());
4600 } else {
4601 assert(Output.isNothing() && "Invalid output.");
4602 }
4603
4604 addDashXForInput(Args, Input, CmdArgs);
4605
4606 if (Input.isFilename())
4607 CmdArgs.push_back(Input.getFilename());
4608 else
4609 Input.getInputArg().renderAsInput(Args, CmdArgs);
4610
4611 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4612
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004613 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00004614
4615 // Optionally embed the -cc1 level arguments into the debug info, for build
4616 // analysis.
Eric Christopherca325172017-03-29 23:34:20 +00004617 // Also record command line arguments into the debug info if
4618 // -grecord-gcc-switches options is set on.
4619 // By default, -gno-record-gcc-switches is set on and no recording.
4620 if (getToolChain().UseDwarfDebugFlags() ||
4621 Args.hasFlag(options::OPT_grecord_gcc_switches,
4622 options::OPT_gno_record_gcc_switches, false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004623 ArgStringList OriginalArgs;
4624 for (const auto &Arg : Args)
4625 Arg->render(Args, OriginalArgs);
4626
4627 SmallString<256> Flags;
4628 Flags += Exec;
4629 for (const char *OriginalArg : OriginalArgs) {
4630 SmallString<128> EscapedArg;
4631 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4632 Flags += " ";
4633 Flags += EscapedArg;
4634 }
4635 CmdArgs.push_back("-dwarf-debug-flags");
4636 CmdArgs.push_back(Args.MakeArgString(Flags));
4637 }
4638
David L. Jonesf561aba2017-03-08 01:02:16 +00004639 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4640 // Include them with -fcuda-include-gpubinary.
4641 if (IsCuda && Inputs.size() > 1)
4642 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4643 CmdArgs.push_back("-fcuda-include-gpubinary");
4644 CmdArgs.push_back(I->getFilename());
4645 }
4646
4647 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4648 // to specify the result of the compile phase on the host, so the meaningful
4649 // device declarations can be identified. Also, -fopenmp-is-device is passed
4650 // along to tell the frontend that it is generating code for a device, so that
4651 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004652 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004653 CmdArgs.push_back("-fopenmp-is-device");
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00004654 if (Inputs.size() == 2) {
4655 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4656 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4657 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004658 }
4659
4660 // For all the host OpenMP offloading compile jobs we need to pass the targets
4661 // information using -fopenmp-targets= option.
4662 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4663 SmallString<128> TargetInfo("-fopenmp-targets=");
4664
4665 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4666 assert(Tgts && Tgts->getNumValues() &&
4667 "OpenMP offloading has to have targets specified.");
4668 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4669 if (i)
4670 TargetInfo += ',';
4671 // We need to get the string from the triple because it may be not exactly
4672 // the same as the one we get directly from the arguments.
4673 llvm::Triple T(Tgts->getValue(i));
4674 TargetInfo += T.getTriple();
4675 }
4676 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4677 }
4678
4679 bool WholeProgramVTables =
4680 Args.hasFlag(options::OPT_fwhole_program_vtables,
4681 options::OPT_fno_whole_program_vtables, false);
4682 if (WholeProgramVTables) {
4683 if (!D.isUsingLTO())
4684 D.Diag(diag::err_drv_argument_only_allowed_with)
4685 << "-fwhole-program-vtables"
4686 << "-flto";
4687 CmdArgs.push_back("-fwhole-program-vtables");
4688 }
4689
4690 // Finally add the compile command to the compilation.
4691 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4692 Output.getType() == types::TY_Object &&
4693 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4694 auto CLCommand =
4695 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4696 C.addCommand(llvm::make_unique<FallbackCommand>(
4697 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4698 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4699 isa<PrecompileJobAction>(JA)) {
4700 // In /fallback builds, run the main compilation even if the pch generation
4701 // fails, so that the main compilation's fallback to cl.exe runs.
4702 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4703 CmdArgs, Inputs));
4704 } else {
4705 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4706 }
4707
4708 // Handle the debug info splitting at object creation time if we're
4709 // creating an object.
4710 // TODO: Currently only works on linux with newer objcopy.
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004711 if (SplitDWARF && Output.getType() == types::TY_Object)
4712 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDWARFOut);
David L. Jonesf561aba2017-03-08 01:02:16 +00004713
4714 if (Arg *A = Args.getLastArg(options::OPT_pg))
4715 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4716 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4717 << A->getAsString(Args);
4718
4719 // Claim some arguments which clang supports automatically.
4720
4721 // -fpch-preprocess is used with gcc to add a special marker in the output to
4722 // include the PCH file. Clang's PTH solution is completely transparent, so we
4723 // do not need to deal with it at all.
4724 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4725
4726 // Claim some arguments which clang doesn't support, but we don't
4727 // care to warn the user about.
4728 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4729 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4730
4731 // Disable warnings for clang -E -emit-llvm foo.c
4732 Args.ClaimAllArgs(options::OPT_emit_llvm);
4733}
4734
4735Clang::Clang(const ToolChain &TC)
4736 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4737 // as it is for other tools. Some operations on a Tool actually test
4738 // whether that tool is Clang based on the Tool's Name as a string.
4739 : Tool("clang", "clang frontend", TC, RF_Full) {}
4740
4741Clang::~Clang() {}
4742
4743/// Add options related to the Objective-C runtime/ABI.
4744///
4745/// Returns true if the runtime is non-fragile.
4746ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4747 ArgStringList &cmdArgs,
4748 RewriteKind rewriteKind) const {
4749 // Look for the controlling runtime option.
4750 Arg *runtimeArg =
4751 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4752 options::OPT_fobjc_runtime_EQ);
4753
4754 // Just forward -fobjc-runtime= to the frontend. This supercedes
4755 // options about fragility.
4756 if (runtimeArg &&
4757 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4758 ObjCRuntime runtime;
4759 StringRef value = runtimeArg->getValue();
4760 if (runtime.tryParse(value)) {
4761 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4762 << value;
4763 }
4764
4765 runtimeArg->render(args, cmdArgs);
4766 return runtime;
4767 }
4768
4769 // Otherwise, we'll need the ABI "version". Version numbers are
4770 // slightly confusing for historical reasons:
4771 // 1 - Traditional "fragile" ABI
4772 // 2 - Non-fragile ABI, version 1
4773 // 3 - Non-fragile ABI, version 2
4774 unsigned objcABIVersion = 1;
4775 // If -fobjc-abi-version= is present, use that to set the version.
4776 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4777 StringRef value = abiArg->getValue();
4778 if (value == "1")
4779 objcABIVersion = 1;
4780 else if (value == "2")
4781 objcABIVersion = 2;
4782 else if (value == "3")
4783 objcABIVersion = 3;
4784 else
4785 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4786 } else {
4787 // Otherwise, determine if we are using the non-fragile ABI.
4788 bool nonFragileABIIsDefault =
4789 (rewriteKind == RK_NonFragile ||
4790 (rewriteKind == RK_None &&
4791 getToolChain().IsObjCNonFragileABIDefault()));
4792 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4793 options::OPT_fno_objc_nonfragile_abi,
4794 nonFragileABIIsDefault)) {
4795// Determine the non-fragile ABI version to use.
4796#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4797 unsigned nonFragileABIVersion = 1;
4798#else
4799 unsigned nonFragileABIVersion = 2;
4800#endif
4801
4802 if (Arg *abiArg =
4803 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4804 StringRef value = abiArg->getValue();
4805 if (value == "1")
4806 nonFragileABIVersion = 1;
4807 else if (value == "2")
4808 nonFragileABIVersion = 2;
4809 else
4810 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4811 << value;
4812 }
4813
4814 objcABIVersion = 1 + nonFragileABIVersion;
4815 } else {
4816 objcABIVersion = 1;
4817 }
4818 }
4819
4820 // We don't actually care about the ABI version other than whether
4821 // it's non-fragile.
4822 bool isNonFragile = objcABIVersion != 1;
4823
4824 // If we have no runtime argument, ask the toolchain for its default runtime.
4825 // However, the rewriter only really supports the Mac runtime, so assume that.
4826 ObjCRuntime runtime;
4827 if (!runtimeArg) {
4828 switch (rewriteKind) {
4829 case RK_None:
4830 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4831 break;
4832 case RK_Fragile:
4833 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4834 break;
4835 case RK_NonFragile:
4836 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4837 break;
4838 }
4839
4840 // -fnext-runtime
4841 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4842 // On Darwin, make this use the default behavior for the toolchain.
4843 if (getToolChain().getTriple().isOSDarwin()) {
4844 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4845
4846 // Otherwise, build for a generic macosx port.
4847 } else {
4848 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4849 }
4850
4851 // -fgnu-runtime
4852 } else {
4853 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4854 // Legacy behaviour is to target the gnustep runtime if we are in
4855 // non-fragile mode or the GCC runtime in fragile mode.
4856 if (isNonFragile)
4857 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4858 else
4859 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4860 }
4861
4862 cmdArgs.push_back(
4863 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4864 return runtime;
4865}
4866
4867static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4868 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4869 I += HaveDash;
4870 return !HaveDash;
4871}
4872
4873namespace {
4874struct EHFlags {
4875 bool Synch = false;
4876 bool Asynch = false;
4877 bool NoUnwindC = false;
4878};
4879} // end anonymous namespace
4880
4881/// /EH controls whether to run destructor cleanups when exceptions are
4882/// thrown. There are three modifiers:
4883/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4884/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4885/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4886/// - c: Assume that extern "C" functions are implicitly nounwind.
4887/// The default is /EHs-c-, meaning cleanups are disabled.
4888static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4889 EHFlags EH;
4890
4891 std::vector<std::string> EHArgs =
4892 Args.getAllArgValues(options::OPT__SLASH_EH);
4893 for (auto EHVal : EHArgs) {
4894 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4895 switch (EHVal[I]) {
4896 case 'a':
4897 EH.Asynch = maybeConsumeDash(EHVal, I);
4898 if (EH.Asynch)
4899 EH.Synch = false;
4900 continue;
4901 case 'c':
4902 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4903 continue;
4904 case 's':
4905 EH.Synch = maybeConsumeDash(EHVal, I);
4906 if (EH.Synch)
4907 EH.Asynch = false;
4908 continue;
4909 default:
4910 break;
4911 }
4912 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4913 break;
4914 }
4915 }
4916 // The /GX, /GX- flags are only processed if there are not /EH flags.
4917 // The default is that /GX is not specified.
4918 if (EHArgs.empty() &&
4919 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4920 /*default=*/false)) {
4921 EH.Synch = true;
4922 EH.NoUnwindC = true;
4923 }
4924
4925 return EH;
4926}
4927
4928void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4929 ArgStringList &CmdArgs,
4930 codegenoptions::DebugInfoKind *DebugInfoKind,
4931 bool *EmitCodeView) const {
4932 unsigned RTOptionID = options::OPT__SLASH_MT;
4933
4934 if (Args.hasArg(options::OPT__SLASH_LDd))
4935 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4936 // but defining _DEBUG is sticky.
4937 RTOptionID = options::OPT__SLASH_MTd;
4938
4939 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4940 RTOptionID = A->getOption().getID();
4941
4942 StringRef FlagForCRT;
4943 switch (RTOptionID) {
4944 case options::OPT__SLASH_MD:
4945 if (Args.hasArg(options::OPT__SLASH_LDd))
4946 CmdArgs.push_back("-D_DEBUG");
4947 CmdArgs.push_back("-D_MT");
4948 CmdArgs.push_back("-D_DLL");
4949 FlagForCRT = "--dependent-lib=msvcrt";
4950 break;
4951 case options::OPT__SLASH_MDd:
4952 CmdArgs.push_back("-D_DEBUG");
4953 CmdArgs.push_back("-D_MT");
4954 CmdArgs.push_back("-D_DLL");
4955 FlagForCRT = "--dependent-lib=msvcrtd";
4956 break;
4957 case options::OPT__SLASH_MT:
4958 if (Args.hasArg(options::OPT__SLASH_LDd))
4959 CmdArgs.push_back("-D_DEBUG");
4960 CmdArgs.push_back("-D_MT");
4961 CmdArgs.push_back("-flto-visibility-public-std");
4962 FlagForCRT = "--dependent-lib=libcmt";
4963 break;
4964 case options::OPT__SLASH_MTd:
4965 CmdArgs.push_back("-D_DEBUG");
4966 CmdArgs.push_back("-D_MT");
4967 CmdArgs.push_back("-flto-visibility-public-std");
4968 FlagForCRT = "--dependent-lib=libcmtd";
4969 break;
4970 default:
4971 llvm_unreachable("Unexpected option ID.");
4972 }
4973
4974 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4975 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4976 } else {
4977 CmdArgs.push_back(FlagForCRT.data());
4978
4979 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4980 // users want. The /Za flag to cl.exe turns this off, but it's not
4981 // implemented in clang.
4982 CmdArgs.push_back("--dependent-lib=oldnames");
4983 }
4984
4985 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4986 // would produce interleaved output, so ignore /showIncludes in such cases.
Erich Keane87baae22017-10-20 19:18:30 +00004987 if ((!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP)) ||
4988 (Args.hasArg(options::OPT__SLASH_P) &&
4989 Args.hasArg(options::OPT__SLASH_EP) && !Args.hasArg(options::OPT_E)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004990 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4991 A->render(Args, CmdArgs);
4992
4993 // This controls whether or not we emit RTTI data for polymorphic types.
4994 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4995 /*default=*/false))
4996 CmdArgs.push_back("-fno-rtti-data");
4997
4998 // This controls whether or not we emit stack-protector instrumentation.
4999 // In MSVC, Buffer Security Check (/GS) is on by default.
5000 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5001 /*default=*/true)) {
5002 CmdArgs.push_back("-stack-protector");
5003 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5004 }
5005
5006 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5007 if (Arg *DebugInfoArg =
5008 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5009 options::OPT_gline_tables_only)) {
5010 *EmitCodeView = true;
5011 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5012 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5013 else
5014 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5015 CmdArgs.push_back("-gcodeview");
5016 } else {
5017 *EmitCodeView = false;
5018 }
5019
5020 const Driver &D = getToolChain().getDriver();
5021 EHFlags EH = parseClangCLEHFlags(D, Args);
5022 if (EH.Synch || EH.Asynch) {
5023 if (types::isCXX(InputType))
5024 CmdArgs.push_back("-fcxx-exceptions");
5025 CmdArgs.push_back("-fexceptions");
5026 }
5027 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5028 CmdArgs.push_back("-fexternc-nounwind");
5029
5030 // /EP should expand to -E -P.
5031 if (Args.hasArg(options::OPT__SLASH_EP)) {
5032 CmdArgs.push_back("-E");
5033 CmdArgs.push_back("-P");
5034 }
5035
5036 unsigned VolatileOptionID;
5037 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5038 getToolChain().getArch() == llvm::Triple::x86)
5039 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5040 else
5041 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5042
5043 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5044 VolatileOptionID = A->getOption().getID();
5045
5046 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5047 CmdArgs.push_back("-fms-volatile");
5048
5049 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5050 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5051 if (MostGeneralArg && BestCaseArg)
5052 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5053 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5054
5055 if (MostGeneralArg) {
5056 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5057 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5058 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5059
5060 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5061 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5062 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5063 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5064 << FirstConflict->getAsString(Args)
5065 << SecondConflict->getAsString(Args);
5066
5067 if (SingleArg)
5068 CmdArgs.push_back("-fms-memptr-rep=single");
5069 else if (MultipleArg)
5070 CmdArgs.push_back("-fms-memptr-rep=multiple");
5071 else
5072 CmdArgs.push_back("-fms-memptr-rep=virtual");
5073 }
5074
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005075 // Parse the default calling convention options.
5076 if (Arg *CCArg =
5077 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005078 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5079 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005080 unsigned DCCOptId = CCArg->getOption().getID();
5081 const char *DCCFlag = nullptr;
5082 bool ArchSupported = true;
5083 llvm::Triple::ArchType Arch = getToolChain().getArch();
5084 switch (DCCOptId) {
5085 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005086 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005087 break;
5088 case options::OPT__SLASH_Gr:
5089 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005090 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005091 break;
5092 case options::OPT__SLASH_Gz:
5093 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005094 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005095 break;
5096 case options::OPT__SLASH_Gv:
5097 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005098 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005099 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005100 case options::OPT__SLASH_Gregcall:
5101 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5102 DCCFlag = "-fdefault-calling-conv=regcall";
5103 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005104 }
5105
5106 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5107 if (ArchSupported && DCCFlag)
5108 CmdArgs.push_back(DCCFlag);
5109 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005110
5111 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5112 A->render(Args, CmdArgs);
5113
5114 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5115 CmdArgs.push_back("-fdiagnostics-format");
5116 if (Args.hasArg(options::OPT__SLASH_fallback))
5117 CmdArgs.push_back("msvc-fallback");
5118 else
5119 CmdArgs.push_back("msvc");
5120 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005121
5122 if (Args.hasArg(options::OPT__SLASH_Guard) &&
5123 Args.getLastArgValue(options::OPT__SLASH_Guard).equals_lower("cf"))
5124 CmdArgs.push_back("-cfguard");
David L. Jonesf561aba2017-03-08 01:02:16 +00005125}
5126
5127visualstudio::Compiler *Clang::getCLFallback() const {
5128 if (!CLFallback)
5129 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5130 return CLFallback.get();
5131}
5132
5133
5134const char *Clang::getBaseInputName(const ArgList &Args,
5135 const InputInfo &Input) {
5136 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5137}
5138
5139const char *Clang::getBaseInputStem(const ArgList &Args,
5140 const InputInfoList &Inputs) {
5141 const char *Str = getBaseInputName(Args, Inputs[0]);
5142
5143 if (const char *End = strrchr(Str, '.'))
5144 return Args.MakeArgString(std::string(Str, End));
5145
5146 return Str;
5147}
5148
5149const char *Clang::getDependencyFileName(const ArgList &Args,
5150 const InputInfoList &Inputs) {
5151 // FIXME: Think about this more.
5152 std::string Res;
5153
5154 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5155 std::string Str(OutputOpt->getValue());
5156 Res = Str.substr(0, Str.rfind('.'));
5157 } else {
5158 Res = getBaseInputStem(Args, Inputs);
5159 }
5160 return Args.MakeArgString(Res + ".d");
5161}
5162
5163// Begin ClangAs
5164
5165void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5166 ArgStringList &CmdArgs) const {
5167 StringRef CPUName;
5168 StringRef ABIName;
5169 const llvm::Triple &Triple = getToolChain().getTriple();
5170 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5171
5172 CmdArgs.push_back("-target-abi");
5173 CmdArgs.push_back(ABIName.data());
5174}
5175
5176void ClangAs::AddX86TargetArgs(const ArgList &Args,
5177 ArgStringList &CmdArgs) const {
5178 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5179 StringRef Value = A->getValue();
5180 if (Value == "intel" || Value == "att") {
5181 CmdArgs.push_back("-mllvm");
5182 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5183 } else {
5184 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5185 << A->getOption().getName() << Value;
5186 }
5187 }
5188}
5189
5190void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5191 const InputInfo &Output, const InputInfoList &Inputs,
5192 const ArgList &Args,
5193 const char *LinkingOutput) const {
5194 ArgStringList CmdArgs;
5195
5196 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5197 const InputInfo &Input = Inputs[0];
5198
5199 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5200 const std::string &TripleStr = Triple.getTriple();
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005201 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005202
5203 // Don't warn about "clang -w -c foo.s"
5204 Args.ClaimAllArgs(options::OPT_w);
5205 // and "clang -emit-llvm -c foo.s"
5206 Args.ClaimAllArgs(options::OPT_emit_llvm);
5207
5208 claimNoWarnArgs(Args);
5209
5210 // Invoke ourselves in -cc1as mode.
5211 //
5212 // FIXME: Implement custom jobs for internal actions.
5213 CmdArgs.push_back("-cc1as");
5214
5215 // Add the "effective" target triple.
5216 CmdArgs.push_back("-triple");
5217 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5218
5219 // Set the output mode, we currently only expect to be used as a real
5220 // assembler.
5221 CmdArgs.push_back("-filetype");
5222 CmdArgs.push_back("obj");
5223
5224 // Set the main file name, so that debug info works even with
5225 // -save-temps or preprocessed assembly.
5226 CmdArgs.push_back("-main-file-name");
5227 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5228
5229 // Add the target cpu
5230 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5231 if (!CPU.empty()) {
5232 CmdArgs.push_back("-target-cpu");
5233 CmdArgs.push_back(Args.MakeArgString(CPU));
5234 }
5235
5236 // Add the target features
5237 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5238
5239 // Ignore explicit -force_cpusubtype_ALL option.
5240 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5241
5242 // Pass along any -I options so we get proper .include search paths.
5243 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5244
5245 // Determine the original source input.
5246 const Action *SourceAction = &JA;
5247 while (SourceAction->getKind() != Action::InputClass) {
5248 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5249 SourceAction = SourceAction->getInputs()[0];
5250 }
5251
5252 // Forward -g and handle debug info related flags, assuming we are dealing
5253 // with an actual assembly file.
5254 bool WantDebug = false;
5255 unsigned DwarfVersion = 0;
5256 Args.ClaimAllArgs(options::OPT_g_Group);
5257 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5258 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5259 !A->getOption().matches(options::OPT_ggdb0);
5260 if (WantDebug)
5261 DwarfVersion = DwarfVersionNum(A->getSpelling());
5262 }
5263 if (DwarfVersion == 0)
5264 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5265
5266 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5267
5268 if (SourceAction->getType() == types::TY_Asm ||
5269 SourceAction->getType() == types::TY_PP_Asm) {
5270 // You might think that it would be ok to set DebugInfoKind outside of
5271 // the guard for source type, however there is a test which asserts
5272 // that some assembler invocation receives no -debug-info-kind,
5273 // and it's not clear whether that test is just overly restrictive.
5274 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
5275 : codegenoptions::NoDebugInfo);
5276 // Add the -fdebug-compilation-dir flag if needed.
5277 addDebugCompDirArg(Args, CmdArgs);
5278
5279 // Set the AT_producer to the clang version when using the integrated
5280 // assembler on assembly source files.
5281 CmdArgs.push_back("-dwarf-debug-producer");
5282 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
5283
5284 // And pass along -I options
5285 Args.AddAllArgs(CmdArgs, options::OPT_I);
5286 }
5287 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
5288 llvm::DebuggerKind::Default);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00005289 RenderDebugInfoCompressionArgs(Args, CmdArgs, D);
5290
David L. Jonesf561aba2017-03-08 01:02:16 +00005291
5292 // Handle -fPIC et al -- the relocation-model affects the assembler
5293 // for some targets.
5294 llvm::Reloc::Model RelocationModel;
5295 unsigned PICLevel;
5296 bool IsPIE;
5297 std::tie(RelocationModel, PICLevel, IsPIE) =
5298 ParsePICArgs(getToolChain(), Args);
5299
5300 const char *RMName = RelocationModelName(RelocationModel);
5301 if (RMName) {
5302 CmdArgs.push_back("-mrelocation-model");
5303 CmdArgs.push_back(RMName);
5304 }
5305
5306 // Optionally embed the -cc1as level arguments into the debug info, for build
5307 // analysis.
5308 if (getToolChain().UseDwarfDebugFlags()) {
5309 ArgStringList OriginalArgs;
5310 for (const auto &Arg : Args)
5311 Arg->render(Args, OriginalArgs);
5312
5313 SmallString<256> Flags;
5314 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5315 Flags += Exec;
5316 for (const char *OriginalArg : OriginalArgs) {
5317 SmallString<128> EscapedArg;
5318 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5319 Flags += " ";
5320 Flags += EscapedArg;
5321 }
5322 CmdArgs.push_back("-dwarf-debug-flags");
5323 CmdArgs.push_back(Args.MakeArgString(Flags));
5324 }
5325
5326 // FIXME: Add -static support, once we have it.
5327
5328 // Add target specific flags.
5329 switch (getToolChain().getArch()) {
5330 default:
5331 break;
5332
5333 case llvm::Triple::mips:
5334 case llvm::Triple::mipsel:
5335 case llvm::Triple::mips64:
5336 case llvm::Triple::mips64el:
5337 AddMIPSTargetArgs(Args, CmdArgs);
5338 break;
5339
5340 case llvm::Triple::x86:
5341 case llvm::Triple::x86_64:
5342 AddX86TargetArgs(Args, CmdArgs);
5343 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00005344
5345 case llvm::Triple::arm:
5346 case llvm::Triple::armeb:
5347 case llvm::Triple::thumb:
5348 case llvm::Triple::thumbeb:
5349 // This isn't in AddARMTargetArgs because we want to do this for assembly
5350 // only, not C/C++.
5351 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
5352 options::OPT_mno_default_build_attributes, true)) {
5353 CmdArgs.push_back("-mllvm");
5354 CmdArgs.push_back("-arm-add-build-attributes");
5355 }
5356 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00005357 }
5358
5359 // Consume all the warning flags. Usually this would be handled more
5360 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5361 // doesn't handle that so rather than warning about unused flags that are
5362 // actually used, we'll lie by omission instead.
5363 // FIXME: Stop lying and consume only the appropriate driver flags
5364 Args.ClaimAllArgs(options::OPT_W_Group);
5365
5366 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5367 getToolChain().getDriver());
5368
5369 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5370
5371 assert(Output.isFilename() && "Unexpected lipo output.");
5372 CmdArgs.push_back("-o");
5373 CmdArgs.push_back(Output.getFilename());
5374
5375 assert(Input.isFilename() && "Invalid input.");
5376 CmdArgs.push_back(Input.getFilename());
5377
5378 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5379 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5380
5381 // Handle the debug info splitting at object creation time if we're
5382 // creating an object.
5383 // TODO: Currently only works on linux with newer objcopy.
5384 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5385 getToolChain().getTriple().isOSLinux())
5386 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5387 SplitDebugName(Args, Input));
5388}
5389
5390// Begin OffloadBundler
5391
5392void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5393 const InputInfo &Output,
5394 const InputInfoList &Inputs,
5395 const llvm::opt::ArgList &TCArgs,
5396 const char *LinkingOutput) const {
5397 // The version with only one output is expected to refer to a bundling job.
5398 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5399
5400 // The bundling command looks like this:
5401 // clang-offload-bundler -type=bc
5402 // -targets=host-triple,openmp-triple1,openmp-triple2
5403 // -outputs=input_file
5404 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5405
5406 ArgStringList CmdArgs;
5407
5408 // Get the type.
5409 CmdArgs.push_back(TCArgs.MakeArgString(
5410 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5411
5412 assert(JA.getInputs().size() == Inputs.size() &&
5413 "Not have inputs for all dependence actions??");
5414
5415 // Get the targets.
5416 SmallString<128> Triples;
5417 Triples += "-targets=";
5418 for (unsigned I = 0; I < Inputs.size(); ++I) {
5419 if (I)
5420 Triples += ',';
5421
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005422 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00005423 Action::OffloadKind CurKind = Action::OFK_Host;
5424 const ToolChain *CurTC = &getToolChain();
5425 const Action *CurDep = JA.getInputs()[I];
5426
5427 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005428 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00005429 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005430 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00005431 CurKind = A->getOffloadingDeviceKind();
5432 CurTC = TC;
5433 });
5434 }
5435 Triples += Action::GetOffloadKindName(CurKind);
5436 Triples += '-';
5437 Triples += CurTC->getTriple().normalize();
5438 }
5439 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5440
5441 // Get bundled file command.
5442 CmdArgs.push_back(
5443 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5444
5445 // Get unbundled files command.
5446 SmallString<128> UB;
5447 UB += "-inputs=";
5448 for (unsigned I = 0; I < Inputs.size(); ++I) {
5449 if (I)
5450 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005451
5452 // Find ToolChain for this input.
5453 const ToolChain *CurTC = &getToolChain();
5454 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
5455 CurTC = nullptr;
5456 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
5457 assert(CurTC == nullptr && "Expected one dependence!");
5458 CurTC = TC;
5459 });
5460 }
5461 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005462 }
5463 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5464
5465 // All the inputs are encoded as commands.
5466 C.addCommand(llvm::make_unique<Command>(
5467 JA, *this,
5468 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5469 CmdArgs, None));
5470}
5471
5472void OffloadBundler::ConstructJobMultipleOutputs(
5473 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5474 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5475 const char *LinkingOutput) const {
5476 // The version with multiple outputs is expected to refer to a unbundling job.
5477 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5478
5479 // The unbundling command looks like this:
5480 // clang-offload-bundler -type=bc
5481 // -targets=host-triple,openmp-triple1,openmp-triple2
5482 // -inputs=input_file
5483 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5484 // -unbundle
5485
5486 ArgStringList CmdArgs;
5487
5488 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5489 InputInfo Input = Inputs.front();
5490
5491 // Get the type.
5492 CmdArgs.push_back(TCArgs.MakeArgString(
5493 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5494
5495 // Get the targets.
5496 SmallString<128> Triples;
5497 Triples += "-targets=";
5498 auto DepInfo = UA.getDependentActionsInfo();
5499 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5500 if (I)
5501 Triples += ',';
5502
5503 auto &Dep = DepInfo[I];
5504 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5505 Triples += '-';
5506 Triples += Dep.DependentToolChain->getTriple().normalize();
5507 }
5508
5509 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5510
5511 // Get bundled file command.
5512 CmdArgs.push_back(
5513 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5514
5515 // Get unbundled files command.
5516 SmallString<128> UB;
5517 UB += "-outputs=";
5518 for (unsigned I = 0; I < Outputs.size(); ++I) {
5519 if (I)
5520 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00005521 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00005522 }
5523 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5524 CmdArgs.push_back("-unbundle");
5525
5526 // All the inputs are encoded as commands.
5527 C.addCommand(llvm::make_unique<Command>(
5528 JA, *this,
5529 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5530 CmdArgs, None));
5531}