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