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