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