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