blob: 17c860f88dd0f6dbde0c0681455e82eb97dc1fe9 [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
2731 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
2732 Args.ClaimAllArgs(options::OPT_g_flags_Group);
2733
2734 // Column info is included by default for everything except PS4 and CodeView.
2735 // Clang doesn't track end columns, just starting columns, which, in theory,
2736 // is fine for CodeView (and PDB). In practice, however, the Microsoft
2737 // debuggers don't handle missing end columns well, so it's better not to
2738 // include any column info.
2739 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
2740 /*Default=*/ !IsPS4CPU && !(IsWindowsMSVC && EmitCodeView)))
2741 CmdArgs.push_back("-dwarf-column-info");
2742
2743 // FIXME: Move backend command line options to the module.
2744 // If -gline-tables-only is the last option it wins.
2745 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
2746 Args.hasArg(options::OPT_gmodules)) {
2747 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2748 CmdArgs.push_back("-dwarf-ext-refs");
2749 CmdArgs.push_back("-fmodule-format=obj");
2750 }
2751
2752 // -gsplit-dwarf should turn on -g and enable the backend dwarf
2753 // splitting and extraction.
2754 // FIXME: Currently only works on Linux.
2755 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
2756 if (!splitDwarfInlining)
2757 CmdArgs.push_back("-fno-split-dwarf-inlining");
2758 if (DebugInfoKind == codegenoptions::NoDebugInfo)
2759 DebugInfoKind = codegenoptions::LimitedDebugInfo;
2760 CmdArgs.push_back("-backend-option");
2761 CmdArgs.push_back("-split-dwarf=Enable");
2762 }
2763
2764 // After we've dealt with all combinations of things that could
2765 // make DebugInfoKind be other than None or DebugLineTablesOnly,
2766 // figure out if we need to "upgrade" it to standalone debug info.
2767 // We parse these two '-f' options whether or not they will be used,
2768 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
2769 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
2770 options::OPT_fno_standalone_debug,
2771 getToolChain().GetDefaultStandaloneDebug());
2772 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
2773 DebugInfoKind = codegenoptions::FullDebugInfo;
2774 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
2775 DebuggerTuning);
2776
2777 // -fdebug-macro turns on macro debug info generation.
2778 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
2779 false))
2780 CmdArgs.push_back("-debug-info-macro");
2781
2782 // -ggnu-pubnames turns on gnu style pubnames in the backend.
2783 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
2784 CmdArgs.push_back("-backend-option");
2785 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
2786 }
2787
2788 // -gdwarf-aranges turns on the emission of the aranges section in the
2789 // backend.
2790 // Always enabled on the PS4.
2791 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
2792 CmdArgs.push_back("-backend-option");
2793 CmdArgs.push_back("-generate-arange-section");
2794 }
2795
2796 if (Args.hasFlag(options::OPT_fdebug_types_section,
2797 options::OPT_fno_debug_types_section, false)) {
2798 CmdArgs.push_back("-backend-option");
2799 CmdArgs.push_back("-generate-type-units");
2800 }
2801
2802 bool UseSeparateSections = isUseSeparateSections(Triple);
2803
2804 if (Args.hasFlag(options::OPT_ffunction_sections,
2805 options::OPT_fno_function_sections, UseSeparateSections)) {
2806 CmdArgs.push_back("-ffunction-sections");
2807 }
2808
2809 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
2810 UseSeparateSections)) {
2811 CmdArgs.push_back("-fdata-sections");
2812 }
2813
2814 if (!Args.hasFlag(options::OPT_funique_section_names,
2815 options::OPT_fno_unique_section_names, true))
2816 CmdArgs.push_back("-fno-unique-section-names");
2817
2818 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
2819
2820 if (Args.hasFlag(options::OPT_fxray_instrument,
2821 options::OPT_fnoxray_instrument, false)) {
2822 const char *const XRayInstrumentOption = "-fxray-instrument";
2823 if (Triple.getOS() == llvm::Triple::Linux)
2824 switch (Triple.getArch()) {
2825 case llvm::Triple::x86_64:
2826 case llvm::Triple::arm:
2827 case llvm::Triple::aarch64:
2828 case llvm::Triple::ppc64le:
2829 case llvm::Triple::mips:
2830 case llvm::Triple::mipsel:
2831 case llvm::Triple::mips64:
2832 case llvm::Triple::mips64el:
2833 // Supported.
2834 break;
2835 default:
2836 D.Diag(diag::err_drv_clang_unsupported)
2837 << (std::string(XRayInstrumentOption) + " on " + Triple.str());
2838 }
2839 else
2840 D.Diag(diag::err_drv_clang_unsupported)
2841 << (std::string(XRayInstrumentOption) + " on non-Linux target OS");
2842 CmdArgs.push_back(XRayInstrumentOption);
2843 if (const Arg *A =
2844 Args.getLastArg(options::OPT_fxray_instruction_threshold_,
2845 options::OPT_fxray_instruction_threshold_EQ)) {
2846 CmdArgs.push_back("-fxray-instruction-threshold");
2847 CmdArgs.push_back(A->getValue());
2848 }
2849 }
2850
2851 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
2852
2853 // Add runtime flag for PS4 when PGO or Coverage are enabled.
2854 if (getToolChain().getTriple().isPS4CPU())
2855 PS4cpu::addProfileRTArgs(getToolChain(), Args, CmdArgs);
2856
2857 // Pass options for controlling the default header search paths.
2858 if (Args.hasArg(options::OPT_nostdinc)) {
2859 CmdArgs.push_back("-nostdsysteminc");
2860 CmdArgs.push_back("-nobuiltininc");
2861 } else {
2862 if (Args.hasArg(options::OPT_nostdlibinc))
2863 CmdArgs.push_back("-nostdsysteminc");
2864 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
2865 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
2866 }
2867
2868 // Pass the path to compiler resource files.
2869 CmdArgs.push_back("-resource-dir");
2870 CmdArgs.push_back(D.ResourceDir.c_str());
2871
2872 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
2873
2874 bool ARCMTEnabled = false;
2875 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2876 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2877 options::OPT_ccc_arcmt_modify,
2878 options::OPT_ccc_arcmt_migrate)) {
2879 ARCMTEnabled = true;
2880 switch (A->getOption().getID()) {
2881 default:
2882 llvm_unreachable("missed a case");
2883 case options::OPT_ccc_arcmt_check:
2884 CmdArgs.push_back("-arcmt-check");
2885 break;
2886 case options::OPT_ccc_arcmt_modify:
2887 CmdArgs.push_back("-arcmt-modify");
2888 break;
2889 case options::OPT_ccc_arcmt_migrate:
2890 CmdArgs.push_back("-arcmt-migrate");
2891 CmdArgs.push_back("-mt-migrate-directory");
2892 CmdArgs.push_back(A->getValue());
2893
2894 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2895 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2896 break;
2897 }
2898 }
2899 } else {
2900 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2901 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2902 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2903 }
2904
2905 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2906 if (ARCMTEnabled) {
2907 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
2908 << "-ccc-arcmt-migrate";
2909 }
2910 CmdArgs.push_back("-mt-migrate-directory");
2911 CmdArgs.push_back(A->getValue());
2912
2913 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2914 options::OPT_objcmt_migrate_subscripting,
2915 options::OPT_objcmt_migrate_property)) {
2916 // None specified, means enable them all.
2917 CmdArgs.push_back("-objcmt-migrate-literals");
2918 CmdArgs.push_back("-objcmt-migrate-subscripting");
2919 CmdArgs.push_back("-objcmt-migrate-property");
2920 } else {
2921 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2922 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2923 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2924 }
2925 } else {
2926 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2927 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2928 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2929 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2930 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2931 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2932 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2933 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2934 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2935 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2936 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2937 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2938 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2939 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2940 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2941 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2942 }
2943
2944 // Add preprocessing options like -I, -D, etc. if we are using the
2945 // preprocessor.
2946 //
2947 // FIXME: Support -fpreprocessed
2948 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
2949 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
2950
2951 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
2952 // that "The compiler can only warn and ignore the option if not recognized".
2953 // When building with ccache, it will pass -D options to clang even on
2954 // preprocessed inputs and configure concludes that -fPIC is not supported.
2955 Args.ClaimAllArgs(options::OPT_D);
2956
2957 // Manually translate -O4 to -O3; let clang reject others.
2958 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2959 if (A->getOption().matches(options::OPT_O4)) {
2960 CmdArgs.push_back("-O3");
2961 D.Diag(diag::warn_O4_is_O3);
2962 } else {
2963 A->render(Args, CmdArgs);
2964 }
2965 }
2966
2967 // Warn about ignored options to clang.
2968 for (const Arg *A :
2969 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
2970 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
2971 A->claim();
2972 }
2973
2974 claimNoWarnArgs(Args);
2975
2976 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
2977
2978 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
2979 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
2980 CmdArgs.push_back("-pedantic");
2981 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
2982 Args.AddLastArg(CmdArgs, options::OPT_w);
2983
2984 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
2985 // (-ansi is equivalent to -std=c89 or -std=c++98).
2986 //
2987 // If a std is supplied, only add -trigraphs if it follows the
2988 // option.
2989 bool ImplyVCPPCXXVer = false;
2990 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
2991 if (Std->getOption().matches(options::OPT_ansi))
2992 if (types::isCXX(InputType))
2993 CmdArgs.push_back("-std=c++98");
2994 else
2995 CmdArgs.push_back("-std=c89");
2996 else
2997 Std->render(Args, CmdArgs);
2998
2999 // If -f(no-)trigraphs appears after the language standard flag, honor it.
3000 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
3001 options::OPT_ftrigraphs,
3002 options::OPT_fno_trigraphs))
3003 if (A != Std)
3004 A->render(Args, CmdArgs);
3005 } else {
3006 // Honor -std-default.
3007 //
3008 // FIXME: Clang doesn't correctly handle -std= when the input language
3009 // doesn't match. For the time being just ignore this for C++ inputs;
3010 // eventually we want to do all the standard defaulting here instead of
3011 // splitting it between the driver and clang -cc1.
3012 if (!types::isCXX(InputType))
3013 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
3014 /*Joined=*/true);
3015 else if (IsWindowsMSVC)
3016 ImplyVCPPCXXVer = true;
3017
3018 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
3019 options::OPT_fno_trigraphs);
3020 }
3021
3022 // GCC's behavior for -Wwrite-strings is a bit strange:
3023 // * In C, this "warning flag" changes the types of string literals from
3024 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
3025 // for the discarded qualifier.
3026 // * In C++, this is just a normal warning flag.
3027 //
3028 // Implementing this warning correctly in C is hard, so we follow GCC's
3029 // behavior for now. FIXME: Directly diagnose uses of a string literal as
3030 // a non-const char* in C, rather than using this crude hack.
3031 if (!types::isCXX(InputType)) {
3032 // FIXME: This should behave just like a warning flag, and thus should also
3033 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
3034 Arg *WriteStrings =
3035 Args.getLastArg(options::OPT_Wwrite_strings,
3036 options::OPT_Wno_write_strings, options::OPT_w);
3037 if (WriteStrings &&
3038 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
3039 CmdArgs.push_back("-fconst-strings");
3040 }
3041
3042 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
3043 // during C++ compilation, which it is by default. GCC keeps this define even
3044 // in the presence of '-w', match this behavior bug-for-bug.
3045 if (types::isCXX(InputType) &&
3046 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
3047 true)) {
3048 CmdArgs.push_back("-fdeprecated-macro");
3049 }
3050
3051 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
3052 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
3053 if (Asm->getOption().matches(options::OPT_fasm))
3054 CmdArgs.push_back("-fgnu-keywords");
3055 else
3056 CmdArgs.push_back("-fno-gnu-keywords");
3057 }
3058
3059 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
3060 CmdArgs.push_back("-fno-dwarf-directory-asm");
3061
3062 if (ShouldDisableAutolink(Args, getToolChain()))
3063 CmdArgs.push_back("-fno-autolink");
3064
3065 // Add in -fdebug-compilation-dir if necessary.
3066 addDebugCompDirArg(Args, CmdArgs);
3067
3068 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
3069 StringRef Map = A->getValue();
3070 if (Map.find('=') == StringRef::npos)
3071 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
3072 else
3073 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
3074 A->claim();
3075 }
3076
3077 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
3078 options::OPT_ftemplate_depth_EQ)) {
3079 CmdArgs.push_back("-ftemplate-depth");
3080 CmdArgs.push_back(A->getValue());
3081 }
3082
3083 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
3084 CmdArgs.push_back("-foperator-arrow-depth");
3085 CmdArgs.push_back(A->getValue());
3086 }
3087
3088 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
3089 CmdArgs.push_back("-fconstexpr-depth");
3090 CmdArgs.push_back(A->getValue());
3091 }
3092
3093 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
3094 CmdArgs.push_back("-fconstexpr-steps");
3095 CmdArgs.push_back(A->getValue());
3096 }
3097
3098 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
3099 CmdArgs.push_back("-fbracket-depth");
3100 CmdArgs.push_back(A->getValue());
3101 }
3102
3103 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
3104 options::OPT_Wlarge_by_value_copy_def)) {
3105 if (A->getNumValues()) {
3106 StringRef bytes = A->getValue();
3107 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
3108 } else
3109 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
3110 }
3111
3112 if (Args.hasArg(options::OPT_relocatable_pch))
3113 CmdArgs.push_back("-relocatable-pch");
3114
3115 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
3116 CmdArgs.push_back("-fconstant-string-class");
3117 CmdArgs.push_back(A->getValue());
3118 }
3119
3120 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
3121 CmdArgs.push_back("-ftabstop");
3122 CmdArgs.push_back(A->getValue());
3123 }
3124
3125 CmdArgs.push_back("-ferror-limit");
3126 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
3127 CmdArgs.push_back(A->getValue());
3128 else
3129 CmdArgs.push_back("19");
3130
3131 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
3132 CmdArgs.push_back("-fmacro-backtrace-limit");
3133 CmdArgs.push_back(A->getValue());
3134 }
3135
3136 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
3137 CmdArgs.push_back("-ftemplate-backtrace-limit");
3138 CmdArgs.push_back(A->getValue());
3139 }
3140
3141 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
3142 CmdArgs.push_back("-fconstexpr-backtrace-limit");
3143 CmdArgs.push_back(A->getValue());
3144 }
3145
3146 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
3147 CmdArgs.push_back("-fspell-checking-limit");
3148 CmdArgs.push_back(A->getValue());
3149 }
3150
3151 // Pass -fmessage-length=.
3152 CmdArgs.push_back("-fmessage-length");
3153 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
3154 CmdArgs.push_back(A->getValue());
3155 } else {
3156 // If -fmessage-length=N was not specified, determine whether this is a
3157 // terminal and, if so, implicitly define -fmessage-length appropriately.
3158 unsigned N = llvm::sys::Process::StandardErrColumns();
3159 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
3160 }
3161
3162 // -fvisibility= and -fvisibility-ms-compat are of a piece.
3163 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
3164 options::OPT_fvisibility_ms_compat)) {
3165 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
3166 CmdArgs.push_back("-fvisibility");
3167 CmdArgs.push_back(A->getValue());
3168 } else {
3169 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
3170 CmdArgs.push_back("-fvisibility");
3171 CmdArgs.push_back("hidden");
3172 CmdArgs.push_back("-ftype-visibility");
3173 CmdArgs.push_back("default");
3174 }
3175 }
3176
3177 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
3178
3179 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
3180
3181 // -fhosted is default.
3182 bool IsHosted = true;
3183 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
3184 KernelOrKext) {
3185 CmdArgs.push_back("-ffreestanding");
3186 IsHosted = false;
3187 }
3188
3189 // Forward -f (flag) options which we can pass directly.
3190 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
3191 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
3192 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
3193 // Emulated TLS is enabled by default on Android, and can be enabled manually
3194 // with -femulated-tls.
3195 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
3196 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
3197 EmulatedTLSDefault))
3198 CmdArgs.push_back("-femulated-tls");
3199 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00003200 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00003201 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00003202
David L. Jonesf561aba2017-03-08 01:02:16 +00003203 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
3204 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
3205
3206 // Forward flags for OpenMP. We don't do this if the current action is an
3207 // device offloading action other than OpenMP.
3208 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3209 options::OPT_fno_openmp, false) &&
3210 (JA.isDeviceOffloading(Action::OFK_None) ||
3211 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
3212 switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
3213 case Driver::OMPRT_OMP:
3214 case Driver::OMPRT_IOMP5:
3215 // Clang can generate useful OpenMP code for these two runtime libraries.
3216 CmdArgs.push_back("-fopenmp");
3217
3218 // If no option regarding the use of TLS in OpenMP codegeneration is
3219 // given, decide a default based on the target. Otherwise rely on the
3220 // options and pass the right information to the frontend.
3221 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
3222 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
3223 CmdArgs.push_back("-fnoopenmp-use-tls");
3224 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
3225 break;
3226 default:
3227 // By default, if Clang doesn't know how to generate useful OpenMP code
3228 // for a specific runtime library, we just don't pass the '-fopenmp' flag
3229 // down to the actual compilation.
3230 // FIXME: It would be better to have a mode which *only* omits IR
3231 // generation based on the OpenMP support so that we get consistent
3232 // semantic analysis, etc.
3233 break;
3234 }
3235 }
3236
3237 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
3238 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
3239
David L. Jonesf561aba2017-03-08 01:02:16 +00003240 if (getToolChain().SupportsProfiling())
3241 Args.AddLastArg(CmdArgs, options::OPT_pg);
3242
3243 if (getToolChain().SupportsProfiling())
3244 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
3245
3246 // -flax-vector-conversions is default.
3247 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
3248 options::OPT_fno_lax_vector_conversions))
3249 CmdArgs.push_back("-fno-lax-vector-conversions");
3250
3251 if (Args.getLastArg(options::OPT_fapple_kext) ||
3252 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
3253 CmdArgs.push_back("-fapple-kext");
3254
3255 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
3256 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
3257 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
3258 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
3259 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
3260
3261 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
3262 CmdArgs.push_back("-ftrapv-handler");
3263 CmdArgs.push_back(A->getValue());
3264 }
3265
3266 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
3267
3268 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
3269 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
3270 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
3271 if (A->getOption().matches(options::OPT_fwrapv))
3272 CmdArgs.push_back("-fwrapv");
3273 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
3274 options::OPT_fno_strict_overflow)) {
3275 if (A->getOption().matches(options::OPT_fno_strict_overflow))
3276 CmdArgs.push_back("-fwrapv");
3277 }
3278
3279 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
3280 options::OPT_fno_reroll_loops))
3281 if (A->getOption().matches(options::OPT_freroll_loops))
3282 CmdArgs.push_back("-freroll-loops");
3283
3284 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
3285 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
3286 options::OPT_fno_unroll_loops);
3287
3288 Args.AddLastArg(CmdArgs, options::OPT_pthread);
3289
3290 // -stack-protector=0 is default.
3291 unsigned StackProtectorLevel = 0;
3292 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3293 // doesn't even have a stack!
3294 if (!Triple.isNVPTX()) {
3295 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3296 options::OPT_fstack_protector_all,
3297 options::OPT_fstack_protector_strong,
3298 options::OPT_fstack_protector)) {
3299 if (A->getOption().matches(options::OPT_fstack_protector)) {
3300 StackProtectorLevel = std::max<unsigned>(
3301 LangOptions::SSPOn,
3302 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
3303 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3304 StackProtectorLevel = LangOptions::SSPStrong;
3305 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3306 StackProtectorLevel = LangOptions::SSPReq;
3307 } else {
3308 StackProtectorLevel =
3309 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
3310 // Only use a default stack protector on Darwin in case -ffreestanding
3311 // is not specified.
3312 if (Triple.isOSDarwin() && !IsHosted)
3313 StackProtectorLevel = 0;
3314 }
3315 }
3316 if (StackProtectorLevel) {
3317 CmdArgs.push_back("-stack-protector");
3318 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3319 }
3320
3321 // --param ssp-buffer-size=
3322 for (const Arg *A : Args.filtered(options::OPT__param)) {
3323 StringRef Str(A->getValue());
3324 if (Str.startswith("ssp-buffer-size=")) {
3325 if (StackProtectorLevel) {
3326 CmdArgs.push_back("-stack-protector-buffer-size");
3327 // FIXME: Verify the argument is a valid integer.
3328 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3329 }
3330 A->claim();
3331 }
3332 }
3333
3334 // Translate -mstackrealign
3335 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
3336 false))
3337 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
3338
3339 if (Args.hasArg(options::OPT_mstack_alignment)) {
3340 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
3341 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
3342 }
3343
3344 if (Args.hasArg(options::OPT_mstack_probe_size)) {
3345 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
3346
3347 if (!Size.empty())
3348 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
3349 else
3350 CmdArgs.push_back("-mstack-probe-size=0");
3351 }
3352
3353 switch (getToolChain().getArch()) {
3354 case llvm::Triple::aarch64:
3355 case llvm::Triple::aarch64_be:
3356 case llvm::Triple::arm:
3357 case llvm::Triple::armeb:
3358 case llvm::Triple::thumb:
3359 case llvm::Triple::thumbeb:
3360 CmdArgs.push_back("-fallow-half-arguments-and-returns");
3361 break;
3362
3363 default:
3364 break;
3365 }
3366
3367 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
3368 options::OPT_mno_restrict_it)) {
3369 if (A->getOption().matches(options::OPT_mrestrict_it)) {
3370 CmdArgs.push_back("-backend-option");
3371 CmdArgs.push_back("-arm-restrict-it");
3372 } else {
3373 CmdArgs.push_back("-backend-option");
3374 CmdArgs.push_back("-arm-no-restrict-it");
3375 }
3376 } else if (Triple.isOSWindows() &&
3377 (Triple.getArch() == llvm::Triple::arm ||
3378 Triple.getArch() == llvm::Triple::thumb)) {
3379 // Windows on ARM expects restricted IT blocks
3380 CmdArgs.push_back("-backend-option");
3381 CmdArgs.push_back("-arm-restrict-it");
3382 }
3383
3384 // Forward -cl options to -cc1
3385 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
3386 CmdArgs.push_back("-cl-opt-disable");
3387 }
3388 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
3389 CmdArgs.push_back("-cl-strict-aliasing");
3390 }
3391 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
3392 CmdArgs.push_back("-cl-single-precision-constant");
3393 }
3394 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
3395 CmdArgs.push_back("-cl-finite-math-only");
3396 }
3397 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
3398 CmdArgs.push_back("-cl-kernel-arg-info");
3399 }
3400 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
3401 CmdArgs.push_back("-cl-unsafe-math-optimizations");
3402 }
3403 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
3404 CmdArgs.push_back("-cl-fast-relaxed-math");
3405 }
3406 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
3407 CmdArgs.push_back("-cl-mad-enable");
3408 }
3409 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
3410 CmdArgs.push_back("-cl-no-signed-zeros");
3411 }
3412 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3413 std::string CLStdStr = "-cl-std=";
3414 CLStdStr += A->getValue();
3415 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3416 }
3417 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
3418 CmdArgs.push_back("-cl-denorms-are-zero");
3419 }
3420 if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
3421 CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
3422 }
3423
3424 // Forward -f options with positive and negative forms; we translate
3425 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00003426 if (Arg *A = getLastProfileSampleUseArg(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003427 StringRef fname = A->getValue();
3428 if (!llvm::sys::fs::exists(fname))
3429 D.Diag(diag::err_drv_no_such_file) << fname;
3430 else
3431 A->render(Args, CmdArgs);
3432 }
3433
3434 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3435 options::OPT_fno_debug_info_for_profiling, false))
3436 CmdArgs.push_back("-fdebug-info-for-profiling");
3437
3438 // -fbuiltin is default unless -mkernel is used.
3439 bool UseBuiltins =
3440 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3441 !Args.hasArg(options::OPT_mkernel));
3442 if (!UseBuiltins)
3443 CmdArgs.push_back("-fno-builtin");
3444
3445 // -ffreestanding implies -fno-builtin.
3446 if (Args.hasArg(options::OPT_ffreestanding))
3447 UseBuiltins = false;
3448
3449 // Process the -fno-builtin-* options.
3450 for (const auto &Arg : Args) {
3451 const Option &O = Arg->getOption();
3452 if (!O.matches(options::OPT_fno_builtin_))
3453 continue;
3454
3455 Arg->claim();
3456 // If -fno-builtin is specified, then there's no need to pass the option to
3457 // the frontend.
3458 if (!UseBuiltins)
3459 continue;
3460
3461 StringRef FuncName = Arg->getValue();
3462 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3463 }
3464
3465 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3466 options::OPT_fno_assume_sane_operator_new))
3467 CmdArgs.push_back("-fno-assume-sane-operator-new");
3468
3469 // -fblocks=0 is default.
3470 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
3471 getToolChain().IsBlocksDefault()) ||
3472 (Args.hasArg(options::OPT_fgnu_runtime) &&
3473 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
3474 !Args.hasArg(options::OPT_fno_blocks))) {
3475 CmdArgs.push_back("-fblocks");
3476
3477 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
3478 !getToolChain().hasBlocksRuntime())
3479 CmdArgs.push_back("-fblocks-runtime-optional");
3480 }
3481
3482 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
3483 false) &&
3484 types::isCXX(InputType)) {
3485 CmdArgs.push_back("-fcoroutines-ts");
3486 }
3487
3488 // -fmodules enables the use of precompiled modules (off by default).
3489 // Users can pass -fno-cxx-modules to turn off modules support for
3490 // C++/Objective-C++ programs.
3491 bool HaveClangModules = false;
3492 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3493 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3494 options::OPT_fno_cxx_modules, true);
3495 if (AllowedInCXX || !types::isCXX(InputType)) {
3496 CmdArgs.push_back("-fmodules");
3497 HaveClangModules = true;
3498 }
3499 }
3500
3501 bool HaveAnyModules = HaveClangModules;
3502 if (Args.hasArg(options::OPT_fmodules_ts)) {
3503 CmdArgs.push_back("-fmodules-ts");
3504 HaveAnyModules = true;
3505 }
3506
3507 // -fmodule-maps enables implicit reading of module map files. By default,
3508 // this is enabled if we are using Clang's flavor of precompiled modules.
3509 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3510 options::OPT_fno_implicit_module_maps, HaveClangModules)) {
3511 CmdArgs.push_back("-fimplicit-module-maps");
3512 }
3513
3514 // -fmodules-decluse checks that modules used are declared so (off by
3515 // default).
3516 if (Args.hasFlag(options::OPT_fmodules_decluse,
3517 options::OPT_fno_modules_decluse, false)) {
3518 CmdArgs.push_back("-fmodules-decluse");
3519 }
3520
3521 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3522 // all #included headers are part of modules.
3523 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3524 options::OPT_fno_modules_strict_decluse, false)) {
3525 CmdArgs.push_back("-fmodules-strict-decluse");
3526 }
3527
3528 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3529 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3530 options::OPT_fno_implicit_modules, HaveClangModules)) {
3531 if (HaveAnyModules)
3532 CmdArgs.push_back("-fno-implicit-modules");
3533 } else if (HaveAnyModules) {
3534 // -fmodule-cache-path specifies where our implicitly-built module files
3535 // should be written.
3536 SmallString<128> Path;
3537 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3538 Path = A->getValue();
3539 if (C.isForDiagnostics()) {
3540 // When generating crash reports, we want to emit the modules along with
3541 // the reproduction sources, so we ignore any provided module path.
3542 Path = Output.getFilename();
3543 llvm::sys::path::replace_extension(Path, ".cache");
3544 llvm::sys::path::append(Path, "modules");
3545 } else if (Path.empty()) {
3546 // No module path was provided: use the default.
3547 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
3548 llvm::sys::path::append(Path, "org.llvm.clang.");
3549 appendUserToPath(Path);
3550 llvm::sys::path::append(Path, "ModuleCache");
3551 }
3552 const char Arg[] = "-fmodules-cache-path=";
3553 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3554 CmdArgs.push_back(Args.MakeArgString(Path));
3555 }
3556
3557 if (HaveAnyModules) {
3558 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3559 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path))
3560 CmdArgs.push_back(Args.MakeArgString(
3561 std::string("-fprebuilt-module-path=") + A->getValue()));
3562 }
3563
3564 // -fmodule-name specifies the module that is currently being built (or
3565 // used for header checking by -fmodule-maps).
3566 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3567
3568 // -fmodule-map-file can be used to specify files containing module
3569 // definitions.
3570 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3571
3572 // -fbuiltin-module-map can be used to load the clang
3573 // builtin headers modulemap file.
3574 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3575 SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
3576 llvm::sys::path::append(BuiltinModuleMap, "include");
3577 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3578 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
3579 CmdArgs.push_back(Args.MakeArgString("-fmodule-map-file=" +
3580 BuiltinModuleMap));
3581 }
3582 }
3583
3584 // -fmodule-file can be used to specify files containing precompiled modules.
3585 if (HaveAnyModules)
3586 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3587 else
3588 Args.ClaimAllArgs(options::OPT_fmodule_file);
3589
3590 // When building modules and generating crashdumps, we need to dump a module
3591 // dependency VFS alongside the output.
3592 if (HaveClangModules && C.isForDiagnostics()) {
3593 SmallString<128> VFSDir(Output.getFilename());
3594 llvm::sys::path::replace_extension(VFSDir, ".cache");
3595 // Add the cache directory as a temp so the crash diagnostics pick it up.
3596 C.addTempFile(Args.MakeArgString(VFSDir));
3597
3598 llvm::sys::path::append(VFSDir, "vfs");
3599 CmdArgs.push_back("-module-dependency-dir");
3600 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3601 }
3602
3603 if (HaveClangModules)
3604 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3605
3606 // Pass through all -fmodules-ignore-macro arguments.
3607 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3608 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3609 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3610
3611 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3612
3613 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3614 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3615 D.Diag(diag::err_drv_argument_not_allowed_with)
3616 << A->getAsString(Args) << "-fbuild-session-timestamp";
3617
3618 llvm::sys::fs::file_status Status;
3619 if (llvm::sys::fs::status(A->getValue(), Status))
3620 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3621 CmdArgs.push_back(
3622 Args.MakeArgString("-fbuild-session-timestamp=" +
3623 Twine((uint64_t)Status.getLastModificationTime()
3624 .time_since_epoch()
3625 .count())));
3626 }
3627
3628 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3629 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3630 options::OPT_fbuild_session_file))
3631 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3632
3633 Args.AddLastArg(CmdArgs,
3634 options::OPT_fmodules_validate_once_per_build_session);
3635 }
3636
3637 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
3638 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3639
3640 // -faccess-control is default.
3641 if (Args.hasFlag(options::OPT_fno_access_control,
3642 options::OPT_faccess_control, false))
3643 CmdArgs.push_back("-fno-access-control");
3644
3645 // -felide-constructors is the default.
3646 if (Args.hasFlag(options::OPT_fno_elide_constructors,
3647 options::OPT_felide_constructors, false))
3648 CmdArgs.push_back("-fno-elide-constructors");
3649
3650 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
3651
3652 if (KernelOrKext || (types::isCXX(InputType) &&
3653 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
3654 RTTIMode == ToolChain::RM_DisabledImplicitly)))
3655 CmdArgs.push_back("-fno-rtti");
3656
3657 // -fshort-enums=0 is default for all architectures except Hexagon.
3658 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
3659 getToolChain().getArch() == llvm::Triple::hexagon))
3660 CmdArgs.push_back("-fshort-enums");
3661
3662 // -fsigned-char is default.
3663 if (Arg *A = Args.getLastArg(
3664 options::OPT_fsigned_char, options::OPT_fno_signed_char,
3665 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
3666 if (A->getOption().matches(options::OPT_funsigned_char) ||
3667 A->getOption().matches(options::OPT_fno_signed_char)) {
3668 CmdArgs.push_back("-fno-signed-char");
3669 }
3670 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
3671 CmdArgs.push_back("-fno-signed-char");
3672 }
3673
3674 // -fuse-cxa-atexit is default.
3675 if (!Args.hasFlag(
3676 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
3677 !IsWindowsCygnus && !IsWindowsGNU &&
3678 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
3679 getToolChain().getArch() != llvm::Triple::hexagon &&
3680 getToolChain().getArch() != llvm::Triple::xcore &&
3681 ((getToolChain().getTriple().getVendor() !=
3682 llvm::Triple::MipsTechnologies) ||
3683 getToolChain().getTriple().hasEnvironment())) ||
3684 KernelOrKext)
3685 CmdArgs.push_back("-fno-use-cxa-atexit");
3686
3687 // -fms-extensions=0 is default.
3688 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3689 IsWindowsMSVC))
3690 CmdArgs.push_back("-fms-extensions");
3691
3692 // -fno-use-line-directives is default.
3693 if (Args.hasFlag(options::OPT_fuse_line_directives,
3694 options::OPT_fno_use_line_directives, false))
3695 CmdArgs.push_back("-fuse-line-directives");
3696
3697 // -fms-compatibility=0 is default.
3698 if (Args.hasFlag(options::OPT_fms_compatibility,
3699 options::OPT_fno_ms_compatibility,
3700 (IsWindowsMSVC &&
3701 Args.hasFlag(options::OPT_fms_extensions,
3702 options::OPT_fno_ms_extensions, true))))
3703 CmdArgs.push_back("-fms-compatibility");
3704
3705 VersionTuple MSVT =
3706 getToolChain().computeMSVCVersion(&getToolChain().getDriver(), Args);
3707 if (!MSVT.empty())
3708 CmdArgs.push_back(
3709 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
3710
3711 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
3712 if (ImplyVCPPCXXVer) {
3713 StringRef LanguageStandard;
3714 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
3715 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
3716 .Case("c++14", "-std=c++14")
3717 .Case("c++latest", "-std=c++1z")
3718 .Default("");
3719 if (LanguageStandard.empty())
3720 D.Diag(clang::diag::warn_drv_unused_argument)
3721 << StdArg->getAsString(Args);
3722 }
3723
3724 if (LanguageStandard.empty()) {
3725 if (IsMSVC2015Compatible)
3726 LanguageStandard = "-std=c++14";
3727 else
3728 LanguageStandard = "-std=c++11";
3729 }
3730
3731 CmdArgs.push_back(LanguageStandard.data());
3732 }
3733
3734 // -fno-borland-extensions is default.
3735 if (Args.hasFlag(options::OPT_fborland_extensions,
3736 options::OPT_fno_borland_extensions, false))
3737 CmdArgs.push_back("-fborland-extensions");
3738
3739 // -fno-declspec is default, except for PS4.
3740 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
3741 getToolChain().getTriple().isPS4()))
3742 CmdArgs.push_back("-fdeclspec");
3743 else if (Args.hasArg(options::OPT_fno_declspec))
3744 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
3745
3746 // -fthreadsafe-static is default, except for MSVC compatibility versions less
3747 // than 19.
3748 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
3749 options::OPT_fno_threadsafe_statics,
3750 !IsWindowsMSVC || IsMSVC2015Compatible))
3751 CmdArgs.push_back("-fno-threadsafe-statics");
3752
3753 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
3754 // needs it.
3755 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
3756 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
3757 CmdArgs.push_back("-fdelayed-template-parsing");
3758
3759 // -fgnu-keywords default varies depending on language; only pass if
3760 // specified.
3761 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
3762 options::OPT_fno_gnu_keywords))
3763 A->render(Args, CmdArgs);
3764
3765 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
3766 false))
3767 CmdArgs.push_back("-fgnu89-inline");
3768
3769 if (Args.hasArg(options::OPT_fno_inline))
3770 CmdArgs.push_back("-fno-inline");
3771
3772 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
3773 options::OPT_finline_hint_functions,
3774 options::OPT_fno_inline_functions))
3775 InlineArg->render(Args, CmdArgs);
3776
3777 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
3778 options::OPT_fno_experimental_new_pass_manager);
3779
3780 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
3781
3782 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
3783 // legacy is the default. Except for deployment target of 10.5,
3784 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
3785 // gets ignored silently.
3786 if (objcRuntime.isNonFragile()) {
3787 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3788 options::OPT_fno_objc_legacy_dispatch,
3789 objcRuntime.isLegacyDispatchDefaultForArch(
3790 getToolChain().getArch()))) {
3791 if (getToolChain().UseObjCMixedDispatch())
3792 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3793 else
3794 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3795 }
3796 }
3797
3798 // When ObjectiveC legacy runtime is in effect on MacOSX,
3799 // turn on the option to do Array/Dictionary subscripting
3800 // by default.
3801 if (getToolChain().getArch() == llvm::Triple::x86 &&
3802 getToolChain().getTriple().isMacOSX() &&
3803 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
3804 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
3805 objcRuntime.isNeXTFamily())
3806 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3807
3808 // -fencode-extended-block-signature=1 is default.
3809 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
3810 CmdArgs.push_back("-fencode-extended-block-signature");
3811 }
3812
3813 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3814 // NOTE: This logic is duplicated in ToolChains.cpp.
3815 bool ARC = isObjCAutoRefCount(Args);
3816 if (ARC) {
3817 getToolChain().CheckObjCARC();
3818
3819 CmdArgs.push_back("-fobjc-arc");
3820
3821 // FIXME: It seems like this entire block, and several around it should be
3822 // wrapped in isObjC, but for now we just use it here as this is where it
3823 // was being used previously.
3824 if (types::isCXX(InputType) && types::isObjC(InputType)) {
3825 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3826 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3827 else
3828 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3829 }
3830
3831 // Allow the user to enable full exceptions code emission.
3832 // We define off for Objective-CC, on for Objective-C++.
3833 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3834 options::OPT_fno_objc_arc_exceptions,
3835 /*default*/ types::isCXX(InputType)))
3836 CmdArgs.push_back("-fobjc-arc-exceptions");
3837 }
3838
3839 // Silence warning for full exception code emission options when explicitly
3840 // set to use no ARC.
3841 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3842 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3843 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3844 }
3845
3846 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3847 // rewriter.
3848 if (rewriteKind != RK_None)
3849 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3850
3851 // Pass down -fobjc-weak or -fno-objc-weak if present.
3852 if (types::isObjC(InputType)) {
3853 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
3854 options::OPT_fno_objc_weak);
3855 if (!WeakArg) {
3856 // nothing to do
3857 } else if (!objcRuntime.allowsWeak()) {
3858 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3859 D.Diag(diag::err_objc_weak_unsupported);
3860 } else {
3861 WeakArg->render(Args, CmdArgs);
3862 }
3863 }
3864
3865 if (Args.hasFlag(options::OPT_fapplication_extension,
3866 options::OPT_fno_application_extension, false))
3867 CmdArgs.push_back("-fapplication-extension");
3868
3869 // Handle GCC-style exception args.
3870 if (!C.getDriver().IsCLMode())
3871 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
3872 CmdArgs);
3873
3874 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
3875 getToolChain().UseSjLjExceptions(Args))
3876 CmdArgs.push_back("-fsjlj-exceptions");
3877
3878 // C++ "sane" operator new.
3879 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
3880 options::OPT_fno_assume_sane_operator_new))
3881 CmdArgs.push_back("-fno-assume-sane-operator-new");
3882
3883 // -frelaxed-template-template-args is off by default, as it is a severe
3884 // breaking change until a corresponding change to template partial ordering
3885 // is provided.
3886 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
3887 options::OPT_fno_relaxed_template_template_args, false))
3888 CmdArgs.push_back("-frelaxed-template-template-args");
3889
3890 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
3891 // most platforms.
3892 if (Args.hasFlag(options::OPT_fsized_deallocation,
3893 options::OPT_fno_sized_deallocation, false))
3894 CmdArgs.push_back("-fsized-deallocation");
3895
3896 // -faligned-allocation is on by default in C++17 onwards and otherwise off
3897 // by default.
3898 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
3899 options::OPT_fno_aligned_allocation,
3900 options::OPT_faligned_new_EQ)) {
3901 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
3902 CmdArgs.push_back("-fno-aligned-allocation");
3903 else
3904 CmdArgs.push_back("-faligned-allocation");
3905 }
3906
3907 // The default new alignment can be specified using a dedicated option or via
3908 // a GCC-compatible option that also turns on aligned allocation.
3909 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
3910 options::OPT_faligned_new_EQ))
3911 CmdArgs.push_back(
3912 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
3913
3914 // -fconstant-cfstrings is default, and may be subject to argument translation
3915 // on Darwin.
3916 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
3917 options::OPT_fno_constant_cfstrings) ||
3918 !Args.hasFlag(options::OPT_mconstant_cfstrings,
3919 options::OPT_mno_constant_cfstrings))
3920 CmdArgs.push_back("-fno-constant-cfstrings");
3921
3922 // -fshort-wchar default varies depending on platform; only
3923 // pass if specified.
3924 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3925 options::OPT_fno_short_wchar))
3926 A->render(Args, CmdArgs);
3927
3928 // -fno-pascal-strings is default, only pass non-default.
3929 if (Args.hasFlag(options::OPT_fpascal_strings,
3930 options::OPT_fno_pascal_strings, false))
3931 CmdArgs.push_back("-fpascal-strings");
3932
3933 // Honor -fpack-struct= and -fpack-struct, if given. Note that
3934 // -fno-pack-struct doesn't apply to -fpack-struct=.
3935 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
3936 std::string PackStructStr = "-fpack-struct=";
3937 PackStructStr += A->getValue();
3938 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
3939 } else if (Args.hasFlag(options::OPT_fpack_struct,
3940 options::OPT_fno_pack_struct, false)) {
3941 CmdArgs.push_back("-fpack-struct=1");
3942 }
3943
3944 // Handle -fmax-type-align=N and -fno-type-align
3945 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
3946 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
3947 if (!SkipMaxTypeAlign) {
3948 std::string MaxTypeAlignStr = "-fmax-type-align=";
3949 MaxTypeAlignStr += A->getValue();
3950 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3951 }
3952 } else if (getToolChain().getTriple().isOSDarwin()) {
3953 if (!SkipMaxTypeAlign) {
3954 std::string MaxTypeAlignStr = "-fmax-type-align=16";
3955 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
3956 }
3957 }
3958
3959 // -fcommon is the default unless compiling kernel code or the target says so
3960 bool NoCommonDefault =
3961 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
3962 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
3963 !NoCommonDefault))
3964 CmdArgs.push_back("-fno-common");
3965
3966 // -fsigned-bitfields is default, and clang doesn't yet support
3967 // -funsigned-bitfields.
3968 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
3969 options::OPT_funsigned_bitfields))
3970 D.Diag(diag::warn_drv_clang_unsupported)
3971 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
3972
3973 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
3974 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
3975 D.Diag(diag::err_drv_clang_unsupported)
3976 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
3977
3978 // -finput_charset=UTF-8 is default. Reject others
3979 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
3980 StringRef value = inputCharset->getValue();
3981 if (!value.equals_lower("utf-8"))
3982 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
3983 << value;
3984 }
3985
3986 // -fexec_charset=UTF-8 is default. Reject others
3987 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
3988 StringRef value = execCharset->getValue();
3989 if (!value.equals_lower("utf-8"))
3990 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
3991 << value;
3992 }
3993
3994 // -fcaret-diagnostics is default.
3995 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3996 options::OPT_fno_caret_diagnostics, true))
3997 CmdArgs.push_back("-fno-caret-diagnostics");
3998
3999 // -fdiagnostics-fixit-info is default, only pass non-default.
4000 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
4001 options::OPT_fno_diagnostics_fixit_info))
4002 CmdArgs.push_back("-fno-diagnostics-fixit-info");
4003
4004 // Enable -fdiagnostics-show-option by default.
4005 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
4006 options::OPT_fno_diagnostics_show_option))
4007 CmdArgs.push_back("-fdiagnostics-show-option");
4008
4009 if (const Arg *A =
4010 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4011 CmdArgs.push_back("-fdiagnostics-show-category");
4012 CmdArgs.push_back(A->getValue());
4013 }
4014
4015 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
4016 options::OPT_fno_diagnostics_show_hotness, false))
4017 CmdArgs.push_back("-fdiagnostics-show-hotness");
4018
4019 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4020 CmdArgs.push_back("-fdiagnostics-format");
4021 CmdArgs.push_back(A->getValue());
4022 }
4023
4024 if (Arg *A = Args.getLastArg(
4025 options::OPT_fdiagnostics_show_note_include_stack,
4026 options::OPT_fno_diagnostics_show_note_include_stack)) {
4027 if (A->getOption().matches(
4028 options::OPT_fdiagnostics_show_note_include_stack))
4029 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4030 else
4031 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4032 }
4033
4034 // Color diagnostics are parsed by the driver directly from argv
4035 // and later re-parsed to construct this job; claim any possible
4036 // color diagnostic here to avoid warn_drv_unused_argument and
4037 // diagnose bad OPT_fdiagnostics_color_EQ values.
4038 for (Arg *A : Args) {
4039 const Option &O = A->getOption();
4040 if (!O.matches(options::OPT_fcolor_diagnostics) &&
4041 !O.matches(options::OPT_fdiagnostics_color) &&
4042 !O.matches(options::OPT_fno_color_diagnostics) &&
4043 !O.matches(options::OPT_fno_diagnostics_color) &&
4044 !O.matches(options::OPT_fdiagnostics_color_EQ))
4045 continue;
4046 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
4047 StringRef Value(A->getValue());
4048 if (Value != "always" && Value != "never" && Value != "auto")
4049 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4050 << ("-fdiagnostics-color=" + Value).str();
4051 }
4052 A->claim();
4053 }
4054 if (D.getDiags().getDiagnosticOptions().ShowColors)
4055 CmdArgs.push_back("-fcolor-diagnostics");
4056
4057 if (Args.hasArg(options::OPT_fansi_escape_codes))
4058 CmdArgs.push_back("-fansi-escape-codes");
4059
4060 if (!Args.hasFlag(options::OPT_fshow_source_location,
4061 options::OPT_fno_show_source_location))
4062 CmdArgs.push_back("-fno-show-source-location");
4063
4064 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4065 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4066
4067 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4068 true))
4069 CmdArgs.push_back("-fno-show-column");
4070
4071 if (!Args.hasFlag(options::OPT_fspell_checking,
4072 options::OPT_fno_spell_checking))
4073 CmdArgs.push_back("-fno-spell-checking");
4074
4075 // -fno-asm-blocks is default.
4076 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4077 false))
4078 CmdArgs.push_back("-fasm-blocks");
4079
4080 // -fgnu-inline-asm is default.
4081 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4082 options::OPT_fno_gnu_inline_asm, true))
4083 CmdArgs.push_back("-fno-gnu-inline-asm");
4084
4085 // Enable vectorization per default according to the optimization level
4086 // selected. For optimization levels that want vectorization we use the alias
4087 // option to simplify the hasFlag logic.
4088 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4089 OptSpecifier VectorizeAliasOption =
4090 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4091 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4092 options::OPT_fno_vectorize, EnableVec))
4093 CmdArgs.push_back("-vectorize-loops");
4094
4095 // -fslp-vectorize is enabled based on the optimization level selected.
4096 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4097 OptSpecifier SLPVectAliasOption =
4098 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
4099 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
4100 options::OPT_fno_slp_vectorize, EnableSLPVec))
4101 CmdArgs.push_back("-vectorize-slp");
4102
4103 // -fno-slp-vectorize-aggressive is default.
4104 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
4105 options::OPT_fno_slp_vectorize_aggressive, false))
4106 CmdArgs.push_back("-vectorize-slp-aggressive");
4107
4108 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
4109 A->render(Args, CmdArgs);
4110
4111 if (Arg *A = Args.getLastArg(
4112 options::OPT_fsanitize_undefined_strip_path_components_EQ))
4113 A->render(Args, CmdArgs);
4114
4115 // -fdollars-in-identifiers default varies depending on platform and
4116 // language; only pass if specified.
4117 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
4118 options::OPT_fno_dollars_in_identifiers)) {
4119 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
4120 CmdArgs.push_back("-fdollars-in-identifiers");
4121 else
4122 CmdArgs.push_back("-fno-dollars-in-identifiers");
4123 }
4124
4125 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
4126 // practical purposes.
4127 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
4128 options::OPT_fno_unit_at_a_time)) {
4129 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
4130 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
4131 }
4132
4133 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
4134 options::OPT_fno_apple_pragma_pack, false))
4135 CmdArgs.push_back("-fapple-pragma-pack");
4136
4137 // le32-specific flags:
4138 // -fno-math-builtin: clang should not convert math builtins to intrinsics
4139 // by default.
4140 if (getToolChain().getArch() == llvm::Triple::le32) {
4141 CmdArgs.push_back("-fno-math-builtin");
4142 }
4143
4144 if (Args.hasFlag(options::OPT_fsave_optimization_record,
4145 options::OPT_fno_save_optimization_record, false)) {
4146 CmdArgs.push_back("-opt-record-file");
4147
4148 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
4149 if (A) {
4150 CmdArgs.push_back(A->getValue());
4151 } else {
4152 SmallString<128> F;
4153 if (Output.isFilename() && (Args.hasArg(options::OPT_c) ||
4154 Args.hasArg(options::OPT_S))) {
4155 F = Output.getFilename();
4156 } else {
4157 // Use the input filename.
4158 F = llvm::sys::path::stem(Input.getBaseInput());
4159
4160 // If we're compiling for an offload architecture (i.e. a CUDA device),
4161 // we need to make the file name for the device compilation different
4162 // from the host compilation.
4163 if (!JA.isDeviceOffloading(Action::OFK_None) &&
4164 !JA.isDeviceOffloading(Action::OFK_Host)) {
4165 llvm::sys::path::replace_extension(F, "");
4166 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
4167 Triple.normalize());
4168 F += "-";
4169 F += JA.getOffloadingArch();
4170 }
4171 }
4172
4173 llvm::sys::path::replace_extension(F, "opt.yaml");
4174 CmdArgs.push_back(Args.MakeArgString(F));
4175 }
4176 }
4177
4178// Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
4179//
4180// FIXME: Now that PR4941 has been fixed this can be enabled.
4181#if 0
4182 if (getToolChain().getTriple().isOSDarwin() &&
4183 (getToolChain().getArch() == llvm::Triple::arm ||
4184 getToolChain().getArch() == llvm::Triple::thumb)) {
4185 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
4186 CmdArgs.push_back("-fno-builtin-strcat");
4187 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
4188 CmdArgs.push_back("-fno-builtin-strcpy");
4189 }
4190#endif
4191
4192 // Enable rewrite includes if the user's asked for it or if we're generating
4193 // diagnostics.
4194 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
4195 // nice to enable this when doing a crashdump for modules as well.
4196 if (Args.hasFlag(options::OPT_frewrite_includes,
4197 options::OPT_fno_rewrite_includes, false) ||
4198 (C.isForDiagnostics() && !HaveAnyModules))
4199 CmdArgs.push_back("-frewrite-includes");
4200
4201 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
4202 if (Arg *A = Args.getLastArg(options::OPT_traditional,
4203 options::OPT_traditional_cpp)) {
4204 if (isa<PreprocessJobAction>(JA))
4205 CmdArgs.push_back("-traditional-cpp");
4206 else
4207 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
4208 }
4209
4210 Args.AddLastArg(CmdArgs, options::OPT_dM);
4211 Args.AddLastArg(CmdArgs, options::OPT_dD);
4212
4213 // Handle serialized diagnostics.
4214 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
4215 CmdArgs.push_back("-serialize-diagnostic-file");
4216 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
4217 }
4218
4219 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
4220 CmdArgs.push_back("-fretain-comments-from-system-headers");
4221
4222 // Forward -fcomment-block-commands to -cc1.
4223 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
4224 // Forward -fparse-all-comments to -cc1.
4225 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
4226
4227 // Turn -fplugin=name.so into -load name.so
4228 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
4229 CmdArgs.push_back("-load");
4230 CmdArgs.push_back(A->getValue());
4231 A->claim();
4232 }
4233
4234 // Setup statistics file output.
4235 if (const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ)) {
4236 StringRef SaveStats = A->getValue();
4237
4238 SmallString<128> StatsFile;
4239 bool DoSaveStats = false;
4240 if (SaveStats == "obj") {
4241 if (Output.isFilename()) {
4242 StatsFile.assign(Output.getFilename());
4243 llvm::sys::path::remove_filename(StatsFile);
4244 }
4245 DoSaveStats = true;
4246 } else if (SaveStats == "cwd") {
4247 DoSaveStats = true;
4248 } else {
4249 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
4250 }
4251
4252 if (DoSaveStats) {
4253 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
4254 llvm::sys::path::append(StatsFile, BaseName);
4255 llvm::sys::path::replace_extension(StatsFile, "stats");
4256 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") +
4257 StatsFile));
4258 }
4259 }
4260
4261 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
4262 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00004263 // -finclude-default-header flag is for preprocessor,
4264 // do not pass it to other cc1 commands when save-temps is enabled
4265 if (C.getDriver().isSaveTempsEnabled() &&
4266 !isa<PreprocessJobAction>(JA)) {
4267 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
4268 Arg->claim();
4269 if (StringRef(Arg->getValue()) != "-finclude-default-header")
4270 CmdArgs.push_back(Arg->getValue());
4271 }
4272 }
4273 else {
4274 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
4275 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004276 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
4277 A->claim();
4278
4279 // We translate this by hand to the -cc1 argument, since nightly test uses
4280 // it and developers have been trained to spell it with -mllvm. Both
4281 // spellings are now deprecated and should be removed.
4282 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
4283 CmdArgs.push_back("-disable-llvm-optzns");
4284 } else {
4285 A->render(Args, CmdArgs);
4286 }
4287 }
4288
4289 // With -save-temps, we want to save the unoptimized bitcode output from the
4290 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
4291 // by the frontend.
4292 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
4293 // has slightly different breakdown between stages.
4294 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
4295 // pristine IR generated by the frontend. Ideally, a new compile action should
4296 // be added so both IR can be captured.
4297 if (C.getDriver().isSaveTempsEnabled() &&
4298 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
4299 isa<CompileJobAction>(JA))
4300 CmdArgs.push_back("-disable-llvm-passes");
4301
4302 if (Output.getType() == types::TY_Dependencies) {
4303 // Handled with other dependency code.
4304 } else if (Output.isFilename()) {
4305 CmdArgs.push_back("-o");
4306 CmdArgs.push_back(Output.getFilename());
4307 } else {
4308 assert(Output.isNothing() && "Invalid output.");
4309 }
4310
4311 addDashXForInput(Args, Input, CmdArgs);
4312
4313 if (Input.isFilename())
4314 CmdArgs.push_back(Input.getFilename());
4315 else
4316 Input.getInputArg().renderAsInput(Args, CmdArgs);
4317
4318 Args.AddAllArgs(CmdArgs, options::OPT_undef);
4319
4320 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4321
4322 // Optionally embed the -cc1 level arguments into the debug info, for build
4323 // analysis.
4324 if (getToolChain().UseDwarfDebugFlags()) {
4325 ArgStringList OriginalArgs;
4326 for (const auto &Arg : Args)
4327 Arg->render(Args, OriginalArgs);
4328
4329 SmallString<256> Flags;
4330 Flags += Exec;
4331 for (const char *OriginalArg : OriginalArgs) {
4332 SmallString<128> EscapedArg;
4333 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4334 Flags += " ";
4335 Flags += EscapedArg;
4336 }
4337 CmdArgs.push_back("-dwarf-debug-flags");
4338 CmdArgs.push_back(Args.MakeArgString(Flags));
4339 }
4340
4341 // Add the split debug info name to the command lines here so we
4342 // can propagate it to the backend.
4343 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
4344 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4345 isa<BackendJobAction>(JA));
4346 const char *SplitDwarfOut;
4347 if (SplitDwarf) {
4348 CmdArgs.push_back("-split-dwarf-file");
4349 SplitDwarfOut = SplitDebugName(Args, Input);
4350 CmdArgs.push_back(SplitDwarfOut);
4351 }
4352
4353 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
4354 // Include them with -fcuda-include-gpubinary.
4355 if (IsCuda && Inputs.size() > 1)
4356 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
4357 CmdArgs.push_back("-fcuda-include-gpubinary");
4358 CmdArgs.push_back(I->getFilename());
4359 }
4360
4361 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
4362 // to specify the result of the compile phase on the host, so the meaningful
4363 // device declarations can be identified. Also, -fopenmp-is-device is passed
4364 // along to tell the frontend that it is generating code for a device, so that
4365 // only the relevant declarations are emitted.
4366 if (IsOpenMPDevice && Inputs.size() == 2) {
4367 CmdArgs.push_back("-fopenmp-is-device");
4368 CmdArgs.push_back("-fopenmp-host-ir-file-path");
4369 CmdArgs.push_back(Args.MakeArgString(Inputs.back().getFilename()));
4370 }
4371
4372 // For all the host OpenMP offloading compile jobs we need to pass the targets
4373 // information using -fopenmp-targets= option.
4374 if (isa<CompileJobAction>(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
4375 SmallString<128> TargetInfo("-fopenmp-targets=");
4376
4377 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
4378 assert(Tgts && Tgts->getNumValues() &&
4379 "OpenMP offloading has to have targets specified.");
4380 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
4381 if (i)
4382 TargetInfo += ',';
4383 // We need to get the string from the triple because it may be not exactly
4384 // the same as the one we get directly from the arguments.
4385 llvm::Triple T(Tgts->getValue(i));
4386 TargetInfo += T.getTriple();
4387 }
4388 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
4389 }
4390
4391 bool WholeProgramVTables =
4392 Args.hasFlag(options::OPT_fwhole_program_vtables,
4393 options::OPT_fno_whole_program_vtables, false);
4394 if (WholeProgramVTables) {
4395 if (!D.isUsingLTO())
4396 D.Diag(diag::err_drv_argument_only_allowed_with)
4397 << "-fwhole-program-vtables"
4398 << "-flto";
4399 CmdArgs.push_back("-fwhole-program-vtables");
4400 }
4401
4402 // Finally add the compile command to the compilation.
4403 if (Args.hasArg(options::OPT__SLASH_fallback) &&
4404 Output.getType() == types::TY_Object &&
4405 (InputType == types::TY_C || InputType == types::TY_CXX)) {
4406 auto CLCommand =
4407 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
4408 C.addCommand(llvm::make_unique<FallbackCommand>(
4409 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
4410 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
4411 isa<PrecompileJobAction>(JA)) {
4412 // In /fallback builds, run the main compilation even if the pch generation
4413 // fails, so that the main compilation's fallback to cl.exe runs.
4414 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
4415 CmdArgs, Inputs));
4416 } else {
4417 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
4418 }
4419
4420 // Handle the debug info splitting at object creation time if we're
4421 // creating an object.
4422 // TODO: Currently only works on linux with newer objcopy.
4423 if (SplitDwarf && Output.getType() == types::TY_Object)
4424 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
4425
4426 if (Arg *A = Args.getLastArg(options::OPT_pg))
4427 if (Args.hasArg(options::OPT_fomit_frame_pointer))
4428 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
4429 << A->getAsString(Args);
4430
4431 // Claim some arguments which clang supports automatically.
4432
4433 // -fpch-preprocess is used with gcc to add a special marker in the output to
4434 // include the PCH file. Clang's PTH solution is completely transparent, so we
4435 // do not need to deal with it at all.
4436 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
4437
4438 // Claim some arguments which clang doesn't support, but we don't
4439 // care to warn the user about.
4440 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
4441 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
4442
4443 // Disable warnings for clang -E -emit-llvm foo.c
4444 Args.ClaimAllArgs(options::OPT_emit_llvm);
4445}
4446
4447Clang::Clang(const ToolChain &TC)
4448 // CAUTION! The first constructor argument ("clang") is not arbitrary,
4449 // as it is for other tools. Some operations on a Tool actually test
4450 // whether that tool is Clang based on the Tool's Name as a string.
4451 : Tool("clang", "clang frontend", TC, RF_Full) {}
4452
4453Clang::~Clang() {}
4454
4455/// Add options related to the Objective-C runtime/ABI.
4456///
4457/// Returns true if the runtime is non-fragile.
4458ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
4459 ArgStringList &cmdArgs,
4460 RewriteKind rewriteKind) const {
4461 // Look for the controlling runtime option.
4462 Arg *runtimeArg =
4463 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
4464 options::OPT_fobjc_runtime_EQ);
4465
4466 // Just forward -fobjc-runtime= to the frontend. This supercedes
4467 // options about fragility.
4468 if (runtimeArg &&
4469 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
4470 ObjCRuntime runtime;
4471 StringRef value = runtimeArg->getValue();
4472 if (runtime.tryParse(value)) {
4473 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
4474 << value;
4475 }
4476
4477 runtimeArg->render(args, cmdArgs);
4478 return runtime;
4479 }
4480
4481 // Otherwise, we'll need the ABI "version". Version numbers are
4482 // slightly confusing for historical reasons:
4483 // 1 - Traditional "fragile" ABI
4484 // 2 - Non-fragile ABI, version 1
4485 // 3 - Non-fragile ABI, version 2
4486 unsigned objcABIVersion = 1;
4487 // If -fobjc-abi-version= is present, use that to set the version.
4488 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
4489 StringRef value = abiArg->getValue();
4490 if (value == "1")
4491 objcABIVersion = 1;
4492 else if (value == "2")
4493 objcABIVersion = 2;
4494 else if (value == "3")
4495 objcABIVersion = 3;
4496 else
4497 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
4498 } else {
4499 // Otherwise, determine if we are using the non-fragile ABI.
4500 bool nonFragileABIIsDefault =
4501 (rewriteKind == RK_NonFragile ||
4502 (rewriteKind == RK_None &&
4503 getToolChain().IsObjCNonFragileABIDefault()));
4504 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
4505 options::OPT_fno_objc_nonfragile_abi,
4506 nonFragileABIIsDefault)) {
4507// Determine the non-fragile ABI version to use.
4508#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
4509 unsigned nonFragileABIVersion = 1;
4510#else
4511 unsigned nonFragileABIVersion = 2;
4512#endif
4513
4514 if (Arg *abiArg =
4515 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
4516 StringRef value = abiArg->getValue();
4517 if (value == "1")
4518 nonFragileABIVersion = 1;
4519 else if (value == "2")
4520 nonFragileABIVersion = 2;
4521 else
4522 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
4523 << value;
4524 }
4525
4526 objcABIVersion = 1 + nonFragileABIVersion;
4527 } else {
4528 objcABIVersion = 1;
4529 }
4530 }
4531
4532 // We don't actually care about the ABI version other than whether
4533 // it's non-fragile.
4534 bool isNonFragile = objcABIVersion != 1;
4535
4536 // If we have no runtime argument, ask the toolchain for its default runtime.
4537 // However, the rewriter only really supports the Mac runtime, so assume that.
4538 ObjCRuntime runtime;
4539 if (!runtimeArg) {
4540 switch (rewriteKind) {
4541 case RK_None:
4542 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4543 break;
4544 case RK_Fragile:
4545 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
4546 break;
4547 case RK_NonFragile:
4548 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4549 break;
4550 }
4551
4552 // -fnext-runtime
4553 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
4554 // On Darwin, make this use the default behavior for the toolchain.
4555 if (getToolChain().getTriple().isOSDarwin()) {
4556 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
4557
4558 // Otherwise, build for a generic macosx port.
4559 } else {
4560 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
4561 }
4562
4563 // -fgnu-runtime
4564 } else {
4565 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
4566 // Legacy behaviour is to target the gnustep runtime if we are in
4567 // non-fragile mode or the GCC runtime in fragile mode.
4568 if (isNonFragile)
4569 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
4570 else
4571 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
4572 }
4573
4574 cmdArgs.push_back(
4575 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
4576 return runtime;
4577}
4578
4579static bool maybeConsumeDash(const std::string &EH, size_t &I) {
4580 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
4581 I += HaveDash;
4582 return !HaveDash;
4583}
4584
4585namespace {
4586struct EHFlags {
4587 bool Synch = false;
4588 bool Asynch = false;
4589 bool NoUnwindC = false;
4590};
4591} // end anonymous namespace
4592
4593/// /EH controls whether to run destructor cleanups when exceptions are
4594/// thrown. There are three modifiers:
4595/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
4596/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
4597/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
4598/// - c: Assume that extern "C" functions are implicitly nounwind.
4599/// The default is /EHs-c-, meaning cleanups are disabled.
4600static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
4601 EHFlags EH;
4602
4603 std::vector<std::string> EHArgs =
4604 Args.getAllArgValues(options::OPT__SLASH_EH);
4605 for (auto EHVal : EHArgs) {
4606 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
4607 switch (EHVal[I]) {
4608 case 'a':
4609 EH.Asynch = maybeConsumeDash(EHVal, I);
4610 if (EH.Asynch)
4611 EH.Synch = false;
4612 continue;
4613 case 'c':
4614 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
4615 continue;
4616 case 's':
4617 EH.Synch = maybeConsumeDash(EHVal, I);
4618 if (EH.Synch)
4619 EH.Asynch = false;
4620 continue;
4621 default:
4622 break;
4623 }
4624 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
4625 break;
4626 }
4627 }
4628 // The /GX, /GX- flags are only processed if there are not /EH flags.
4629 // The default is that /GX is not specified.
4630 if (EHArgs.empty() &&
4631 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
4632 /*default=*/false)) {
4633 EH.Synch = true;
4634 EH.NoUnwindC = true;
4635 }
4636
4637 return EH;
4638}
4639
4640void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
4641 ArgStringList &CmdArgs,
4642 codegenoptions::DebugInfoKind *DebugInfoKind,
4643 bool *EmitCodeView) const {
4644 unsigned RTOptionID = options::OPT__SLASH_MT;
4645
4646 if (Args.hasArg(options::OPT__SLASH_LDd))
4647 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4648 // but defining _DEBUG is sticky.
4649 RTOptionID = options::OPT__SLASH_MTd;
4650
4651 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4652 RTOptionID = A->getOption().getID();
4653
4654 StringRef FlagForCRT;
4655 switch (RTOptionID) {
4656 case options::OPT__SLASH_MD:
4657 if (Args.hasArg(options::OPT__SLASH_LDd))
4658 CmdArgs.push_back("-D_DEBUG");
4659 CmdArgs.push_back("-D_MT");
4660 CmdArgs.push_back("-D_DLL");
4661 FlagForCRT = "--dependent-lib=msvcrt";
4662 break;
4663 case options::OPT__SLASH_MDd:
4664 CmdArgs.push_back("-D_DEBUG");
4665 CmdArgs.push_back("-D_MT");
4666 CmdArgs.push_back("-D_DLL");
4667 FlagForCRT = "--dependent-lib=msvcrtd";
4668 break;
4669 case options::OPT__SLASH_MT:
4670 if (Args.hasArg(options::OPT__SLASH_LDd))
4671 CmdArgs.push_back("-D_DEBUG");
4672 CmdArgs.push_back("-D_MT");
4673 CmdArgs.push_back("-flto-visibility-public-std");
4674 FlagForCRT = "--dependent-lib=libcmt";
4675 break;
4676 case options::OPT__SLASH_MTd:
4677 CmdArgs.push_back("-D_DEBUG");
4678 CmdArgs.push_back("-D_MT");
4679 CmdArgs.push_back("-flto-visibility-public-std");
4680 FlagForCRT = "--dependent-lib=libcmtd";
4681 break;
4682 default:
4683 llvm_unreachable("Unexpected option ID.");
4684 }
4685
4686 if (Args.hasArg(options::OPT__SLASH_Zl)) {
4687 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4688 } else {
4689 CmdArgs.push_back(FlagForCRT.data());
4690
4691 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4692 // users want. The /Za flag to cl.exe turns this off, but it's not
4693 // implemented in clang.
4694 CmdArgs.push_back("--dependent-lib=oldnames");
4695 }
4696
4697 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
4698 // would produce interleaved output, so ignore /showIncludes in such cases.
4699 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
4700 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
4701 A->render(Args, CmdArgs);
4702
4703 // This controls whether or not we emit RTTI data for polymorphic types.
4704 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
4705 /*default=*/false))
4706 CmdArgs.push_back("-fno-rtti-data");
4707
4708 // This controls whether or not we emit stack-protector instrumentation.
4709 // In MSVC, Buffer Security Check (/GS) is on by default.
4710 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
4711 /*default=*/true)) {
4712 CmdArgs.push_back("-stack-protector");
4713 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
4714 }
4715
4716 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
4717 if (Arg *DebugInfoArg =
4718 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
4719 options::OPT_gline_tables_only)) {
4720 *EmitCodeView = true;
4721 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
4722 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
4723 else
4724 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4725 CmdArgs.push_back("-gcodeview");
4726 } else {
4727 *EmitCodeView = false;
4728 }
4729
4730 const Driver &D = getToolChain().getDriver();
4731 EHFlags EH = parseClangCLEHFlags(D, Args);
4732 if (EH.Synch || EH.Asynch) {
4733 if (types::isCXX(InputType))
4734 CmdArgs.push_back("-fcxx-exceptions");
4735 CmdArgs.push_back("-fexceptions");
4736 }
4737 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
4738 CmdArgs.push_back("-fexternc-nounwind");
4739
4740 // /EP should expand to -E -P.
4741 if (Args.hasArg(options::OPT__SLASH_EP)) {
4742 CmdArgs.push_back("-E");
4743 CmdArgs.push_back("-P");
4744 }
4745
4746 unsigned VolatileOptionID;
4747 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
4748 getToolChain().getArch() == llvm::Triple::x86)
4749 VolatileOptionID = options::OPT__SLASH_volatile_ms;
4750 else
4751 VolatileOptionID = options::OPT__SLASH_volatile_iso;
4752
4753 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
4754 VolatileOptionID = A->getOption().getID();
4755
4756 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
4757 CmdArgs.push_back("-fms-volatile");
4758
4759 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
4760 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
4761 if (MostGeneralArg && BestCaseArg)
4762 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4763 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
4764
4765 if (MostGeneralArg) {
4766 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
4767 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
4768 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
4769
4770 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
4771 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
4772 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
4773 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
4774 << FirstConflict->getAsString(Args)
4775 << SecondConflict->getAsString(Args);
4776
4777 if (SingleArg)
4778 CmdArgs.push_back("-fms-memptr-rep=single");
4779 else if (MultipleArg)
4780 CmdArgs.push_back("-fms-memptr-rep=multiple");
4781 else
4782 CmdArgs.push_back("-fms-memptr-rep=virtual");
4783 }
4784
4785 if (Args.getLastArg(options::OPT__SLASH_Gd))
4786 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
4787 else if (Args.getLastArg(options::OPT__SLASH_Gr))
4788 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
4789 else if (Args.getLastArg(options::OPT__SLASH_Gz))
4790 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4791 else if (Args.getLastArg(options::OPT__SLASH_Gv))
4792 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
4793
4794 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
4795 A->render(Args, CmdArgs);
4796
4797 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
4798 CmdArgs.push_back("-fdiagnostics-format");
4799 if (Args.hasArg(options::OPT__SLASH_fallback))
4800 CmdArgs.push_back("msvc-fallback");
4801 else
4802 CmdArgs.push_back("msvc");
4803 }
4804}
4805
4806visualstudio::Compiler *Clang::getCLFallback() const {
4807 if (!CLFallback)
4808 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
4809 return CLFallback.get();
4810}
4811
4812
4813const char *Clang::getBaseInputName(const ArgList &Args,
4814 const InputInfo &Input) {
4815 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
4816}
4817
4818const char *Clang::getBaseInputStem(const ArgList &Args,
4819 const InputInfoList &Inputs) {
4820 const char *Str = getBaseInputName(Args, Inputs[0]);
4821
4822 if (const char *End = strrchr(Str, '.'))
4823 return Args.MakeArgString(std::string(Str, End));
4824
4825 return Str;
4826}
4827
4828const char *Clang::getDependencyFileName(const ArgList &Args,
4829 const InputInfoList &Inputs) {
4830 // FIXME: Think about this more.
4831 std::string Res;
4832
4833 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
4834 std::string Str(OutputOpt->getValue());
4835 Res = Str.substr(0, Str.rfind('.'));
4836 } else {
4837 Res = getBaseInputStem(Args, Inputs);
4838 }
4839 return Args.MakeArgString(Res + ".d");
4840}
4841
4842// Begin ClangAs
4843
4844void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
4845 ArgStringList &CmdArgs) const {
4846 StringRef CPUName;
4847 StringRef ABIName;
4848 const llvm::Triple &Triple = getToolChain().getTriple();
4849 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
4850
4851 CmdArgs.push_back("-target-abi");
4852 CmdArgs.push_back(ABIName.data());
4853}
4854
4855void ClangAs::AddX86TargetArgs(const ArgList &Args,
4856 ArgStringList &CmdArgs) const {
4857 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
4858 StringRef Value = A->getValue();
4859 if (Value == "intel" || Value == "att") {
4860 CmdArgs.push_back("-mllvm");
4861 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
4862 } else {
4863 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
4864 << A->getOption().getName() << Value;
4865 }
4866 }
4867}
4868
4869void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
4870 const InputInfo &Output, const InputInfoList &Inputs,
4871 const ArgList &Args,
4872 const char *LinkingOutput) const {
4873 ArgStringList CmdArgs;
4874
4875 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
4876 const InputInfo &Input = Inputs[0];
4877
4878 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
4879 const std::string &TripleStr = Triple.getTriple();
4880
4881 // Don't warn about "clang -w -c foo.s"
4882 Args.ClaimAllArgs(options::OPT_w);
4883 // and "clang -emit-llvm -c foo.s"
4884 Args.ClaimAllArgs(options::OPT_emit_llvm);
4885
4886 claimNoWarnArgs(Args);
4887
4888 // Invoke ourselves in -cc1as mode.
4889 //
4890 // FIXME: Implement custom jobs for internal actions.
4891 CmdArgs.push_back("-cc1as");
4892
4893 // Add the "effective" target triple.
4894 CmdArgs.push_back("-triple");
4895 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4896
4897 // Set the output mode, we currently only expect to be used as a real
4898 // assembler.
4899 CmdArgs.push_back("-filetype");
4900 CmdArgs.push_back("obj");
4901
4902 // Set the main file name, so that debug info works even with
4903 // -save-temps or preprocessed assembly.
4904 CmdArgs.push_back("-main-file-name");
4905 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
4906
4907 // Add the target cpu
4908 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
4909 if (!CPU.empty()) {
4910 CmdArgs.push_back("-target-cpu");
4911 CmdArgs.push_back(Args.MakeArgString(CPU));
4912 }
4913
4914 // Add the target features
4915 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
4916
4917 // Ignore explicit -force_cpusubtype_ALL option.
4918 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4919
4920 // Pass along any -I options so we get proper .include search paths.
4921 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
4922
4923 // Determine the original source input.
4924 const Action *SourceAction = &JA;
4925 while (SourceAction->getKind() != Action::InputClass) {
4926 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
4927 SourceAction = SourceAction->getInputs()[0];
4928 }
4929
4930 // Forward -g and handle debug info related flags, assuming we are dealing
4931 // with an actual assembly file.
4932 bool WantDebug = false;
4933 unsigned DwarfVersion = 0;
4934 Args.ClaimAllArgs(options::OPT_g_Group);
4935 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4936 WantDebug = !A->getOption().matches(options::OPT_g0) &&
4937 !A->getOption().matches(options::OPT_ggdb0);
4938 if (WantDebug)
4939 DwarfVersion = DwarfVersionNum(A->getSpelling());
4940 }
4941 if (DwarfVersion == 0)
4942 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4943
4944 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4945
4946 if (SourceAction->getType() == types::TY_Asm ||
4947 SourceAction->getType() == types::TY_PP_Asm) {
4948 // You might think that it would be ok to set DebugInfoKind outside of
4949 // the guard for source type, however there is a test which asserts
4950 // that some assembler invocation receives no -debug-info-kind,
4951 // and it's not clear whether that test is just overly restrictive.
4952 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
4953 : codegenoptions::NoDebugInfo);
4954 // Add the -fdebug-compilation-dir flag if needed.
4955 addDebugCompDirArg(Args, CmdArgs);
4956
4957 // Set the AT_producer to the clang version when using the integrated
4958 // assembler on assembly source files.
4959 CmdArgs.push_back("-dwarf-debug-producer");
4960 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
4961
4962 // And pass along -I options
4963 Args.AddAllArgs(CmdArgs, options::OPT_I);
4964 }
4965 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4966 llvm::DebuggerKind::Default);
4967
4968 // Handle -fPIC et al -- the relocation-model affects the assembler
4969 // for some targets.
4970 llvm::Reloc::Model RelocationModel;
4971 unsigned PICLevel;
4972 bool IsPIE;
4973 std::tie(RelocationModel, PICLevel, IsPIE) =
4974 ParsePICArgs(getToolChain(), Args);
4975
4976 const char *RMName = RelocationModelName(RelocationModel);
4977 if (RMName) {
4978 CmdArgs.push_back("-mrelocation-model");
4979 CmdArgs.push_back(RMName);
4980 }
4981
4982 // Optionally embed the -cc1as level arguments into the debug info, for build
4983 // analysis.
4984 if (getToolChain().UseDwarfDebugFlags()) {
4985 ArgStringList OriginalArgs;
4986 for (const auto &Arg : Args)
4987 Arg->render(Args, OriginalArgs);
4988
4989 SmallString<256> Flags;
4990 const char *Exec = getToolChain().getDriver().getClangProgramPath();
4991 Flags += Exec;
4992 for (const char *OriginalArg : OriginalArgs) {
4993 SmallString<128> EscapedArg;
4994 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
4995 Flags += " ";
4996 Flags += EscapedArg;
4997 }
4998 CmdArgs.push_back("-dwarf-debug-flags");
4999 CmdArgs.push_back(Args.MakeArgString(Flags));
5000 }
5001
5002 // FIXME: Add -static support, once we have it.
5003
5004 // Add target specific flags.
5005 switch (getToolChain().getArch()) {
5006 default:
5007 break;
5008
5009 case llvm::Triple::mips:
5010 case llvm::Triple::mipsel:
5011 case llvm::Triple::mips64:
5012 case llvm::Triple::mips64el:
5013 AddMIPSTargetArgs(Args, CmdArgs);
5014 break;
5015
5016 case llvm::Triple::x86:
5017 case llvm::Triple::x86_64:
5018 AddX86TargetArgs(Args, CmdArgs);
5019 break;
5020 }
5021
5022 // Consume all the warning flags. Usually this would be handled more
5023 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
5024 // doesn't handle that so rather than warning about unused flags that are
5025 // actually used, we'll lie by omission instead.
5026 // FIXME: Stop lying and consume only the appropriate driver flags
5027 Args.ClaimAllArgs(options::OPT_W_Group);
5028
5029 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
5030 getToolChain().getDriver());
5031
5032 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
5033
5034 assert(Output.isFilename() && "Unexpected lipo output.");
5035 CmdArgs.push_back("-o");
5036 CmdArgs.push_back(Output.getFilename());
5037
5038 assert(Input.isFilename() && "Invalid input.");
5039 CmdArgs.push_back(Input.getFilename());
5040
5041 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5042 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5043
5044 // Handle the debug info splitting at object creation time if we're
5045 // creating an object.
5046 // TODO: Currently only works on linux with newer objcopy.
5047 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
5048 getToolChain().getTriple().isOSLinux())
5049 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
5050 SplitDebugName(Args, Input));
5051}
5052
5053// Begin OffloadBundler
5054
5055void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
5056 const InputInfo &Output,
5057 const InputInfoList &Inputs,
5058 const llvm::opt::ArgList &TCArgs,
5059 const char *LinkingOutput) const {
5060 // The version with only one output is expected to refer to a bundling job.
5061 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
5062
5063 // The bundling command looks like this:
5064 // clang-offload-bundler -type=bc
5065 // -targets=host-triple,openmp-triple1,openmp-triple2
5066 // -outputs=input_file
5067 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5068
5069 ArgStringList CmdArgs;
5070
5071 // Get the type.
5072 CmdArgs.push_back(TCArgs.MakeArgString(
5073 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
5074
5075 assert(JA.getInputs().size() == Inputs.size() &&
5076 "Not have inputs for all dependence actions??");
5077
5078 // Get the targets.
5079 SmallString<128> Triples;
5080 Triples += "-targets=";
5081 for (unsigned I = 0; I < Inputs.size(); ++I) {
5082 if (I)
5083 Triples += ',';
5084
5085 Action::OffloadKind CurKind = Action::OFK_Host;
5086 const ToolChain *CurTC = &getToolChain();
5087 const Action *CurDep = JA.getInputs()[I];
5088
5089 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
5090 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
5091 CurKind = A->getOffloadingDeviceKind();
5092 CurTC = TC;
5093 });
5094 }
5095 Triples += Action::GetOffloadKindName(CurKind);
5096 Triples += '-';
5097 Triples += CurTC->getTriple().normalize();
5098 }
5099 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5100
5101 // Get bundled file command.
5102 CmdArgs.push_back(
5103 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
5104
5105 // Get unbundled files command.
5106 SmallString<128> UB;
5107 UB += "-inputs=";
5108 for (unsigned I = 0; I < Inputs.size(); ++I) {
5109 if (I)
5110 UB += ',';
5111 UB += Inputs[I].getFilename();
5112 }
5113 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5114
5115 // All the inputs are encoded as commands.
5116 C.addCommand(llvm::make_unique<Command>(
5117 JA, *this,
5118 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5119 CmdArgs, None));
5120}
5121
5122void OffloadBundler::ConstructJobMultipleOutputs(
5123 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
5124 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
5125 const char *LinkingOutput) const {
5126 // The version with multiple outputs is expected to refer to a unbundling job.
5127 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
5128
5129 // The unbundling command looks like this:
5130 // clang-offload-bundler -type=bc
5131 // -targets=host-triple,openmp-triple1,openmp-triple2
5132 // -inputs=input_file
5133 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
5134 // -unbundle
5135
5136 ArgStringList CmdArgs;
5137
5138 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
5139 InputInfo Input = Inputs.front();
5140
5141 // Get the type.
5142 CmdArgs.push_back(TCArgs.MakeArgString(
5143 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
5144
5145 // Get the targets.
5146 SmallString<128> Triples;
5147 Triples += "-targets=";
5148 auto DepInfo = UA.getDependentActionsInfo();
5149 for (unsigned I = 0; I < DepInfo.size(); ++I) {
5150 if (I)
5151 Triples += ',';
5152
5153 auto &Dep = DepInfo[I];
5154 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
5155 Triples += '-';
5156 Triples += Dep.DependentToolChain->getTriple().normalize();
5157 }
5158
5159 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
5160
5161 // Get bundled file command.
5162 CmdArgs.push_back(
5163 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
5164
5165 // Get unbundled files command.
5166 SmallString<128> UB;
5167 UB += "-outputs=";
5168 for (unsigned I = 0; I < Outputs.size(); ++I) {
5169 if (I)
5170 UB += ',';
5171 UB += Outputs[I].getFilename();
5172 }
5173 CmdArgs.push_back(TCArgs.MakeArgString(UB));
5174 CmdArgs.push_back("-unbundle");
5175
5176 // All the inputs are encoded as commands.
5177 C.addCommand(llvm::make_unique<Command>(
5178 JA, *this,
5179 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
5180 CmdArgs, None));
5181}