blob: 3bc7412911b61e74c1b2ba60ee71ee7cbe85fa9a [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
David L. Jonesf561aba2017-03-08 01:02:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
David L. Jonesf561aba2017-03-08 01:02:16 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000014#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000018#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000019#include "CommonArgs.h"
20#include "Hexagon.h"
Anton Korobeynikov93165d62019-01-15 19:44:05 +000021#include "MSP430.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000022#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
Michal Gornydae01c32018-12-23 15:07:26 +000028#include "clang/Driver/Distro.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000029#include "clang/Driver/DriverDiagnostic.h"
30#include "clang/Driver/Options.h"
31#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000032#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000034#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000035#include "llvm/Option/ArgList.h"
36#include "llvm/Support/CodeGen.h"
37#include "llvm/Support/Compression.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000041#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000042#include "llvm/Support/YAMLParser.h"
43
44#ifdef LLVM_ON_UNIX
45#include <unistd.h> // For getuid().
46#endif
47
48using namespace clang::driver;
49using namespace clang::driver::tools;
50using namespace clang;
51using namespace llvm::opt;
52
53static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
54 if (Arg *A =
55 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
56 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
57 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
58 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
59 << A->getBaseArg().getAsString(Args)
60 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
61 }
62 }
63}
64
65static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
66 // In gcc, only ARM checks this, but it seems reasonable to check universally.
67 if (Args.hasArg(options::OPT_static))
68 if (const Arg *A =
69 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
70 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
71 << "-static";
72}
73
74// Add backslashes to escape spaces and other backslashes.
75// This is used for the space-separated argument list specified with
76// the -dwarf-debug-flags option.
77static void EscapeSpacesAndBackslashes(const char *Arg,
78 SmallVectorImpl<char> &Res) {
79 for (; *Arg; ++Arg) {
80 switch (*Arg) {
81 default:
82 break;
83 case ' ':
84 case '\\':
85 Res.push_back('\\');
86 break;
87 }
88 Res.push_back(*Arg);
89 }
90}
91
92// Quote target names for inclusion in GNU Make dependency files.
93// Only the characters '$', '#', ' ', '\t' are quoted.
94static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
95 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
96 switch (Target[i]) {
97 case ' ':
98 case '\t':
99 // Escape the preceding backslashes
100 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
101 Res.push_back('\\');
102
103 // Escape the space/tab
104 Res.push_back('\\');
105 break;
106 case '$':
107 Res.push_back('$');
108 break;
109 case '#':
110 Res.push_back('\\');
111 break;
112 default:
113 break;
114 }
115
116 Res.push_back(Target[i]);
117 }
118}
119
120/// Apply \a Work on the current tool chain \a RegularToolChain and any other
121/// offloading tool chain that is associated with the current action \a JA.
122static void
123forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
124 const ToolChain &RegularToolChain,
125 llvm::function_ref<void(const ToolChain &)> Work) {
126 // Apply Work on the current/regular tool chain.
127 Work(RegularToolChain);
128
129 // Apply Work on all the offloading tool chains associated with the current
130 // action.
131 if (JA.isHostOffloading(Action::OFK_Cuda))
132 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
133 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
134 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000135 else if (JA.isHostOffloading(Action::OFK_HIP))
136 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
137 else if (JA.isDeviceOffloading(Action::OFK_HIP))
138 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000139
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000140 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
141 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
142 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
143 Work(*II->second);
144 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
145 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
146
David L. Jonesf561aba2017-03-08 01:02:16 +0000147 //
148 // TODO: Add support for other offloading programming models here.
149 //
150}
151
152/// This is a helper function for validating the optional refinement step
153/// parameter in reciprocal argument strings. Return false if there is an error
154/// parsing the refinement step. Otherwise, return true and set the Position
155/// of the refinement step in the input string.
156static bool getRefinementStep(StringRef In, const Driver &D,
157 const Arg &A, size_t &Position) {
158 const char RefinementStepToken = ':';
159 Position = In.find(RefinementStepToken);
160 if (Position != StringRef::npos) {
161 StringRef Option = A.getOption().getName();
162 StringRef RefStep = In.substr(Position + 1);
163 // Allow exactly one numeric character for the additional refinement
164 // step parameter. This is reasonable for all currently-supported
165 // operations and architectures because we would expect that a larger value
166 // of refinement steps would cause the estimate "optimization" to
167 // under-perform the native operation. Also, if the estimate does not
168 // converge quickly, it probably will not ever converge, so further
169 // refinement steps will not produce a better answer.
170 if (RefStep.size() != 1) {
171 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
172 return false;
173 }
174 char RefStepChar = RefStep[0];
175 if (RefStepChar < '0' || RefStepChar > '9') {
176 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
177 return false;
178 }
179 }
180 return true;
181}
182
183/// The -mrecip flag requires processing of many optional parameters.
184static void ParseMRecip(const Driver &D, const ArgList &Args,
185 ArgStringList &OutStrings) {
186 StringRef DisabledPrefixIn = "!";
187 StringRef DisabledPrefixOut = "!";
188 StringRef EnabledPrefixOut = "";
189 StringRef Out = "-mrecip=";
190
191 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
192 if (!A)
193 return;
194
195 unsigned NumOptions = A->getNumValues();
196 if (NumOptions == 0) {
197 // No option is the same as "all".
198 OutStrings.push_back(Args.MakeArgString(Out + "all"));
199 return;
200 }
201
202 // Pass through "all", "none", or "default" with an optional refinement step.
203 if (NumOptions == 1) {
204 StringRef Val = A->getValue(0);
205 size_t RefStepLoc;
206 if (!getRefinementStep(Val, D, *A, RefStepLoc))
207 return;
208 StringRef ValBase = Val.slice(0, RefStepLoc);
209 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
210 OutStrings.push_back(Args.MakeArgString(Out + Val));
211 return;
212 }
213 }
214
215 // Each reciprocal type may be enabled or disabled individually.
216 // Check each input value for validity, concatenate them all back together,
217 // and pass through.
218
219 llvm::StringMap<bool> OptionStrings;
220 OptionStrings.insert(std::make_pair("divd", false));
221 OptionStrings.insert(std::make_pair("divf", false));
222 OptionStrings.insert(std::make_pair("vec-divd", false));
223 OptionStrings.insert(std::make_pair("vec-divf", false));
224 OptionStrings.insert(std::make_pair("sqrtd", false));
225 OptionStrings.insert(std::make_pair("sqrtf", false));
226 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
228
229 for (unsigned i = 0; i != NumOptions; ++i) {
230 StringRef Val = A->getValue(i);
231
232 bool IsDisabled = Val.startswith(DisabledPrefixIn);
233 // Ignore the disablement token for string matching.
234 if (IsDisabled)
235 Val = Val.substr(1);
236
237 size_t RefStep;
238 if (!getRefinementStep(Val, D, *A, RefStep))
239 return;
240
241 StringRef ValBase = Val.slice(0, RefStep);
242 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
243 if (OptionIter == OptionStrings.end()) {
244 // Try again specifying float suffix.
245 OptionIter = OptionStrings.find(ValBase.str() + 'f');
246 if (OptionIter == OptionStrings.end()) {
247 // The input name did not match any known option string.
248 D.Diag(diag::err_drv_unknown_argument) << Val;
249 return;
250 }
251 // The option was specified without a float or double suffix.
252 // Make sure that the double entry was not already specified.
253 // The float entry will be checked below.
254 if (OptionStrings[ValBase.str() + 'd']) {
255 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256 return;
257 }
258 }
259
260 if (OptionIter->second == true) {
261 // Duplicate option specified.
262 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
263 return;
264 }
265
266 // Mark the matched option as found. Do not allow duplicate specifiers.
267 OptionIter->second = true;
268
269 // If the precision was not specified, also mark the double entry as found.
270 if (ValBase.back() != 'f' && ValBase.back() != 'd')
271 OptionStrings[ValBase.str() + 'd'] = true;
272
273 // Build the output string.
274 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
275 Out = Args.MakeArgString(Out + Prefix + Val);
276 if (i != NumOptions - 1)
277 Out = Args.MakeArgString(Out + ",");
278 }
279
280 OutStrings.push_back(Args.MakeArgString(Out));
281}
282
Craig Topper9a724aa2017-12-11 21:09:19 +0000283/// The -mprefer-vector-width option accepts either a positive integer
284/// or the string "none".
285static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
286 ArgStringList &CmdArgs) {
287 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
288 if (!A)
289 return;
290
291 StringRef Value = A->getValue();
292 if (Value == "none") {
293 CmdArgs.push_back("-mprefer-vector-width=none");
294 } else {
295 unsigned Width;
296 if (Value.getAsInteger(10, Width)) {
297 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
298 return;
299 }
300 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301 }
302}
303
David L. Jonesf561aba2017-03-08 01:02:16 +0000304static void getWebAssemblyTargetFeatures(const ArgList &Args,
305 std::vector<StringRef> &Features) {
306 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
307}
308
David L. Jonesf561aba2017-03-08 01:02:16 +0000309static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
310 const ArgList &Args, ArgStringList &CmdArgs,
311 bool ForAS) {
312 const Driver &D = TC.getDriver();
313 std::vector<StringRef> Features;
314 switch (Triple.getArch()) {
315 default:
316 break;
317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el:
321 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
322 break;
323
324 case llvm::Triple::arm:
325 case llvm::Triple::armeb:
326 case llvm::Triple::thumb:
327 case llvm::Triple::thumbeb:
328 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
329 break;
330
331 case llvm::Triple::ppc:
332 case llvm::Triple::ppc64:
333 case llvm::Triple::ppc64le:
334 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
335 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000336 case llvm::Triple::riscv32:
337 case llvm::Triple::riscv64:
338 riscv::getRISCVTargetFeatures(D, Args, Features);
339 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000340 case llvm::Triple::systemz:
341 systemz::getSystemZTargetFeatures(Args, Features);
342 break;
343 case llvm::Triple::aarch64:
344 case llvm::Triple::aarch64_be:
Alex Lorenz9b20a992018-12-17 19:30:46 +0000345 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000346 break;
347 case llvm::Triple::x86:
348 case llvm::Triple::x86_64:
349 x86::getX86TargetFeatures(D, Triple, Args, Features);
350 break;
351 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000352 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000353 break;
354 case llvm::Triple::wasm32:
355 case llvm::Triple::wasm64:
356 getWebAssemblyTargetFeatures(Args, Features);
357 break;
358 case llvm::Triple::sparc:
359 case llvm::Triple::sparcel:
360 case llvm::Triple::sparcv9:
361 sparc::getSparcTargetFeatures(D, Args, Features);
362 break;
363 case llvm::Triple::r600:
364 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000365 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000366 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +0000367 case llvm::Triple::msp430:
368 msp430::getMSP430TargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000369 }
370
371 // Find the last of each feature.
372 llvm::StringMap<unsigned> LastOpt;
373 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
374 StringRef Name = Features[I];
375 assert(Name[0] == '-' || Name[0] == '+');
376 LastOpt[Name.drop_front(1)] = I;
377 }
378
379 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
380 // If this feature was overridden, ignore it.
381 StringRef Name = Features[I];
382 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
383 assert(LastI != LastOpt.end());
384 unsigned Last = LastI->second;
385 if (Last != I)
386 continue;
387
388 CmdArgs.push_back("-target-feature");
389 CmdArgs.push_back(Name.data());
390 }
391}
392
393static bool
394shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
395 const llvm::Triple &Triple) {
396 // We use the zero-cost exception tables for Objective-C if the non-fragile
397 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
398 // later.
399 if (runtime.isNonFragile())
400 return true;
401
402 if (!Triple.isMacOSX())
403 return false;
404
405 return (!Triple.isMacOSXVersionLT(10, 5) &&
406 (Triple.getArch() == llvm::Triple::x86_64 ||
407 Triple.getArch() == llvm::Triple::arm));
408}
409
410/// Adds exception related arguments to the driver command arguments. There's a
411/// master flag, -fexceptions and also language specific flags to enable/disable
412/// C++ and Objective-C exceptions. This makes it possible to for example
413/// disable C++ exceptions but enable Objective-C exceptions.
414static void addExceptionArgs(const ArgList &Args, types::ID InputType,
415 const ToolChain &TC, bool KernelOrKext,
416 const ObjCRuntime &objcRuntime,
417 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000418 const llvm::Triple &Triple = TC.getTriple();
419
420 if (KernelOrKext) {
421 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
422 // arguments now to avoid warnings about unused arguments.
423 Args.ClaimAllArgs(options::OPT_fexceptions);
424 Args.ClaimAllArgs(options::OPT_fno_exceptions);
425 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
426 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
428 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
429 return;
430 }
431
432 // See if the user explicitly enabled exceptions.
433 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
434 false);
435
436 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
437 // is not necessarily sensible, but follows GCC.
438 if (types::isObjC(InputType) &&
439 Args.hasFlag(options::OPT_fobjc_exceptions,
440 options::OPT_fno_objc_exceptions, true)) {
441 CmdArgs.push_back("-fobjc-exceptions");
442
443 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
444 }
445
446 if (types::isCXX(InputType)) {
447 // Disable C++ EH by default on XCore and PS4.
448 bool CXXExceptionsEnabled =
449 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
450 Arg *ExceptionArg = Args.getLastArg(
451 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
452 options::OPT_fexceptions, options::OPT_fno_exceptions);
453 if (ExceptionArg)
454 CXXExceptionsEnabled =
455 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
456 ExceptionArg->getOption().matches(options::OPT_fexceptions);
457
458 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000459 CmdArgs.push_back("-fcxx-exceptions");
460
461 EH = true;
462 }
463 }
464
465 if (EH)
466 CmdArgs.push_back("-fexceptions");
467}
468
469static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
470 bool Default = true;
471 if (TC.getTriple().isOSDarwin()) {
472 // The native darwin assembler doesn't support the linker_option directives,
473 // so we disable them if we think the .s file will be passed to it.
474 Default = TC.useIntegratedAs();
475 }
476 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
477 Default);
478}
479
480static bool ShouldDisableDwarfDirectory(const ArgList &Args,
481 const ToolChain &TC) {
482 bool UseDwarfDirectory =
483 Args.hasFlag(options::OPT_fdwarf_directory_asm,
484 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
485 return !UseDwarfDirectory;
486}
487
488// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
489// to the corresponding DebugInfoKind.
490static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
491 assert(A.getOption().matches(options::OPT_gN_Group) &&
492 "Not a -g option that specifies a debug-info level");
493 if (A.getOption().matches(options::OPT_g0) ||
494 A.getOption().matches(options::OPT_ggdb0))
495 return codegenoptions::NoDebugInfo;
496 if (A.getOption().matches(options::OPT_gline_tables_only) ||
497 A.getOption().matches(options::OPT_ggdb1))
498 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000499 if (A.getOption().matches(options::OPT_gline_directives_only))
500 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000501 return codegenoptions::LimitedDebugInfo;
502}
503
504static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
505 switch (Triple.getArch()){
506 default:
507 return false;
508 case llvm::Triple::arm:
509 case llvm::Triple::thumb:
510 // ARM Darwin targets require a frame pointer to be always present to aid
511 // offline debugging via backtraces.
512 return Triple.isOSDarwin();
513 }
514}
515
516static bool useFramePointerForTargetByDefault(const ArgList &Args,
517 const llvm::Triple &Triple) {
518 switch (Triple.getArch()) {
519 case llvm::Triple::xcore:
520 case llvm::Triple::wasm32:
521 case llvm::Triple::wasm64:
Anton Korobeynikovf1f897c2019-02-05 20:15:03 +0000522 case llvm::Triple::msp430:
David L. Jonesf561aba2017-03-08 01:02:16 +0000523 // XCore never wants frame pointers, regardless of OS.
524 // WebAssembly never wants frame pointers.
525 return false;
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000526 case llvm::Triple::riscv32:
527 case llvm::Triple::riscv64:
528 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000529 default:
530 break;
531 }
532
Michal Gorny5a409d02018-12-20 13:09:30 +0000533 if (Triple.isOSNetBSD()) {
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000534 return !areOptimizationsEnabled(Args);
535 }
536
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000537 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
538 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000539 switch (Triple.getArch()) {
540 // Don't use a frame pointer on linux if optimizing for certain targets.
541 case llvm::Triple::mips64:
542 case llvm::Triple::mips64el:
543 case llvm::Triple::mips:
544 case llvm::Triple::mipsel:
545 case llvm::Triple::ppc:
546 case llvm::Triple::ppc64:
547 case llvm::Triple::ppc64le:
548 case llvm::Triple::systemz:
549 case llvm::Triple::x86:
550 case llvm::Triple::x86_64:
551 return !areOptimizationsEnabled(Args);
552 default:
553 return true;
554 }
555 }
556
557 if (Triple.isOSWindows()) {
558 switch (Triple.getArch()) {
559 case llvm::Triple::x86:
560 return !areOptimizationsEnabled(Args);
561 case llvm::Triple::x86_64:
562 return Triple.isOSBinFormatMachO();
563 case llvm::Triple::arm:
564 case llvm::Triple::thumb:
565 // Windows on ARM builds with FPO disabled to aid fast stack walking
566 return true;
567 default:
568 // All other supported Windows ISAs use xdata unwind information, so frame
569 // pointers are not generally useful.
570 return false;
571 }
572 }
573
574 return true;
575}
576
577static bool shouldUseFramePointer(const ArgList &Args,
578 const llvm::Triple &Triple) {
579 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
580 options::OPT_fomit_frame_pointer))
581 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
582 mustUseNonLeafFramePointerForTarget(Triple);
583
584 if (Args.hasArg(options::OPT_pg))
585 return true;
586
587 return useFramePointerForTargetByDefault(Args, Triple);
588}
589
590static bool shouldUseLeafFramePointer(const ArgList &Args,
591 const llvm::Triple &Triple) {
592 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
593 options::OPT_momit_leaf_frame_pointer))
594 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
595
596 if (Args.hasArg(options::OPT_pg))
597 return true;
598
599 if (Triple.isPS4CPU())
600 return false;
601
602 return useFramePointerForTargetByDefault(Args, Triple);
603}
604
605/// Add a CC1 option to specify the debug compilation directory.
606static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
607 SmallString<128> cwd;
608 if (!llvm::sys::fs::current_path(cwd)) {
609 CmdArgs.push_back("-fdebug-compilation-dir");
610 CmdArgs.push_back(Args.MakeArgString(cwd));
611 }
612}
613
Paul Robinson9b292b42018-07-10 15:15:24 +0000614/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
615static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
616 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
617 StringRef Map = A->getValue();
618 if (Map.find('=') == StringRef::npos)
619 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
620 else
621 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
622 A->claim();
623 }
624}
625
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000626/// Vectorize at all optimization levels greater than 1 except for -Oz.
David L. Jonesf561aba2017-03-08 01:02:16 +0000627/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
628static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
629 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
630 if (A->getOption().matches(options::OPT_O4) ||
631 A->getOption().matches(options::OPT_Ofast))
632 return true;
633
634 if (A->getOption().matches(options::OPT_O0))
635 return false;
636
637 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
638
639 // Vectorize -Os.
640 StringRef S(A->getValue());
641 if (S == "s")
642 return true;
643
644 // Don't vectorize -Oz, unless it's the slp vectorizer.
645 if (S == "z")
646 return isSlpVec;
647
648 unsigned OptLevel = 0;
649 if (S.getAsInteger(10, OptLevel))
650 return false;
651
652 return OptLevel > 1;
653 }
654
655 return false;
656}
657
658/// Add -x lang to \p CmdArgs for \p Input.
659static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
660 ArgStringList &CmdArgs) {
661 // When using -verify-pch, we don't want to provide the type
662 // 'precompiled-header' if it was inferred from the file extension
663 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
664 return;
665
666 CmdArgs.push_back("-x");
667 if (Args.hasArg(options::OPT_rewrite_objc))
668 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000669 else {
670 // Map the driver type to the frontend type. This is mostly an identity
671 // mapping, except that the distinction between module interface units
672 // and other source files does not exist at the frontend layer.
673 const char *ClangType;
674 switch (Input.getType()) {
675 case types::TY_CXXModule:
676 ClangType = "c++";
677 break;
678 case types::TY_PP_CXXModule:
679 ClangType = "c++-cpp-output";
680 break;
681 default:
682 ClangType = types::getTypeName(Input.getType());
683 break;
684 }
685 CmdArgs.push_back(ClangType);
686 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000687}
688
689static void appendUserToPath(SmallVectorImpl<char> &Result) {
690#ifdef LLVM_ON_UNIX
691 const char *Username = getenv("LOGNAME");
692#else
693 const char *Username = getenv("USERNAME");
694#endif
695 if (Username) {
696 // Validate that LoginName can be used in a path, and get its length.
697 size_t Len = 0;
698 for (const char *P = Username; *P; ++P, ++Len) {
699 if (!clang::isAlphanumeric(*P) && *P != '_') {
700 Username = nullptr;
701 break;
702 }
703 }
704
705 if (Username && Len > 0) {
706 Result.append(Username, Username + Len);
707 return;
708 }
709 }
710
711// Fallback to user id.
712#ifdef LLVM_ON_UNIX
713 std::string UID = llvm::utostr(getuid());
714#else
715 // FIXME: Windows seems to have an 'SID' that might work.
716 std::string UID = "9999";
717#endif
718 Result.append(UID.begin(), UID.end());
719}
720
721static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
722 const InputInfo &Output, const ArgList &Args,
723 ArgStringList &CmdArgs) {
724
725 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726 options::OPT_fprofile_generate_EQ,
727 options::OPT_fno_profile_generate);
728 if (PGOGenerateArg &&
729 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730 PGOGenerateArg = nullptr;
731
Rong Xua4a09b22019-03-04 20:21:31 +0000732 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
733 options::OPT_fcs_profile_generate_EQ,
734 options::OPT_fno_profile_generate);
735 if (CSPGOGenerateArg &&
736 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
737 CSPGOGenerateArg = nullptr;
738
David L. Jonesf561aba2017-03-08 01:02:16 +0000739 auto *ProfileGenerateArg = Args.getLastArg(
740 options::OPT_fprofile_instr_generate,
741 options::OPT_fprofile_instr_generate_EQ,
742 options::OPT_fno_profile_instr_generate);
743 if (ProfileGenerateArg &&
744 ProfileGenerateArg->getOption().matches(
745 options::OPT_fno_profile_instr_generate))
746 ProfileGenerateArg = nullptr;
747
748 if (PGOGenerateArg && ProfileGenerateArg)
749 D.Diag(diag::err_drv_argument_not_allowed_with)
750 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
751
752 auto *ProfileUseArg = getLastProfileUseArg(Args);
753
754 if (PGOGenerateArg && ProfileUseArg)
755 D.Diag(diag::err_drv_argument_not_allowed_with)
756 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
757
758 if (ProfileGenerateArg && ProfileUseArg)
759 D.Diag(diag::err_drv_argument_not_allowed_with)
760 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
761
Rong Xua4a09b22019-03-04 20:21:31 +0000762 if (CSPGOGenerateArg && PGOGenerateArg)
763 D.Diag(diag::err_drv_argument_not_allowed_with)
764 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
765
David L. Jonesf561aba2017-03-08 01:02:16 +0000766 if (ProfileGenerateArg) {
767 if (ProfileGenerateArg->getOption().matches(
768 options::OPT_fprofile_instr_generate_EQ))
769 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
770 ProfileGenerateArg->getValue()));
771 // The default is to use Clang Instrumentation.
772 CmdArgs.push_back("-fprofile-instrument=clang");
773 }
774
Rong Xua4a09b22019-03-04 20:21:31 +0000775 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000776 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000777 assert(!CSPGOGenerateArg);
778 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000779 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000780 }
781 if (CSPGOGenerateArg) {
782 assert(!PGOGenerateArg);
783 PGOGenArg = CSPGOGenerateArg;
784 CmdArgs.push_back("-fprofile-instrument=csllvm");
785 }
786 if (PGOGenArg) {
787 if (PGOGenArg->getOption().matches(
788 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
789 : options::OPT_fcs_profile_generate_EQ)) {
790 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000791 llvm::sys::path::append(Path, "default_%m.profraw");
792 CmdArgs.push_back(
793 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
794 }
795 }
796
797 if (ProfileUseArg) {
798 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
799 CmdArgs.push_back(Args.MakeArgString(
800 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
801 else if ((ProfileUseArg->getOption().matches(
802 options::OPT_fprofile_use_EQ) ||
803 ProfileUseArg->getOption().matches(
804 options::OPT_fprofile_instr_use))) {
805 SmallString<128> Path(
806 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
807 if (Path.empty() || llvm::sys::fs::is_directory(Path))
808 llvm::sys::path::append(Path, "default.profdata");
809 CmdArgs.push_back(
810 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
811 }
812 }
813
814 if (Args.hasArg(options::OPT_ftest_coverage) ||
815 Args.hasArg(options::OPT_coverage))
816 CmdArgs.push_back("-femit-coverage-notes");
817 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
818 false) ||
819 Args.hasArg(options::OPT_coverage))
820 CmdArgs.push_back("-femit-coverage-data");
821
822 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000823 options::OPT_fno_coverage_mapping, false)) {
824 if (!ProfileGenerateArg)
825 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
826 << "-fcoverage-mapping"
827 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000828
David L. Jonesf561aba2017-03-08 01:02:16 +0000829 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000830 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000831
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000832 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
833 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
834 if (!Args.hasArg(options::OPT_coverage))
835 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
836 << "-fprofile-exclude-files="
837 << "--coverage";
838
839 StringRef v = Arg->getValue();
840 CmdArgs.push_back(
841 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
842 }
843
844 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
845 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
846 if (!Args.hasArg(options::OPT_coverage))
847 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
848 << "-fprofile-filter-files="
849 << "--coverage";
850
851 StringRef v = Arg->getValue();
852 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
853 }
854
David L. Jonesf561aba2017-03-08 01:02:16 +0000855 if (C.getArgs().hasArg(options::OPT_c) ||
856 C.getArgs().hasArg(options::OPT_S)) {
857 if (Output.isFilename()) {
858 CmdArgs.push_back("-coverage-notes-file");
859 SmallString<128> OutputFilename;
860 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
861 OutputFilename = FinalOutput->getValue();
862 else
863 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
864 SmallString<128> CoverageFilename = OutputFilename;
865 if (llvm::sys::path::is_relative(CoverageFilename)) {
866 SmallString<128> Pwd;
867 if (!llvm::sys::fs::current_path(Pwd)) {
868 llvm::sys::path::append(Pwd, CoverageFilename);
869 CoverageFilename.swap(Pwd);
870 }
871 }
872 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
873 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
874
875 // Leave -fprofile-dir= an unused argument unless .gcda emission is
876 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
877 // the flag used. There is no -fno-profile-dir, so the user has no
878 // targeted way to suppress the warning.
879 if (Args.hasArg(options::OPT_fprofile_arcs) ||
880 Args.hasArg(options::OPT_coverage)) {
881 CmdArgs.push_back("-coverage-data-file");
882 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
883 CoverageFilename = FProfileDir->getValue();
884 llvm::sys::path::append(CoverageFilename, OutputFilename);
885 }
886 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
887 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
888 }
889 }
890 }
891}
892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000893/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000894static bool ContainsCompileAction(const Action *A) {
895 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
896 return true;
897
898 for (const auto &AI : A->inputs())
899 if (ContainsCompileAction(AI))
900 return true;
901
902 return false;
903}
904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000905/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000906/// This is done by default when compiling non-assembler source with -O0.
907static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
908 bool RelaxDefault = true;
909
910 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
911 RelaxDefault = A->getOption().matches(options::OPT_O0);
912
913 if (RelaxDefault) {
914 RelaxDefault = false;
915 for (const auto &Act : C.getActions()) {
916 if (ContainsCompileAction(Act)) {
917 RelaxDefault = true;
918 break;
919 }
920 }
921 }
922
923 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
924 RelaxDefault);
925}
926
927// Extract the integer N from a string spelled "-dwarf-N", returning 0
928// on mismatch. The StringRef input (rather than an Arg) allows
929// for use by the "-Xassembler" option parser.
930static unsigned DwarfVersionNum(StringRef ArgValue) {
931 return llvm::StringSwitch<unsigned>(ArgValue)
932 .Case("-gdwarf-2", 2)
933 .Case("-gdwarf-3", 3)
934 .Case("-gdwarf-4", 4)
935 .Case("-gdwarf-5", 5)
936 .Default(0);
937}
938
939static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
940 codegenoptions::DebugInfoKind DebugInfoKind,
941 unsigned DwarfVersion,
942 llvm::DebuggerKind DebuggerTuning) {
943 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000944 case codegenoptions::DebugDirectivesOnly:
945 CmdArgs.push_back("-debug-info-kind=line-directives-only");
946 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000947 case codegenoptions::DebugLineTablesOnly:
948 CmdArgs.push_back("-debug-info-kind=line-tables-only");
949 break;
950 case codegenoptions::LimitedDebugInfo:
951 CmdArgs.push_back("-debug-info-kind=limited");
952 break;
953 case codegenoptions::FullDebugInfo:
954 CmdArgs.push_back("-debug-info-kind=standalone");
955 break;
956 default:
957 break;
958 }
959 if (DwarfVersion > 0)
960 CmdArgs.push_back(
961 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
962 switch (DebuggerTuning) {
963 case llvm::DebuggerKind::GDB:
964 CmdArgs.push_back("-debugger-tuning=gdb");
965 break;
966 case llvm::DebuggerKind::LLDB:
967 CmdArgs.push_back("-debugger-tuning=lldb");
968 break;
969 case llvm::DebuggerKind::SCE:
970 CmdArgs.push_back("-debugger-tuning=sce");
971 break;
972 default:
973 break;
974 }
975}
976
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000977static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
978 const Driver &D, const ToolChain &TC) {
979 assert(A && "Expected non-nullptr argument.");
980 if (TC.supportsDebugInfoOption(A))
981 return true;
982 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
983 << A->getAsString(Args) << TC.getTripleString();
984 return false;
985}
986
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000987static void RenderDebugInfoCompressionArgs(const ArgList &Args,
988 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000989 const Driver &D,
990 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000991 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
992 if (!A)
993 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000994 if (checkDebugInfoOption(A, Args, D, TC)) {
995 if (A->getOption().getID() == options::OPT_gz) {
996 if (llvm::zlib::isAvailable())
997 CmdArgs.push_back("-compress-debug-sections");
998 else
999 D.Diag(diag::warn_debug_compression_unavailable);
1000 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001001 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001002
1003 StringRef Value = A->getValue();
1004 if (Value == "none") {
1005 CmdArgs.push_back("-compress-debug-sections=none");
1006 } else if (Value == "zlib" || Value == "zlib-gnu") {
1007 if (llvm::zlib::isAvailable()) {
1008 CmdArgs.push_back(
1009 Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
1010 } else {
1011 D.Diag(diag::warn_debug_compression_unavailable);
1012 }
1013 } else {
1014 D.Diag(diag::err_drv_unsupported_option_argument)
1015 << A->getOption().getName() << Value;
1016 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001017 }
1018}
1019
David L. Jonesf561aba2017-03-08 01:02:16 +00001020static const char *RelocationModelName(llvm::Reloc::Model Model) {
1021 switch (Model) {
1022 case llvm::Reloc::Static:
1023 return "static";
1024 case llvm::Reloc::PIC_:
1025 return "pic";
1026 case llvm::Reloc::DynamicNoPIC:
1027 return "dynamic-no-pic";
1028 case llvm::Reloc::ROPI:
1029 return "ropi";
1030 case llvm::Reloc::RWPI:
1031 return "rwpi";
1032 case llvm::Reloc::ROPI_RWPI:
1033 return "ropi-rwpi";
1034 }
1035 llvm_unreachable("Unknown Reloc::Model kind");
1036}
1037
1038void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1039 const Driver &D, const ArgList &Args,
1040 ArgStringList &CmdArgs,
1041 const InputInfo &Output,
1042 const InputInfoList &Inputs) const {
1043 Arg *A;
1044 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1045
1046 CheckPreprocessingOptions(D, Args);
1047
1048 Args.AddLastArg(CmdArgs, options::OPT_C);
1049 Args.AddLastArg(CmdArgs, options::OPT_CC);
1050
1051 // Handle dependency file generation.
1052 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1053 (A = Args.getLastArg(options::OPT_MD)) ||
1054 (A = Args.getLastArg(options::OPT_MMD))) {
1055 // Determine the output location.
1056 const char *DepFile;
1057 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1058 DepFile = MF->getValue();
1059 C.addFailureResultFile(DepFile, &JA);
1060 } else if (Output.getType() == types::TY_Dependencies) {
1061 DepFile = Output.getFilename();
1062 } else if (A->getOption().matches(options::OPT_M) ||
1063 A->getOption().matches(options::OPT_MM)) {
1064 DepFile = "-";
1065 } else {
1066 DepFile = getDependencyFileName(Args, Inputs);
1067 C.addFailureResultFile(DepFile, &JA);
1068 }
1069 CmdArgs.push_back("-dependency-file");
1070 CmdArgs.push_back(DepFile);
1071
1072 // Add a default target if one wasn't specified.
1073 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1074 const char *DepTarget;
1075
1076 // If user provided -o, that is the dependency target, except
1077 // when we are only generating a dependency file.
1078 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1079 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1080 DepTarget = OutputOpt->getValue();
1081 } else {
1082 // Otherwise derive from the base input.
1083 //
1084 // FIXME: This should use the computed output file location.
1085 SmallString<128> P(Inputs[0].getBaseInput());
1086 llvm::sys::path::replace_extension(P, "o");
1087 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1088 }
1089
Yuka Takahashicdb53482017-06-16 16:01:13 +00001090 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1091 CmdArgs.push_back("-w");
1092 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001093 CmdArgs.push_back("-MT");
1094 SmallString<128> Quoted;
1095 QuoteTarget(DepTarget, Quoted);
1096 CmdArgs.push_back(Args.MakeArgString(Quoted));
1097 }
1098
1099 if (A->getOption().matches(options::OPT_M) ||
1100 A->getOption().matches(options::OPT_MD))
1101 CmdArgs.push_back("-sys-header-deps");
1102 if ((isa<PrecompileJobAction>(JA) &&
1103 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1104 Args.hasArg(options::OPT_fmodule_file_deps))
1105 CmdArgs.push_back("-module-file-deps");
1106 }
1107
1108 if (Args.hasArg(options::OPT_MG)) {
1109 if (!A || A->getOption().matches(options::OPT_MD) ||
1110 A->getOption().matches(options::OPT_MMD))
1111 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1112 CmdArgs.push_back("-MG");
1113 }
1114
1115 Args.AddLastArg(CmdArgs, options::OPT_MP);
1116 Args.AddLastArg(CmdArgs, options::OPT_MV);
1117
1118 // Convert all -MQ <target> args to -MT <quoted target>
1119 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1120 A->claim();
1121
1122 if (A->getOption().matches(options::OPT_MQ)) {
1123 CmdArgs.push_back("-MT");
1124 SmallString<128> Quoted;
1125 QuoteTarget(A->getValue(), Quoted);
1126 CmdArgs.push_back(Args.MakeArgString(Quoted));
1127
1128 // -MT flag - no change
1129 } else {
1130 A->render(Args, CmdArgs);
1131 }
1132 }
1133
1134 // Add offload include arguments specific for CUDA. This must happen before
1135 // we -I or -include anything else, because we must pick up the CUDA headers
1136 // from the particular CUDA installation, rather than from e.g.
1137 // /usr/local/include.
1138 if (JA.isOffloading(Action::OFK_Cuda))
1139 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1140
1141 // Add -i* options, and automatically translate to
1142 // -include-pch/-include-pth for transparent PCH support. It's
1143 // wonky, but we include looking for .gch so we can support seamless
1144 // replacement into a build system already set up to be generating
1145 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001146
1147 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001148 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1149 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001150 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1151 JA.getKind() <= Action::AssembleJobClass) {
1152 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001153 }
Erich Keane76675de2018-07-05 17:22:13 +00001154 if (YcArg || YuArg) {
1155 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1156 if (!isa<PrecompileJobAction>(JA)) {
1157 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001158 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1159 C, !ThroughHeader.empty()
1160 ? ThroughHeader
1161 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001162 }
Mike Rice58df1af2018-09-11 17:10:44 +00001163
1164 if (ThroughHeader.empty()) {
1165 CmdArgs.push_back(Args.MakeArgString(
1166 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1167 } else {
1168 CmdArgs.push_back(
1169 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1170 }
Erich Keane76675de2018-07-05 17:22:13 +00001171 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001172 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001173
1174 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001175 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001176 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001177 // Handling of gcc-style gch precompiled headers.
1178 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1179 RenderedImplicitInclude = true;
1180
David L. Jonesf561aba2017-03-08 01:02:16 +00001181 bool FoundPCH = false;
1182 SmallString<128> P(A->getValue());
1183 // We want the files to have a name like foo.h.pch. Add a dummy extension
1184 // so that replace_extension does the right thing.
1185 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001186 llvm::sys::path::replace_extension(P, "pch");
1187 if (llvm::sys::fs::exists(P))
1188 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001189
1190 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001191 llvm::sys::path::replace_extension(P, "gch");
1192 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001193 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001194 }
1195 }
1196
Erich Keane0a6b5b62018-12-04 14:34:09 +00001197 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001198 if (IsFirstImplicitInclude) {
1199 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001200 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001201 CmdArgs.push_back(Args.MakeArgString(P));
1202 continue;
1203 } else {
1204 // Ignore the PCH if not first on command line and emit warning.
1205 D.Diag(diag::warn_drv_pch_not_first_include) << P
1206 << A->getAsString(Args);
1207 }
1208 }
1209 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1210 // Handling of paths which must come late. These entries are handled by
1211 // the toolchain itself after the resource dir is inserted in the right
1212 // search order.
1213 // Do not claim the argument so that the use of the argument does not
1214 // silently go unnoticed on toolchains which do not honour the option.
1215 continue;
1216 }
1217
1218 // Not translated, render as usual.
1219 A->claim();
1220 A->render(Args, CmdArgs);
1221 }
1222
1223 Args.AddAllArgs(CmdArgs,
1224 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1225 options::OPT_F, options::OPT_index_header_map});
1226
1227 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1228
1229 // FIXME: There is a very unfortunate problem here, some troubled
1230 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1231 // really support that we would have to parse and then translate
1232 // those options. :(
1233 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1234 options::OPT_Xpreprocessor);
1235
1236 // -I- is a deprecated GCC feature, reject it.
1237 if (Arg *A = Args.getLastArg(options::OPT_I_))
1238 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1239
1240 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1241 // -isysroot to the CC1 invocation.
1242 StringRef sysroot = C.getSysRoot();
1243 if (sysroot != "") {
1244 if (!Args.hasArg(options::OPT_isysroot)) {
1245 CmdArgs.push_back("-isysroot");
1246 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1247 }
1248 }
1249
1250 // Parse additional include paths from environment variables.
1251 // FIXME: We should probably sink the logic for handling these from the
1252 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1253 // CPATH - included following the user specified includes (but prior to
1254 // builtin and standard includes).
1255 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1256 // C_INCLUDE_PATH - system includes enabled when compiling C.
1257 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1258 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1259 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1260 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1261 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1262 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1263 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1264
1265 // While adding the include arguments, we also attempt to retrieve the
1266 // arguments of related offloading toolchains or arguments that are specific
1267 // of an offloading programming model.
1268
1269 // Add C++ include arguments, if needed.
1270 if (types::isCXX(Inputs[0].getType()))
1271 forAllAssociatedToolChains(C, JA, getToolChain(),
1272 [&Args, &CmdArgs](const ToolChain &TC) {
1273 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1274 });
1275
1276 // Add system include arguments for all targets but IAMCU.
1277 if (!IsIAMCU)
1278 forAllAssociatedToolChains(C, JA, getToolChain(),
1279 [&Args, &CmdArgs](const ToolChain &TC) {
1280 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1281 });
1282 else {
1283 // For IAMCU add special include arguments.
1284 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1285 }
1286}
1287
1288// FIXME: Move to target hook.
1289static bool isSignedCharDefault(const llvm::Triple &Triple) {
1290 switch (Triple.getArch()) {
1291 default:
1292 return true;
1293
1294 case llvm::Triple::aarch64:
1295 case llvm::Triple::aarch64_be:
1296 case llvm::Triple::arm:
1297 case llvm::Triple::armeb:
1298 case llvm::Triple::thumb:
1299 case llvm::Triple::thumbeb:
1300 if (Triple.isOSDarwin() || Triple.isOSWindows())
1301 return true;
1302 return false;
1303
1304 case llvm::Triple::ppc:
1305 case llvm::Triple::ppc64:
1306 if (Triple.isOSDarwin())
1307 return true;
1308 return false;
1309
1310 case llvm::Triple::hexagon:
1311 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001312 case llvm::Triple::riscv32:
1313 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001314 case llvm::Triple::systemz:
1315 case llvm::Triple::xcore:
1316 return false;
1317 }
1318}
1319
1320static bool isNoCommonDefault(const llvm::Triple &Triple) {
1321 switch (Triple.getArch()) {
1322 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001323 if (Triple.isOSFuchsia())
1324 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001325 return false;
1326
1327 case llvm::Triple::xcore:
1328 case llvm::Triple::wasm32:
1329 case llvm::Triple::wasm64:
1330 return true;
1331 }
1332}
1333
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001334namespace {
1335void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1336 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001337 // Select the ABI to use.
1338 // FIXME: Support -meabi.
1339 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1340 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001341 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001342 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001343 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001344 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001345 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001346 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001347
David L. Jonesf561aba2017-03-08 01:02:16 +00001348 CmdArgs.push_back("-target-abi");
1349 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001350}
1351}
1352
1353void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1354 ArgStringList &CmdArgs, bool KernelOrKext) const {
1355 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001356
1357 // Determine floating point ABI from the options & target defaults.
1358 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1359 if (ABI == arm::FloatABI::Soft) {
1360 // Floating point operations and argument passing are soft.
1361 // FIXME: This changes CPP defines, we need -target-soft-float.
1362 CmdArgs.push_back("-msoft-float");
1363 CmdArgs.push_back("-mfloat-abi");
1364 CmdArgs.push_back("soft");
1365 } else if (ABI == arm::FloatABI::SoftFP) {
1366 // Floating point operations are hard, but argument passing is soft.
1367 CmdArgs.push_back("-mfloat-abi");
1368 CmdArgs.push_back("soft");
1369 } else {
1370 // Floating point operations and argument passing are hard.
1371 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1372 CmdArgs.push_back("-mfloat-abi");
1373 CmdArgs.push_back("hard");
1374 }
1375
1376 // Forward the -mglobal-merge option for explicit control over the pass.
1377 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1378 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001379 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001380 if (A->getOption().matches(options::OPT_mno_global_merge))
1381 CmdArgs.push_back("-arm-global-merge=false");
1382 else
1383 CmdArgs.push_back("-arm-global-merge=true");
1384 }
1385
1386 if (!Args.hasFlag(options::OPT_mimplicit_float,
1387 options::OPT_mno_implicit_float, true))
1388 CmdArgs.push_back("-no-implicit-float");
1389}
1390
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001391void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1392 const ArgList &Args, bool KernelOrKext,
1393 ArgStringList &CmdArgs) const {
1394 const ToolChain &TC = getToolChain();
1395
1396 // Add the target features
1397 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1398
1399 // Add target specific flags.
1400 switch (TC.getArch()) {
1401 default:
1402 break;
1403
1404 case llvm::Triple::arm:
1405 case llvm::Triple::armeb:
1406 case llvm::Triple::thumb:
1407 case llvm::Triple::thumbeb:
1408 // Use the effective triple, which takes into account the deployment target.
1409 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1410 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1411 break;
1412
1413 case llvm::Triple::aarch64:
1414 case llvm::Triple::aarch64_be:
1415 AddAArch64TargetArgs(Args, CmdArgs);
1416 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1417 break;
1418
1419 case llvm::Triple::mips:
1420 case llvm::Triple::mipsel:
1421 case llvm::Triple::mips64:
1422 case llvm::Triple::mips64el:
1423 AddMIPSTargetArgs(Args, CmdArgs);
1424 break;
1425
1426 case llvm::Triple::ppc:
1427 case llvm::Triple::ppc64:
1428 case llvm::Triple::ppc64le:
1429 AddPPCTargetArgs(Args, CmdArgs);
1430 break;
1431
Alex Bradbury71f45452018-01-11 13:36:56 +00001432 case llvm::Triple::riscv32:
1433 case llvm::Triple::riscv64:
1434 AddRISCVTargetArgs(Args, CmdArgs);
1435 break;
1436
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001437 case llvm::Triple::sparc:
1438 case llvm::Triple::sparcel:
1439 case llvm::Triple::sparcv9:
1440 AddSparcTargetArgs(Args, CmdArgs);
1441 break;
1442
1443 case llvm::Triple::systemz:
1444 AddSystemZTargetArgs(Args, CmdArgs);
1445 break;
1446
1447 case llvm::Triple::x86:
1448 case llvm::Triple::x86_64:
1449 AddX86TargetArgs(Args, CmdArgs);
1450 break;
1451
1452 case llvm::Triple::lanai:
1453 AddLanaiTargetArgs(Args, CmdArgs);
1454 break;
1455
1456 case llvm::Triple::hexagon:
1457 AddHexagonTargetArgs(Args, CmdArgs);
1458 break;
1459
1460 case llvm::Triple::wasm32:
1461 case llvm::Triple::wasm64:
1462 AddWebAssemblyTargetArgs(Args, CmdArgs);
1463 break;
1464 }
1465}
1466
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001467// Parse -mbranch-protection=<protection>[+<protection>]* where
1468// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1469// Returns a triple of (return address signing Scope, signing key, require
1470// landing pads)
1471static std::tuple<StringRef, StringRef, bool>
1472ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1473 const Arg *A) {
1474 StringRef Scope = "none";
1475 StringRef Key = "a_key";
1476 bool IndirectBranches = false;
1477
1478 StringRef Value = A->getValue();
1479 // This maps onto -mbranch-protection=<scope>+<key>
1480
1481 if (Value.equals("standard")) {
1482 Scope = "non-leaf";
1483 Key = "a_key";
1484 IndirectBranches = true;
1485
1486 } else if (!Value.equals("none")) {
1487 SmallVector<StringRef, 4> BranchProtection;
1488 StringRef(A->getValue()).split(BranchProtection, '+');
1489
1490 auto Protection = BranchProtection.begin();
1491 while (Protection != BranchProtection.end()) {
1492 if (Protection->equals("bti"))
1493 IndirectBranches = true;
1494 else if (Protection->equals("pac-ret")) {
1495 Scope = "non-leaf";
1496 while (++Protection != BranchProtection.end()) {
1497 // Inner loop as "leaf" and "b-key" options must only appear attached
1498 // to pac-ret.
1499 if (Protection->equals("leaf"))
1500 Scope = "all";
1501 else if (Protection->equals("b-key"))
1502 Key = "b_key";
1503 else
1504 break;
1505 }
1506 Protection--;
1507 } else
1508 D.Diag(diag::err_invalid_branch_protection)
1509 << *Protection << A->getAsString(Args);
1510 Protection++;
1511 }
1512 }
1513
1514 return std::make_tuple(Scope, Key, IndirectBranches);
1515}
1516
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001517namespace {
1518void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1519 ArgStringList &CmdArgs) {
1520 const char *ABIName = nullptr;
1521 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1522 ABIName = A->getValue();
1523 else if (Triple.isOSDarwin())
1524 ABIName = "darwinpcs";
1525 else
1526 ABIName = "aapcs";
1527
1528 CmdArgs.push_back("-target-abi");
1529 CmdArgs.push_back(ABIName);
1530}
1531}
1532
David L. Jonesf561aba2017-03-08 01:02:16 +00001533void Clang::AddAArch64TargetArgs(const ArgList &Args,
1534 ArgStringList &CmdArgs) const {
1535 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1536
1537 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1538 Args.hasArg(options::OPT_mkernel) ||
1539 Args.hasArg(options::OPT_fapple_kext))
1540 CmdArgs.push_back("-disable-red-zone");
1541
1542 if (!Args.hasFlag(options::OPT_mimplicit_float,
1543 options::OPT_mno_implicit_float, true))
1544 CmdArgs.push_back("-no-implicit-float");
1545
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001546 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001547
1548 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1549 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001550 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001551 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1552 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1553 else
1554 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1555 } else if (Triple.isAndroid()) {
1556 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001557 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001558 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1559 }
1560
1561 // Forward the -mglobal-merge option for explicit control over the pass.
1562 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1563 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001564 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001565 if (A->getOption().matches(options::OPT_mno_global_merge))
1566 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1567 else
1568 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1569 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001570
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001571 // Enable/disable return address signing and indirect branch targets.
1572 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1573 options::OPT_mbranch_protection_EQ)) {
1574
1575 const Driver &D = getToolChain().getDriver();
1576
1577 StringRef Scope, Key;
1578 bool IndirectBranches;
1579
1580 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1581 Scope = A->getValue();
1582 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1583 !Scope.equals("all"))
1584 D.Diag(diag::err_invalid_branch_protection)
1585 << Scope << A->getAsString(Args);
1586 Key = "a_key";
1587 IndirectBranches = false;
1588 } else
1589 std::tie(Scope, Key, IndirectBranches) =
1590 ParseAArch64BranchProtection(D, Args, A);
1591
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001592 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001593 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1594 CmdArgs.push_back(
1595 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1596 if (IndirectBranches)
1597 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001598 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001599}
1600
1601void Clang::AddMIPSTargetArgs(const ArgList &Args,
1602 ArgStringList &CmdArgs) const {
1603 const Driver &D = getToolChain().getDriver();
1604 StringRef CPUName;
1605 StringRef ABIName;
1606 const llvm::Triple &Triple = getToolChain().getTriple();
1607 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1608
1609 CmdArgs.push_back("-target-abi");
1610 CmdArgs.push_back(ABIName.data());
1611
1612 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1613 if (ABI == mips::FloatABI::Soft) {
1614 // Floating point operations and argument passing are soft.
1615 CmdArgs.push_back("-msoft-float");
1616 CmdArgs.push_back("-mfloat-abi");
1617 CmdArgs.push_back("soft");
1618 } else {
1619 // Floating point operations and argument passing are hard.
1620 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1621 CmdArgs.push_back("-mfloat-abi");
1622 CmdArgs.push_back("hard");
1623 }
1624
1625 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1626 if (A->getOption().matches(options::OPT_mxgot)) {
1627 CmdArgs.push_back("-mllvm");
1628 CmdArgs.push_back("-mxgot");
1629 }
1630 }
1631
1632 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1633 options::OPT_mno_ldc1_sdc1)) {
1634 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1635 CmdArgs.push_back("-mllvm");
1636 CmdArgs.push_back("-mno-ldc1-sdc1");
1637 }
1638 }
1639
1640 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1641 options::OPT_mno_check_zero_division)) {
1642 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1643 CmdArgs.push_back("-mllvm");
1644 CmdArgs.push_back("-mno-check-zero-division");
1645 }
1646 }
1647
1648 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1649 StringRef v = A->getValue();
1650 CmdArgs.push_back("-mllvm");
1651 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1652 A->claim();
1653 }
1654
Simon Dardis31636a12017-07-20 14:04:12 +00001655 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1656 Arg *ABICalls =
1657 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1658
1659 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1660 // -mgpopt is the default for static, -fno-pic environments but these two
1661 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1662 // the only case where -mllvm -mgpopt is passed.
1663 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1664 // passed explicitly when compiling something with -mabicalls
1665 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001666 //
1667 // When the ABI in use is N64, we also need to determine the PIC mode that
1668 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001669 bool NoABICalls =
1670 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001671
1672 llvm::Reloc::Model RelocationModel;
1673 unsigned PICLevel;
1674 bool IsPIE;
1675 std::tie(RelocationModel, PICLevel, IsPIE) =
1676 ParsePICArgs(getToolChain(), Args);
1677
1678 NoABICalls = NoABICalls ||
1679 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1680
Simon Dardis31636a12017-07-20 14:04:12 +00001681 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1682 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1683 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1684 CmdArgs.push_back("-mllvm");
1685 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001686
1687 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1688 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001689 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001690 options::OPT_mno_extern_sdata);
1691 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1692 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001693 if (LocalSData) {
1694 CmdArgs.push_back("-mllvm");
1695 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1696 CmdArgs.push_back("-mlocal-sdata=1");
1697 } else {
1698 CmdArgs.push_back("-mlocal-sdata=0");
1699 }
1700 LocalSData->claim();
1701 }
1702
Simon Dardis7d318782017-07-24 14:02:09 +00001703 if (ExternSData) {
1704 CmdArgs.push_back("-mllvm");
1705 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1706 CmdArgs.push_back("-mextern-sdata=1");
1707 } else {
1708 CmdArgs.push_back("-mextern-sdata=0");
1709 }
1710 ExternSData->claim();
1711 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001712
1713 if (EmbeddedData) {
1714 CmdArgs.push_back("-mllvm");
1715 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1716 CmdArgs.push_back("-membedded-data=1");
1717 } else {
1718 CmdArgs.push_back("-membedded-data=0");
1719 }
1720 EmbeddedData->claim();
1721 }
1722
Simon Dardis31636a12017-07-20 14:04:12 +00001723 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1724 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1725
1726 if (GPOpt)
1727 GPOpt->claim();
1728
David L. Jonesf561aba2017-03-08 01:02:16 +00001729 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1730 StringRef Val = StringRef(A->getValue());
1731 if (mips::hasCompactBranches(CPUName)) {
1732 if (Val == "never" || Val == "always" || Val == "optimal") {
1733 CmdArgs.push_back("-mllvm");
1734 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1735 } else
1736 D.Diag(diag::err_drv_unsupported_option_argument)
1737 << A->getOption().getName() << Val;
1738 } else
1739 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1740 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001741
1742 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1743 options::OPT_mno_relax_pic_calls)) {
1744 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1745 CmdArgs.push_back("-mllvm");
1746 CmdArgs.push_back("-mips-jalr-reloc=0");
1747 }
1748 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001749}
1750
1751void Clang::AddPPCTargetArgs(const ArgList &Args,
1752 ArgStringList &CmdArgs) const {
1753 // Select the ABI to use.
1754 const char *ABIName = nullptr;
1755 if (getToolChain().getTriple().isOSLinux())
1756 switch (getToolChain().getArch()) {
1757 case llvm::Triple::ppc64: {
1758 // When targeting a processor that supports QPX, or if QPX is
1759 // specifically enabled, default to using the ABI that supports QPX (so
1760 // long as it is not specifically disabled).
1761 bool HasQPX = false;
1762 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763 HasQPX = A->getValue() == StringRef("a2q");
1764 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1765 if (HasQPX) {
1766 ABIName = "elfv1-qpx";
1767 break;
1768 }
1769
1770 ABIName = "elfv1";
1771 break;
1772 }
1773 case llvm::Triple::ppc64le:
1774 ABIName = "elfv2";
1775 break;
1776 default:
1777 break;
1778 }
1779
1780 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1781 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1782 // the option if given as we don't have backend support for any targets
1783 // that don't use the altivec abi.
1784 if (StringRef(A->getValue()) != "altivec")
1785 ABIName = A->getValue();
1786
1787 ppc::FloatABI FloatABI =
1788 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1789
1790 if (FloatABI == ppc::FloatABI::Soft) {
1791 // Floating point operations and argument passing are soft.
1792 CmdArgs.push_back("-msoft-float");
1793 CmdArgs.push_back("-mfloat-abi");
1794 CmdArgs.push_back("soft");
1795 } else {
1796 // Floating point operations and argument passing are hard.
1797 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1798 CmdArgs.push_back("-mfloat-abi");
1799 CmdArgs.push_back("hard");
1800 }
1801
1802 if (ABIName) {
1803 CmdArgs.push_back("-target-abi");
1804 CmdArgs.push_back(ABIName);
1805 }
1806}
1807
Alex Bradbury71f45452018-01-11 13:36:56 +00001808void Clang::AddRISCVTargetArgs(const ArgList &Args,
1809 ArgStringList &CmdArgs) const {
1810 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001811 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001812 const char *ABIName = nullptr;
1813 const llvm::Triple &Triple = getToolChain().getTriple();
1814 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1815 ABIName = A->getValue();
1816 else if (Triple.getArch() == llvm::Triple::riscv32)
1817 ABIName = "ilp32";
1818 else if (Triple.getArch() == llvm::Triple::riscv64)
1819 ABIName = "lp64";
1820 else
1821 llvm_unreachable("Unexpected triple!");
1822
1823 CmdArgs.push_back("-target-abi");
1824 CmdArgs.push_back(ABIName);
1825}
1826
David L. Jonesf561aba2017-03-08 01:02:16 +00001827void Clang::AddSparcTargetArgs(const ArgList &Args,
1828 ArgStringList &CmdArgs) const {
1829 sparc::FloatABI FloatABI =
1830 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1831
1832 if (FloatABI == sparc::FloatABI::Soft) {
1833 // Floating point operations and argument passing are soft.
1834 CmdArgs.push_back("-msoft-float");
1835 CmdArgs.push_back("-mfloat-abi");
1836 CmdArgs.push_back("soft");
1837 } else {
1838 // Floating point operations and argument passing are hard.
1839 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1840 CmdArgs.push_back("-mfloat-abi");
1841 CmdArgs.push_back("hard");
1842 }
1843}
1844
1845void Clang::AddSystemZTargetArgs(const ArgList &Args,
1846 ArgStringList &CmdArgs) const {
1847 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1848 CmdArgs.push_back("-mbackchain");
1849}
1850
1851void Clang::AddX86TargetArgs(const ArgList &Args,
1852 ArgStringList &CmdArgs) const {
1853 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1854 Args.hasArg(options::OPT_mkernel) ||
1855 Args.hasArg(options::OPT_fapple_kext))
1856 CmdArgs.push_back("-disable-red-zone");
1857
Kristina Brooks7f569b72018-10-18 14:07:02 +00001858 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1859 options::OPT_mno_tls_direct_seg_refs, true))
1860 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1861
David L. Jonesf561aba2017-03-08 01:02:16 +00001862 // Default to avoid implicit floating-point for kernel/kext code, but allow
1863 // that to be overridden with -mno-soft-float.
1864 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1865 Args.hasArg(options::OPT_fapple_kext));
1866 if (Arg *A = Args.getLastArg(
1867 options::OPT_msoft_float, options::OPT_mno_soft_float,
1868 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1869 const Option &O = A->getOption();
1870 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1871 O.matches(options::OPT_msoft_float));
1872 }
1873 if (NoImplicitFloat)
1874 CmdArgs.push_back("-no-implicit-float");
1875
1876 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1877 StringRef Value = A->getValue();
1878 if (Value == "intel" || Value == "att") {
1879 CmdArgs.push_back("-mllvm");
1880 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1881 } else {
1882 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1883 << A->getOption().getName() << Value;
1884 }
Nico Webere3712cf2018-01-17 13:34:20 +00001885 } else if (getToolChain().getDriver().IsCLMode()) {
1886 CmdArgs.push_back("-mllvm");
1887 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001888 }
1889
1890 // Set flags to support MCU ABI.
1891 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1892 CmdArgs.push_back("-mfloat-abi");
1893 CmdArgs.push_back("soft");
1894 CmdArgs.push_back("-mstack-alignment=4");
1895 }
1896}
1897
1898void Clang::AddHexagonTargetArgs(const ArgList &Args,
1899 ArgStringList &CmdArgs) const {
1900 CmdArgs.push_back("-mqdsp6-compat");
1901 CmdArgs.push_back("-Wreturn-type");
1902
1903 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001904 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001905 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1906 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001907 }
1908
1909 if (!Args.hasArg(options::OPT_fno_short_enums))
1910 CmdArgs.push_back("-fshort-enums");
1911 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1912 CmdArgs.push_back("-mllvm");
1913 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1914 }
1915 CmdArgs.push_back("-mllvm");
1916 CmdArgs.push_back("-machine-sink-split=0");
1917}
1918
1919void Clang::AddLanaiTargetArgs(const ArgList &Args,
1920 ArgStringList &CmdArgs) const {
1921 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1922 StringRef CPUName = A->getValue();
1923
1924 CmdArgs.push_back("-target-cpu");
1925 CmdArgs.push_back(Args.MakeArgString(CPUName));
1926 }
1927 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1928 StringRef Value = A->getValue();
1929 // Only support mregparm=4 to support old usage. Report error for all other
1930 // cases.
1931 int Mregparm;
1932 if (Value.getAsInteger(10, Mregparm)) {
1933 if (Mregparm != 4) {
1934 getToolChain().getDriver().Diag(
1935 diag::err_drv_unsupported_option_argument)
1936 << A->getOption().getName() << Value;
1937 }
1938 }
1939 }
1940}
1941
1942void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1943 ArgStringList &CmdArgs) const {
1944 // Default to "hidden" visibility.
1945 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1946 options::OPT_fvisibility_ms_compat)) {
1947 CmdArgs.push_back("-fvisibility");
1948 CmdArgs.push_back("hidden");
1949 }
1950}
1951
1952void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1953 StringRef Target, const InputInfo &Output,
1954 const InputInfo &Input, const ArgList &Args) const {
1955 // If this is a dry run, do not create the compilation database file.
1956 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1957 return;
1958
1959 using llvm::yaml::escape;
1960 const Driver &D = getToolChain().getDriver();
1961
1962 if (!CompilationDatabase) {
1963 std::error_code EC;
1964 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1965 if (EC) {
1966 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1967 << EC.message();
1968 return;
1969 }
1970 CompilationDatabase = std::move(File);
1971 }
1972 auto &CDB = *CompilationDatabase;
1973 SmallString<128> Buf;
1974 if (llvm::sys::fs::current_path(Buf))
1975 Buf = ".";
1976 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1977 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1978 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1979 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1980 Buf = "-x";
1981 Buf += types::getTypeName(Input.getType());
1982 CDB << ", \"" << escape(Buf) << "\"";
1983 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1984 Buf = "--sysroot=";
1985 Buf += D.SysRoot;
1986 CDB << ", \"" << escape(Buf) << "\"";
1987 }
1988 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1989 for (auto &A: Args) {
1990 auto &O = A->getOption();
1991 // Skip language selection, which is positional.
1992 if (O.getID() == options::OPT_x)
1993 continue;
1994 // Skip writing dependency output and the compilation database itself.
1995 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1996 continue;
1997 // Skip inputs.
1998 if (O.getKind() == Option::InputClass)
1999 continue;
2000 // All other arguments are quoted and appended.
2001 ArgStringList ASL;
2002 A->render(Args, ASL);
2003 for (auto &it: ASL)
2004 CDB << ", \"" << escape(it) << "\"";
2005 }
2006 Buf = "--target=";
2007 Buf += Target;
2008 CDB << ", \"" << escape(Buf) << "\"]},\n";
2009}
2010
2011static void CollectArgsForIntegratedAssembler(Compilation &C,
2012 const ArgList &Args,
2013 ArgStringList &CmdArgs,
2014 const Driver &D) {
2015 if (UseRelaxAll(C, Args))
2016 CmdArgs.push_back("-mrelax-all");
2017
2018 // Only default to -mincremental-linker-compatible if we think we are
2019 // targeting the MSVC linker.
2020 bool DefaultIncrementalLinkerCompatible =
2021 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2022 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2023 options::OPT_mno_incremental_linker_compatible,
2024 DefaultIncrementalLinkerCompatible))
2025 CmdArgs.push_back("-mincremental-linker-compatible");
2026
2027 switch (C.getDefaultToolChain().getArch()) {
2028 case llvm::Triple::arm:
2029 case llvm::Triple::armeb:
2030 case llvm::Triple::thumb:
2031 case llvm::Triple::thumbeb:
2032 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2033 StringRef Value = A->getValue();
2034 if (Value == "always" || Value == "never" || Value == "arm" ||
2035 Value == "thumb") {
2036 CmdArgs.push_back("-mllvm");
2037 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2038 } else {
2039 D.Diag(diag::err_drv_unsupported_option_argument)
2040 << A->getOption().getName() << Value;
2041 }
2042 }
2043 break;
2044 default:
2045 break;
2046 }
2047
2048 // When passing -I arguments to the assembler we sometimes need to
2049 // unconditionally take the next argument. For example, when parsing
2050 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2051 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2052 // arg after parsing the '-I' arg.
2053 bool TakeNextArg = false;
2054
Petr Hosek5668d832017-11-22 01:38:31 +00002055 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
David L. Jonesf561aba2017-03-08 01:02:16 +00002056 const char *MipsTargetFeature = nullptr;
2057 for (const Arg *A :
2058 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2059 A->claim();
2060
2061 for (StringRef Value : A->getValues()) {
2062 if (TakeNextArg) {
2063 CmdArgs.push_back(Value.data());
2064 TakeNextArg = false;
2065 continue;
2066 }
2067
2068 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2069 Value == "-mbig-obj")
2070 continue; // LLVM handles bigobj automatically
2071
2072 switch (C.getDefaultToolChain().getArch()) {
2073 default:
2074 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002075 case llvm::Triple::thumb:
2076 case llvm::Triple::thumbeb:
2077 case llvm::Triple::arm:
2078 case llvm::Triple::armeb:
2079 if (Value == "-mthumb")
2080 // -mthumb has already been processed in ComputeLLVMTriple()
2081 // recognize but skip over here.
2082 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002083 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002084 case llvm::Triple::mips:
2085 case llvm::Triple::mipsel:
2086 case llvm::Triple::mips64:
2087 case llvm::Triple::mips64el:
2088 if (Value == "--trap") {
2089 CmdArgs.push_back("-target-feature");
2090 CmdArgs.push_back("+use-tcc-in-div");
2091 continue;
2092 }
2093 if (Value == "--break") {
2094 CmdArgs.push_back("-target-feature");
2095 CmdArgs.push_back("-use-tcc-in-div");
2096 continue;
2097 }
2098 if (Value.startswith("-msoft-float")) {
2099 CmdArgs.push_back("-target-feature");
2100 CmdArgs.push_back("+soft-float");
2101 continue;
2102 }
2103 if (Value.startswith("-mhard-float")) {
2104 CmdArgs.push_back("-target-feature");
2105 CmdArgs.push_back("-soft-float");
2106 continue;
2107 }
2108
2109 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2110 .Case("-mips1", "+mips1")
2111 .Case("-mips2", "+mips2")
2112 .Case("-mips3", "+mips3")
2113 .Case("-mips4", "+mips4")
2114 .Case("-mips5", "+mips5")
2115 .Case("-mips32", "+mips32")
2116 .Case("-mips32r2", "+mips32r2")
2117 .Case("-mips32r3", "+mips32r3")
2118 .Case("-mips32r5", "+mips32r5")
2119 .Case("-mips32r6", "+mips32r6")
2120 .Case("-mips64", "+mips64")
2121 .Case("-mips64r2", "+mips64r2")
2122 .Case("-mips64r3", "+mips64r3")
2123 .Case("-mips64r5", "+mips64r5")
2124 .Case("-mips64r6", "+mips64r6")
2125 .Default(nullptr);
2126 if (MipsTargetFeature)
2127 continue;
2128 }
2129
2130 if (Value == "-force_cpusubtype_ALL") {
2131 // Do nothing, this is the default and we don't support anything else.
2132 } else if (Value == "-L") {
2133 CmdArgs.push_back("-msave-temp-labels");
2134 } else if (Value == "--fatal-warnings") {
2135 CmdArgs.push_back("-massembler-fatal-warnings");
2136 } else if (Value == "--noexecstack") {
2137 CmdArgs.push_back("-mnoexecstack");
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002138 } else if (Value.startswith("-compress-debug-sections") ||
2139 Value.startswith("--compress-debug-sections") ||
2140 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002141 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002142 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002143 } else if (Value == "-mrelax-relocations=yes" ||
2144 Value == "--mrelax-relocations=yes") {
2145 UseRelaxRelocations = true;
2146 } else if (Value == "-mrelax-relocations=no" ||
2147 Value == "--mrelax-relocations=no") {
2148 UseRelaxRelocations = false;
2149 } else if (Value.startswith("-I")) {
2150 CmdArgs.push_back(Value.data());
2151 // We need to consume the next argument if the current arg is a plain
2152 // -I. The next arg will be the include directory.
2153 if (Value == "-I")
2154 TakeNextArg = true;
2155 } else if (Value.startswith("-gdwarf-")) {
2156 // "-gdwarf-N" options are not cc1as options.
2157 unsigned DwarfVersion = DwarfVersionNum(Value);
2158 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2159 CmdArgs.push_back(Value.data());
2160 } else {
2161 RenderDebugEnablingArgs(Args, CmdArgs,
2162 codegenoptions::LimitedDebugInfo,
2163 DwarfVersion, llvm::DebuggerKind::Default);
2164 }
2165 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2166 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2167 // Do nothing, we'll validate it later.
2168 } else if (Value == "-defsym") {
2169 if (A->getNumValues() != 2) {
2170 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2171 break;
2172 }
2173 const char *S = A->getValue(1);
2174 auto Pair = StringRef(S).split('=');
2175 auto Sym = Pair.first;
2176 auto SVal = Pair.second;
2177
2178 if (Sym.empty() || SVal.empty()) {
2179 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2180 break;
2181 }
2182 int64_t IVal;
2183 if (SVal.getAsInteger(0, IVal)) {
2184 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2185 break;
2186 }
2187 CmdArgs.push_back(Value.data());
2188 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002189 } else if (Value == "-fdebug-compilation-dir") {
2190 CmdArgs.push_back("-fdebug-compilation-dir");
2191 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002192 } else {
2193 D.Diag(diag::err_drv_unsupported_option_argument)
2194 << A->getOption().getName() << Value;
2195 }
2196 }
2197 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002198 if (UseRelaxRelocations)
2199 CmdArgs.push_back("--mrelax-relocations");
2200 if (MipsTargetFeature != nullptr) {
2201 CmdArgs.push_back("-target-feature");
2202 CmdArgs.push_back(MipsTargetFeature);
2203 }
Steven Wu098742f2018-12-12 17:30:16 +00002204
2205 // forward -fembed-bitcode to assmebler
2206 if (C.getDriver().embedBitcodeEnabled() ||
2207 C.getDriver().embedBitcodeMarkerOnly())
2208 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002209}
2210
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002211static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2212 bool OFastEnabled, const ArgList &Args,
2213 ArgStringList &CmdArgs) {
2214 // Handle various floating point optimization flags, mapping them to the
2215 // appropriate LLVM code generation flags. This is complicated by several
2216 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002217 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002218 // LLVM flags based on the final state.
2219 bool HonorINFs = true;
2220 bool HonorNaNs = true;
2221 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2222 bool MathErrno = TC.IsMathErrnoDefault();
2223 bool AssociativeMath = false;
2224 bool ReciprocalMath = false;
2225 bool SignedZeros = true;
2226 bool TrappingMath = true;
2227 StringRef DenormalFPMath = "";
2228 StringRef FPContract = "";
2229
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002230 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2231 CmdArgs.push_back("-mlimit-float-precision");
2232 CmdArgs.push_back(A->getValue());
2233 }
2234
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002235 for (const Arg *A : Args) {
2236 switch (A->getOption().getID()) {
2237 // If this isn't an FP option skip the claim below
2238 default: continue;
2239
2240 // Options controlling individual features
2241 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2242 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2243 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2244 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2245 case options::OPT_fmath_errno: MathErrno = true; break;
2246 case options::OPT_fno_math_errno: MathErrno = false; break;
2247 case options::OPT_fassociative_math: AssociativeMath = true; break;
2248 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2249 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2250 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2251 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2252 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2253 case options::OPT_ftrapping_math: TrappingMath = true; break;
2254 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2255
2256 case options::OPT_fdenormal_fp_math_EQ:
2257 DenormalFPMath = A->getValue();
2258 break;
2259
2260 // Validate and pass through -fp-contract option.
2261 case options::OPT_ffp_contract: {
2262 StringRef Val = A->getValue();
2263 if (Val == "fast" || Val == "on" || Val == "off")
2264 FPContract = Val;
2265 else
2266 D.Diag(diag::err_drv_unsupported_option_argument)
2267 << A->getOption().getName() << Val;
2268 break;
2269 }
2270
2271 case options::OPT_ffinite_math_only:
2272 HonorINFs = false;
2273 HonorNaNs = false;
2274 break;
2275 case options::OPT_fno_finite_math_only:
2276 HonorINFs = true;
2277 HonorNaNs = true;
2278 break;
2279
2280 case options::OPT_funsafe_math_optimizations:
2281 AssociativeMath = true;
2282 ReciprocalMath = true;
2283 SignedZeros = false;
2284 TrappingMath = false;
2285 break;
2286 case options::OPT_fno_unsafe_math_optimizations:
2287 AssociativeMath = false;
2288 ReciprocalMath = false;
2289 SignedZeros = true;
2290 TrappingMath = true;
2291 // -fno_unsafe_math_optimizations restores default denormal handling
2292 DenormalFPMath = "";
2293 break;
2294
2295 case options::OPT_Ofast:
2296 // If -Ofast is the optimization level, then -ffast-math should be enabled
2297 if (!OFastEnabled)
2298 continue;
2299 LLVM_FALLTHROUGH;
2300 case options::OPT_ffast_math:
2301 HonorINFs = false;
2302 HonorNaNs = false;
2303 MathErrno = false;
2304 AssociativeMath = true;
2305 ReciprocalMath = true;
2306 SignedZeros = false;
2307 TrappingMath = false;
2308 // If fast-math is set then set the fp-contract mode to fast.
2309 FPContract = "fast";
2310 break;
2311 case options::OPT_fno_fast_math:
2312 HonorINFs = true;
2313 HonorNaNs = true;
2314 // Turning on -ffast-math (with either flag) removes the need for
2315 // MathErrno. However, turning *off* -ffast-math merely restores the
2316 // toolchain default (which may be false).
2317 MathErrno = TC.IsMathErrnoDefault();
2318 AssociativeMath = false;
2319 ReciprocalMath = false;
2320 SignedZeros = true;
2321 TrappingMath = true;
2322 // -fno_fast_math restores default denormal and fpcontract handling
2323 DenormalFPMath = "";
2324 FPContract = "";
2325 break;
2326 }
2327
2328 // If we handled this option claim it
2329 A->claim();
2330 }
2331
2332 if (!HonorINFs)
2333 CmdArgs.push_back("-menable-no-infs");
2334
2335 if (!HonorNaNs)
2336 CmdArgs.push_back("-menable-no-nans");
2337
2338 if (MathErrno)
2339 CmdArgs.push_back("-fmath-errno");
2340
2341 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2342 !TrappingMath)
2343 CmdArgs.push_back("-menable-unsafe-fp-math");
2344
2345 if (!SignedZeros)
2346 CmdArgs.push_back("-fno-signed-zeros");
2347
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002348 if (AssociativeMath && !SignedZeros && !TrappingMath)
2349 CmdArgs.push_back("-mreassociate");
2350
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002351 if (ReciprocalMath)
2352 CmdArgs.push_back("-freciprocal-math");
2353
2354 if (!TrappingMath)
2355 CmdArgs.push_back("-fno-trapping-math");
2356
2357 if (!DenormalFPMath.empty())
2358 CmdArgs.push_back(
2359 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2360
2361 if (!FPContract.empty())
2362 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2363
2364 ParseMRecip(D, Args, CmdArgs);
2365
2366 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2367 // individual features enabled by -ffast-math instead of the option itself as
2368 // that's consistent with gcc's behaviour.
2369 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2370 ReciprocalMath && !SignedZeros && !TrappingMath)
2371 CmdArgs.push_back("-ffast-math");
2372
2373 // Handle __FINITE_MATH_ONLY__ similarly.
2374 if (!HonorINFs && !HonorNaNs)
2375 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002376
2377 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2378 CmdArgs.push_back("-mfpmath");
2379 CmdArgs.push_back(A->getValue());
2380 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002381
2382 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002383 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2384 options::OPT_fstrict_float_cast_overflow, false))
2385 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002386}
2387
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002388static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2389 const llvm::Triple &Triple,
2390 const InputInfo &Input) {
2391 // Enable region store model by default.
2392 CmdArgs.push_back("-analyzer-store=region");
2393
2394 // Treat blocks as analysis entry points.
2395 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2396
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002397 // Add default argument set.
2398 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2399 CmdArgs.push_back("-analyzer-checker=core");
2400 CmdArgs.push_back("-analyzer-checker=apiModeling");
2401
2402 if (!Triple.isWindowsMSVCEnvironment()) {
2403 CmdArgs.push_back("-analyzer-checker=unix");
2404 } else {
2405 // Enable "unix" checkers that also work on Windows.
2406 CmdArgs.push_back("-analyzer-checker=unix.API");
2407 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2408 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2409 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2410 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2411 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2412 }
2413
2414 // Disable some unix checkers for PS4.
2415 if (Triple.isPS4CPU()) {
2416 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2417 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2418 }
2419
2420 if (Triple.isOSDarwin())
2421 CmdArgs.push_back("-analyzer-checker=osx");
2422
2423 CmdArgs.push_back("-analyzer-checker=deadcode");
2424
2425 if (types::isCXX(Input.getType()))
2426 CmdArgs.push_back("-analyzer-checker=cplusplus");
2427
2428 if (!Triple.isPS4CPU()) {
2429 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2430 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2431 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2432 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2433 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2434 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2435 }
2436
2437 // Default nullability checks.
2438 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2439 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2440 }
2441
2442 // Set the output format. The default is plist, for (lame) historical reasons.
2443 CmdArgs.push_back("-analyzer-output");
2444 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2445 CmdArgs.push_back(A->getValue());
2446 else
2447 CmdArgs.push_back("plist");
2448
2449 // Disable the presentation of standard compiler warnings when using
2450 // --analyze. We only want to show static analyzer diagnostics or frontend
2451 // errors.
2452 CmdArgs.push_back("-w");
2453
2454 // Add -Xanalyzer arguments when running as analyzer.
2455 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2456}
2457
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002458static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002459 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002460 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2461
2462 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2463 // doesn't even have a stack!
2464 if (EffectiveTriple.isNVPTX())
2465 return;
2466
2467 // -stack-protector=0 is default.
2468 unsigned StackProtectorLevel = 0;
2469 unsigned DefaultStackProtectorLevel =
2470 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2471
2472 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2473 options::OPT_fstack_protector_all,
2474 options::OPT_fstack_protector_strong,
2475 options::OPT_fstack_protector)) {
2476 if (A->getOption().matches(options::OPT_fstack_protector))
2477 StackProtectorLevel =
2478 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2479 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2480 StackProtectorLevel = LangOptions::SSPStrong;
2481 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2482 StackProtectorLevel = LangOptions::SSPReq;
2483 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002484 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002485 }
2486
2487 if (StackProtectorLevel) {
2488 CmdArgs.push_back("-stack-protector");
2489 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2490 }
2491
2492 // --param ssp-buffer-size=
2493 for (const Arg *A : Args.filtered(options::OPT__param)) {
2494 StringRef Str(A->getValue());
2495 if (Str.startswith("ssp-buffer-size=")) {
2496 if (StackProtectorLevel) {
2497 CmdArgs.push_back("-stack-protector-buffer-size");
2498 // FIXME: Verify the argument is a valid integer.
2499 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2500 }
2501 A->claim();
2502 }
2503 }
2504}
2505
JF Bastien14daa202018-12-18 05:12:21 +00002506static void RenderTrivialAutoVarInitOptions(const Driver &D,
2507 const ToolChain &TC,
2508 const ArgList &Args,
2509 ArgStringList &CmdArgs) {
2510 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2511 StringRef TrivialAutoVarInit = "";
2512
2513 for (const Arg *A : Args) {
2514 switch (A->getOption().getID()) {
2515 default:
2516 continue;
2517 case options::OPT_ftrivial_auto_var_init: {
2518 A->claim();
2519 StringRef Val = A->getValue();
2520 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2521 TrivialAutoVarInit = Val;
2522 else
2523 D.Diag(diag::err_drv_unsupported_option_argument)
2524 << A->getOption().getName() << Val;
2525 break;
2526 }
2527 }
2528 }
2529
2530 if (TrivialAutoVarInit.empty())
2531 switch (DefaultTrivialAutoVarInit) {
2532 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2533 break;
2534 case LangOptions::TrivialAutoVarInitKind::Pattern:
2535 TrivialAutoVarInit = "pattern";
2536 break;
2537 case LangOptions::TrivialAutoVarInitKind::Zero:
2538 TrivialAutoVarInit = "zero";
2539 break;
2540 }
2541
2542 if (!TrivialAutoVarInit.empty()) {
2543 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2544 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2545 CmdArgs.push_back(
2546 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2547 }
2548}
2549
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002550static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2551 const unsigned ForwardedArguments[] = {
2552 options::OPT_cl_opt_disable,
2553 options::OPT_cl_strict_aliasing,
2554 options::OPT_cl_single_precision_constant,
2555 options::OPT_cl_finite_math_only,
2556 options::OPT_cl_kernel_arg_info,
2557 options::OPT_cl_unsafe_math_optimizations,
2558 options::OPT_cl_fast_relaxed_math,
2559 options::OPT_cl_mad_enable,
2560 options::OPT_cl_no_signed_zeros,
2561 options::OPT_cl_denorms_are_zero,
2562 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002563 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002564 };
2565
2566 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2567 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2568 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2569 }
2570
2571 for (const auto &Arg : ForwardedArguments)
2572 if (const auto *A = Args.getLastArg(Arg))
2573 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2574}
2575
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002576static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2577 ArgStringList &CmdArgs) {
2578 bool ARCMTEnabled = false;
2579 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2580 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2581 options::OPT_ccc_arcmt_modify,
2582 options::OPT_ccc_arcmt_migrate)) {
2583 ARCMTEnabled = true;
2584 switch (A->getOption().getID()) {
2585 default: llvm_unreachable("missed a case");
2586 case options::OPT_ccc_arcmt_check:
2587 CmdArgs.push_back("-arcmt-check");
2588 break;
2589 case options::OPT_ccc_arcmt_modify:
2590 CmdArgs.push_back("-arcmt-modify");
2591 break;
2592 case options::OPT_ccc_arcmt_migrate:
2593 CmdArgs.push_back("-arcmt-migrate");
2594 CmdArgs.push_back("-mt-migrate-directory");
2595 CmdArgs.push_back(A->getValue());
2596
2597 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2598 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2599 break;
2600 }
2601 }
2602 } else {
2603 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2604 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2605 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2606 }
2607
2608 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2609 if (ARCMTEnabled)
2610 D.Diag(diag::err_drv_argument_not_allowed_with)
2611 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2612
2613 CmdArgs.push_back("-mt-migrate-directory");
2614 CmdArgs.push_back(A->getValue());
2615
2616 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2617 options::OPT_objcmt_migrate_subscripting,
2618 options::OPT_objcmt_migrate_property)) {
2619 // None specified, means enable them all.
2620 CmdArgs.push_back("-objcmt-migrate-literals");
2621 CmdArgs.push_back("-objcmt-migrate-subscripting");
2622 CmdArgs.push_back("-objcmt-migrate-property");
2623 } else {
2624 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2625 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2626 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2627 }
2628 } else {
2629 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2630 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2631 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2632 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2633 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2634 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2635 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2636 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2637 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2638 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2639 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2640 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2641 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2642 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2643 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2644 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2645 }
2646}
2647
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002648static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2649 const ArgList &Args, ArgStringList &CmdArgs) {
2650 // -fbuiltin is default unless -mkernel is used.
2651 bool UseBuiltins =
2652 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2653 !Args.hasArg(options::OPT_mkernel));
2654 if (!UseBuiltins)
2655 CmdArgs.push_back("-fno-builtin");
2656
2657 // -ffreestanding implies -fno-builtin.
2658 if (Args.hasArg(options::OPT_ffreestanding))
2659 UseBuiltins = false;
2660
2661 // Process the -fno-builtin-* options.
2662 for (const auto &Arg : Args) {
2663 const Option &O = Arg->getOption();
2664 if (!O.matches(options::OPT_fno_builtin_))
2665 continue;
2666
2667 Arg->claim();
2668
2669 // If -fno-builtin is specified, then there's no need to pass the option to
2670 // the frontend.
2671 if (!UseBuiltins)
2672 continue;
2673
2674 StringRef FuncName = Arg->getValue();
2675 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2676 }
2677
2678 // le32-specific flags:
2679 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2680 // by default.
2681 if (TC.getArch() == llvm::Triple::le32)
2682 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002683}
2684
Adrian Prantl70599032018-02-09 18:43:10 +00002685void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2686 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2687 llvm::sys::path::append(Result, "org.llvm.clang.");
2688 appendUserToPath(Result);
2689 llvm::sys::path::append(Result, "ModuleCache");
2690}
2691
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002692static void RenderModulesOptions(Compilation &C, const Driver &D,
2693 const ArgList &Args, const InputInfo &Input,
2694 const InputInfo &Output,
2695 ArgStringList &CmdArgs, bool &HaveModules) {
2696 // -fmodules enables the use of precompiled modules (off by default).
2697 // Users can pass -fno-cxx-modules to turn off modules support for
2698 // C++/Objective-C++ programs.
2699 bool HaveClangModules = false;
2700 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2701 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2702 options::OPT_fno_cxx_modules, true);
2703 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2704 CmdArgs.push_back("-fmodules");
2705 HaveClangModules = true;
2706 }
2707 }
2708
2709 HaveModules = HaveClangModules;
2710 if (Args.hasArg(options::OPT_fmodules_ts)) {
2711 CmdArgs.push_back("-fmodules-ts");
2712 HaveModules = true;
2713 }
2714
2715 // -fmodule-maps enables implicit reading of module map files. By default,
2716 // this is enabled if we are using Clang's flavor of precompiled modules.
2717 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2718 options::OPT_fno_implicit_module_maps, HaveClangModules))
2719 CmdArgs.push_back("-fimplicit-module-maps");
2720
2721 // -fmodules-decluse checks that modules used are declared so (off by default)
2722 if (Args.hasFlag(options::OPT_fmodules_decluse,
2723 options::OPT_fno_modules_decluse, false))
2724 CmdArgs.push_back("-fmodules-decluse");
2725
2726 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2727 // all #included headers are part of modules.
2728 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2729 options::OPT_fno_modules_strict_decluse, false))
2730 CmdArgs.push_back("-fmodules-strict-decluse");
2731
2732 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002733 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002734 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2735 options::OPT_fno_implicit_modules, HaveClangModules)) {
2736 if (HaveModules)
2737 CmdArgs.push_back("-fno-implicit-modules");
2738 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002739 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002740 // -fmodule-cache-path specifies where our implicitly-built module files
2741 // should be written.
2742 SmallString<128> Path;
2743 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2744 Path = A->getValue();
2745
2746 if (C.isForDiagnostics()) {
2747 // When generating crash reports, we want to emit the modules along with
2748 // the reproduction sources, so we ignore any provided module path.
2749 Path = Output.getFilename();
2750 llvm::sys::path::replace_extension(Path, ".cache");
2751 llvm::sys::path::append(Path, "modules");
2752 } else if (Path.empty()) {
2753 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002754 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002755 }
2756
2757 const char Arg[] = "-fmodules-cache-path=";
2758 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2759 CmdArgs.push_back(Args.MakeArgString(Path));
2760 }
2761
2762 if (HaveModules) {
2763 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2764 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2765 CmdArgs.push_back(Args.MakeArgString(
2766 std::string("-fprebuilt-module-path=") + A->getValue()));
2767 A->claim();
2768 }
2769 }
2770
2771 // -fmodule-name specifies the module that is currently being built (or
2772 // used for header checking by -fmodule-maps).
2773 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2774
2775 // -fmodule-map-file can be used to specify files containing module
2776 // definitions.
2777 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2778
2779 // -fbuiltin-module-map can be used to load the clang
2780 // builtin headers modulemap file.
2781 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2782 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2783 llvm::sys::path::append(BuiltinModuleMap, "include");
2784 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2785 if (llvm::sys::fs::exists(BuiltinModuleMap))
2786 CmdArgs.push_back(
2787 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2788 }
2789
2790 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2791 // names to precompiled module files (the module is loaded only if used).
2792 // The -fmodule-file=<file> form can be used to unconditionally load
2793 // precompiled module files (whether used or not).
2794 if (HaveModules)
2795 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2796 else
2797 Args.ClaimAllArgs(options::OPT_fmodule_file);
2798
2799 // When building modules and generating crashdumps, we need to dump a module
2800 // dependency VFS alongside the output.
2801 if (HaveClangModules && C.isForDiagnostics()) {
2802 SmallString<128> VFSDir(Output.getFilename());
2803 llvm::sys::path::replace_extension(VFSDir, ".cache");
2804 // Add the cache directory as a temp so the crash diagnostics pick it up.
2805 C.addTempFile(Args.MakeArgString(VFSDir));
2806
2807 llvm::sys::path::append(VFSDir, "vfs");
2808 CmdArgs.push_back("-module-dependency-dir");
2809 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2810 }
2811
2812 if (HaveClangModules)
2813 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2814
2815 // Pass through all -fmodules-ignore-macro arguments.
2816 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2817 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2818 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2819
2820 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2821
2822 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2823 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2824 D.Diag(diag::err_drv_argument_not_allowed_with)
2825 << A->getAsString(Args) << "-fbuild-session-timestamp";
2826
2827 llvm::sys::fs::file_status Status;
2828 if (llvm::sys::fs::status(A->getValue(), Status))
2829 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2830 CmdArgs.push_back(
2831 Args.MakeArgString("-fbuild-session-timestamp=" +
2832 Twine((uint64_t)Status.getLastModificationTime()
2833 .time_since_epoch()
2834 .count())));
2835 }
2836
2837 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2838 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2839 options::OPT_fbuild_session_file))
2840 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2841
2842 Args.AddLastArg(CmdArgs,
2843 options::OPT_fmodules_validate_once_per_build_session);
2844 }
2845
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002846 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2847 options::OPT_fno_modules_validate_system_headers,
2848 ImplicitModules))
2849 CmdArgs.push_back("-fmodules-validate-system-headers");
2850
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002851 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2852}
2853
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002854static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2855 ArgStringList &CmdArgs) {
2856 // -fsigned-char is default.
2857 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2858 options::OPT_fno_signed_char,
2859 options::OPT_funsigned_char,
2860 options::OPT_fno_unsigned_char)) {
2861 if (A->getOption().matches(options::OPT_funsigned_char) ||
2862 A->getOption().matches(options::OPT_fno_signed_char)) {
2863 CmdArgs.push_back("-fno-signed-char");
2864 }
2865 } else if (!isSignedCharDefault(T)) {
2866 CmdArgs.push_back("-fno-signed-char");
2867 }
2868
Richard Smith28ddb912018-11-14 21:04:34 +00002869 // The default depends on the language standard.
2870 if (const Arg *A =
2871 Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2872 A->render(Args, CmdArgs);
Richard Smith3a8244d2018-05-01 05:02:45 +00002873
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002874 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2875 options::OPT_fno_short_wchar)) {
2876 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2877 CmdArgs.push_back("-fwchar-type=short");
2878 CmdArgs.push_back("-fno-signed-wchar");
2879 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002880 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002881 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002882 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2883 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002884 CmdArgs.push_back("-fno-signed-wchar");
2885 else
2886 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002887 }
2888 }
2889}
2890
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002891static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2892 const llvm::Triple &T, const ArgList &Args,
2893 ObjCRuntime &Runtime, bool InferCovariantReturns,
2894 const InputInfo &Input, ArgStringList &CmdArgs) {
2895 const llvm::Triple::ArchType Arch = TC.getArch();
2896
2897 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2898 // is the default. Except for deployment target of 10.5, next runtime is
2899 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2900 if (Runtime.isNonFragile()) {
2901 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2902 options::OPT_fno_objc_legacy_dispatch,
2903 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2904 if (TC.UseObjCMixedDispatch())
2905 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2906 else
2907 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2908 }
2909 }
2910
2911 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2912 // to do Array/Dictionary subscripting by default.
2913 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002914 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2915 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2916
2917 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2918 // NOTE: This logic is duplicated in ToolChains.cpp.
2919 if (isObjCAutoRefCount(Args)) {
2920 TC.CheckObjCARC();
2921
2922 CmdArgs.push_back("-fobjc-arc");
2923
2924 // FIXME: It seems like this entire block, and several around it should be
2925 // wrapped in isObjC, but for now we just use it here as this is where it
2926 // was being used previously.
2927 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2928 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2929 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2930 else
2931 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2932 }
2933
2934 // Allow the user to enable full exceptions code emission.
2935 // We default off for Objective-C, on for Objective-C++.
2936 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2937 options::OPT_fno_objc_arc_exceptions,
2938 /*default=*/types::isCXX(Input.getType())))
2939 CmdArgs.push_back("-fobjc-arc-exceptions");
2940 }
2941
2942 // Silence warning for full exception code emission options when explicitly
2943 // set to use no ARC.
2944 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2945 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2946 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2947 }
2948
Pete Coopere3886802018-12-08 05:13:50 +00002949 // Allow the user to control whether messages can be converted to runtime
2950 // functions.
2951 if (types::isObjC(Input.getType())) {
2952 auto *Arg = Args.getLastArg(
2953 options::OPT_fobjc_convert_messages_to_runtime_calls,
2954 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2955 if (Arg &&
2956 Arg->getOption().matches(
2957 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2958 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2959 }
2960
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002961 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2962 // rewriter.
2963 if (InferCovariantReturns)
2964 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2965
2966 // Pass down -fobjc-weak or -fno-objc-weak if present.
2967 if (types::isObjC(Input.getType())) {
2968 auto WeakArg =
2969 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2970 if (!WeakArg) {
2971 // nothing to do
2972 } else if (!Runtime.allowsWeak()) {
2973 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2974 D.Diag(diag::err_objc_weak_unsupported);
2975 } else {
2976 WeakArg->render(Args, CmdArgs);
2977 }
2978 }
2979}
2980
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00002981static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2982 ArgStringList &CmdArgs) {
2983 bool CaretDefault = true;
2984 bool ColumnDefault = true;
2985
2986 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2987 options::OPT__SLASH_diagnostics_column,
2988 options::OPT__SLASH_diagnostics_caret)) {
2989 switch (A->getOption().getID()) {
2990 case options::OPT__SLASH_diagnostics_caret:
2991 CaretDefault = true;
2992 ColumnDefault = true;
2993 break;
2994 case options::OPT__SLASH_diagnostics_column:
2995 CaretDefault = false;
2996 ColumnDefault = true;
2997 break;
2998 case options::OPT__SLASH_diagnostics_classic:
2999 CaretDefault = false;
3000 ColumnDefault = false;
3001 break;
3002 }
3003 }
3004
3005 // -fcaret-diagnostics is default.
3006 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3007 options::OPT_fno_caret_diagnostics, CaretDefault))
3008 CmdArgs.push_back("-fno-caret-diagnostics");
3009
3010 // -fdiagnostics-fixit-info is default, only pass non-default.
3011 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3012 options::OPT_fno_diagnostics_fixit_info))
3013 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3014
3015 // Enable -fdiagnostics-show-option by default.
3016 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3017 options::OPT_fno_diagnostics_show_option))
3018 CmdArgs.push_back("-fdiagnostics-show-option");
3019
3020 if (const Arg *A =
3021 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3022 CmdArgs.push_back("-fdiagnostics-show-category");
3023 CmdArgs.push_back(A->getValue());
3024 }
3025
3026 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3027 options::OPT_fno_diagnostics_show_hotness, false))
3028 CmdArgs.push_back("-fdiagnostics-show-hotness");
3029
3030 if (const Arg *A =
3031 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3032 std::string Opt =
3033 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3034 CmdArgs.push_back(Args.MakeArgString(Opt));
3035 }
3036
3037 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3038 CmdArgs.push_back("-fdiagnostics-format");
3039 CmdArgs.push_back(A->getValue());
3040 }
3041
3042 if (const Arg *A = Args.getLastArg(
3043 options::OPT_fdiagnostics_show_note_include_stack,
3044 options::OPT_fno_diagnostics_show_note_include_stack)) {
3045 const Option &O = A->getOption();
3046 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3047 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3048 else
3049 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3050 }
3051
3052 // Color diagnostics are parsed by the driver directly from argv and later
3053 // re-parsed to construct this job; claim any possible color diagnostic here
3054 // to avoid warn_drv_unused_argument and diagnose bad
3055 // OPT_fdiagnostics_color_EQ values.
3056 for (const Arg *A : Args) {
3057 const Option &O = A->getOption();
3058 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3059 !O.matches(options::OPT_fdiagnostics_color) &&
3060 !O.matches(options::OPT_fno_color_diagnostics) &&
3061 !O.matches(options::OPT_fno_diagnostics_color) &&
3062 !O.matches(options::OPT_fdiagnostics_color_EQ))
3063 continue;
3064
3065 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3066 StringRef Value(A->getValue());
3067 if (Value != "always" && Value != "never" && Value != "auto")
3068 D.Diag(diag::err_drv_clang_unsupported)
3069 << ("-fdiagnostics-color=" + Value).str();
3070 }
3071 A->claim();
3072 }
3073
3074 if (D.getDiags().getDiagnosticOptions().ShowColors)
3075 CmdArgs.push_back("-fcolor-diagnostics");
3076
3077 if (Args.hasArg(options::OPT_fansi_escape_codes))
3078 CmdArgs.push_back("-fansi-escape-codes");
3079
3080 if (!Args.hasFlag(options::OPT_fshow_source_location,
3081 options::OPT_fno_show_source_location))
3082 CmdArgs.push_back("-fno-show-source-location");
3083
3084 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3085 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3086
3087 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3088 ColumnDefault))
3089 CmdArgs.push_back("-fno-show-column");
3090
3091 if (!Args.hasFlag(options::OPT_fspell_checking,
3092 options::OPT_fno_spell_checking))
3093 CmdArgs.push_back("-fno-spell-checking");
3094}
3095
George Rimar91829ee2018-11-14 09:22:16 +00003096enum class DwarfFissionKind { None, Split, Single };
3097
3098static DwarfFissionKind getDebugFissionKind(const Driver &D,
3099 const ArgList &Args, Arg *&Arg) {
3100 Arg =
3101 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3102 if (!Arg)
3103 return DwarfFissionKind::None;
3104
3105 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3106 return DwarfFissionKind::Split;
3107
3108 StringRef Value = Arg->getValue();
3109 if (Value == "split")
3110 return DwarfFissionKind::Split;
3111 if (Value == "single")
3112 return DwarfFissionKind::Single;
3113
3114 D.Diag(diag::err_drv_unsupported_option_argument)
3115 << Arg->getOption().getName() << Arg->getValue();
3116 return DwarfFissionKind::None;
3117}
3118
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003119static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3120 const llvm::Triple &T, const ArgList &Args,
3121 bool EmitCodeView, bool IsWindowsMSVC,
3122 ArgStringList &CmdArgs,
3123 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003124 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003125 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003126 options::OPT_fno_debug_info_for_profiling, false) &&
3127 checkDebugInfoOption(
3128 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003129 CmdArgs.push_back("-fdebug-info-for-profiling");
3130
3131 // The 'g' groups options involve a somewhat intricate sequence of decisions
3132 // about what to pass from the driver to the frontend, but by the time they
3133 // reach cc1 they've been factored into three well-defined orthogonal choices:
3134 // * what level of debug info to generate
3135 // * what dwarf version to write
3136 // * what debugger tuning to use
3137 // This avoids having to monkey around further in cc1 other than to disable
3138 // codeview if not running in a Windows environment. Perhaps even that
3139 // decision should be made in the driver as well though.
3140 unsigned DWARFVersion = 0;
3141 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3142
3143 bool SplitDWARFInlining =
3144 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3145 options::OPT_fno_split_dwarf_inlining, true);
3146
3147 Args.ClaimAllArgs(options::OPT_g_Group);
3148
George Rimar91829ee2018-11-14 09:22:16 +00003149 Arg* SplitDWARFArg;
3150 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003151
George Rimar91829ee2018-11-14 09:22:16 +00003152 if (DwarfFission != DwarfFissionKind::None &&
3153 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3154 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003155 SplitDWARFInlining = false;
3156 }
3157
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003158 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003159 if (checkDebugInfoOption(A, Args, D, TC)) {
3160 // If the last option explicitly specified a debug-info level, use it.
3161 if (A->getOption().matches(options::OPT_gN_Group)) {
3162 DebugInfoKind = DebugLevelToInfoKind(*A);
3163 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
3164 // But -gsplit-dwarf is not a g_group option, hence we have to check the
3165 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
3166 // This gets a bit more complicated if you've disabled inline info in
3167 // the skeleton CUs (SplitDWARFInlining) - then there's value in
3168 // composing split-dwarf and line-tables-only, so let those compose
3169 // naturally in that case. And if you just turned off debug info,
3170 // (-gsplit-dwarf -g0) - do that.
George Rimar91829ee2018-11-14 09:22:16 +00003171 if (DwarfFission != DwarfFissionKind::None) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003172 if (A->getIndex() > SplitDWARFArg->getIndex()) {
3173 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003174 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003175 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3176 SplitDWARFInlining))
George Rimar91829ee2018-11-14 09:22:16 +00003177 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003178 } else if (SplitDWARFInlining)
3179 DebugInfoKind = codegenoptions::NoDebugInfo;
3180 }
3181 } else {
3182 // For any other 'g' option, use Limited.
3183 DebugInfoKind = codegenoptions::LimitedDebugInfo;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003184 }
3185 } else {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003186 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3187 }
3188 }
3189
3190 // If a debugger tuning argument appeared, remember it.
3191 if (const Arg *A =
3192 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003193 if (checkDebugInfoOption(A, Args, D, TC)) {
3194 if (A->getOption().matches(options::OPT_glldb))
3195 DebuggerTuning = llvm::DebuggerKind::LLDB;
3196 else if (A->getOption().matches(options::OPT_gsce))
3197 DebuggerTuning = llvm::DebuggerKind::SCE;
3198 else
3199 DebuggerTuning = llvm::DebuggerKind::GDB;
3200 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003201 }
3202
3203 // If a -gdwarf argument appeared, remember it.
3204 if (const Arg *A =
3205 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3206 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003207 if (checkDebugInfoOption(A, Args, D, TC))
3208 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003209
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003210 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3211 if (checkDebugInfoOption(A, Args, D, TC))
3212 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003213 }
3214
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003215 // If the user asked for debug info but did not explicitly specify -gcodeview
3216 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003217 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003218 DebugInfoKind != codegenoptions::NoDebugInfo) {
3219 switch (TC.getDefaultDebugFormat()) {
3220 case codegenoptions::DIF_CodeView:
3221 EmitCodeView = true;
3222 break;
3223 case codegenoptions::DIF_DWARF:
3224 DWARFVersion = TC.GetDefaultDwarfVersion();
3225 break;
3226 }
3227 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003228
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003229 // -gline-directives-only supported only for the DWARF debug info.
3230 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3231 DebugInfoKind = codegenoptions::NoDebugInfo;
3232
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003233 // We ignore flag -gstrict-dwarf for now.
3234 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3235 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3236
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003237 // Column info is included by default for everything except SCE and
3238 // CodeView. Clang doesn't track end columns, just starting columns, which,
3239 // in theory, is fine for CodeView (and PDB). In practice, however, the
3240 // Microsoft debuggers don't handle missing end columns well, so it's better
3241 // not to include any column info.
3242 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3243 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003244 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003245 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003246 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003247 CmdArgs.push_back("-dwarf-column-info");
3248
3249 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003250 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003251 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3252 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003253 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3254 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003255 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3256 CmdArgs.push_back("-dwarf-ext-refs");
3257 CmdArgs.push_back("-fmodule-format=obj");
3258 }
3259 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003260
3261 // -gsplit-dwarf should turn on -g and enable the backend dwarf
3262 // splitting and extraction.
Petr Hosekd3265352018-10-15 21:30:32 +00003263 // FIXME: Currently only works on Linux and Fuchsia.
3264 if (T.isOSLinux() || T.isOSFuchsia()) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003265 if (!SplitDWARFInlining)
3266 CmdArgs.push_back("-fno-split-dwarf-inlining");
3267
George Rimar91829ee2018-11-14 09:22:16 +00003268 if (DwarfFission != DwarfFissionKind::None) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003269 if (DebugInfoKind == codegenoptions::NoDebugInfo)
3270 DebugInfoKind = codegenoptions::LimitedDebugInfo;
George Rimar91829ee2018-11-14 09:22:16 +00003271
3272 if (DwarfFission == DwarfFissionKind::Single)
3273 CmdArgs.push_back("-enable-split-dwarf=single");
3274 else
3275 CmdArgs.push_back("-enable-split-dwarf");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003276 }
3277 }
3278
3279 // After we've dealt with all combinations of things that could
3280 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3281 // figure out if we need to "upgrade" it to standalone debug info.
3282 // We parse these two '-f' options whether or not they will be used,
3283 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3284 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3285 options::OPT_fno_standalone_debug,
3286 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003287 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3288 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003289 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3290 DebugInfoKind = codegenoptions::FullDebugInfo;
3291
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003292 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3293 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003294 // Source embedding is a vendor extension to DWARF v5. By now we have
3295 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003296 // fallen back to the target default, so if this is still not at least 5
3297 // we emit an error.
3298 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003299 if (DWARFVersion < 5)
3300 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003301 << A->getAsString(Args) << "-gdwarf-5";
3302 else if (checkDebugInfoOption(A, Args, D, TC))
3303 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003304 }
3305
Reid Kleckner75557712018-11-16 18:47:41 +00003306 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003307 CmdArgs.push_back("-gcodeview");
3308
Reid Kleckner75557712018-11-16 18:47:41 +00003309 // Emit codeview type hashes if requested.
3310 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3311 options::OPT_gno_codeview_ghash, false)) {
3312 CmdArgs.push_back("-gcodeview-ghash");
3313 }
3314 }
3315
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003316 // Adjust the debug info kind for the given toolchain.
3317 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3318
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003319 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3320 DebuggerTuning);
3321
3322 // -fdebug-macro turns on macro debug info generation.
3323 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3324 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003325 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3326 D, TC))
3327 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003328
3329 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003330 const auto *PubnamesArg =
3331 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3332 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003333 if (DwarfFission != DwarfFissionKind::None ||
3334 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003335 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3336 if (!PubnamesArg ||
3337 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3338 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3339 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3340 options::OPT_gpubnames)
3341 ? "-gpubnames"
3342 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003343
David Blaikie27692de2018-11-13 20:08:13 +00003344 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3345 options::OPT_fno_debug_ranges_base_address, false)) {
3346 CmdArgs.push_back("-fdebug-ranges-base-address");
3347 }
3348
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003349 // -gdwarf-aranges turns on the emission of the aranges section in the
3350 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003351 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003352 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3353 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3354 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3355 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003356 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003357 CmdArgs.push_back("-generate-arange-section");
3358 }
3359
3360 if (Args.hasFlag(options::OPT_fdebug_types_section,
3361 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003362 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003363 D.Diag(diag::err_drv_unsupported_opt_for_target)
3364 << Args.getLastArg(options::OPT_fdebug_types_section)
3365 ->getAsString(Args)
3366 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003367 } else if (checkDebugInfoOption(
3368 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3369 TC)) {
3370 CmdArgs.push_back("-mllvm");
3371 CmdArgs.push_back("-generate-type-units");
3372 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003373 }
3374
Paul Robinson1787f812017-09-28 18:37:02 +00003375 // Decide how to render forward declarations of template instantiations.
3376 // SCE wants full descriptions, others just get them in the name.
3377 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3378 CmdArgs.push_back("-debug-forward-template-params");
3379
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003380 // Do we need to explicitly import anonymous namespaces into the parent
3381 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003382 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3383 CmdArgs.push_back("-dwarf-explicit-import");
3384
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003385 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003386}
3387
David L. Jonesf561aba2017-03-08 01:02:16 +00003388void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3389 const InputInfo &Output, const InputInfoList &Inputs,
3390 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003391 const auto &TC = getToolChain();
3392 const llvm::Triple &RawTriple = TC.getTriple();
3393 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003394 const std::string &TripleStr = Triple.getTriple();
3395
3396 bool KernelOrKext =
3397 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003398 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003399 ArgStringList CmdArgs;
3400
3401 // Check number of inputs for sanity. We need at least one input.
3402 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003403 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003404 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003405 // second input. Module precompilation accepts a list of header files to
3406 // include as part of the module. All other jobs are expected to have exactly
3407 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003408 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003409 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003410 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003411 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3412
3413 // A header module compilation doesn't have a main input file, so invent a
3414 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003415 const char *ModuleName = [&]{
3416 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3417 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3418 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003419 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003420
3421 const InputInfo &Input =
3422 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3423
3424 InputInfoList ModuleHeaderInputs;
3425 const InputInfo *CudaDeviceInput = nullptr;
3426 const InputInfo *OpenMPDeviceInput = nullptr;
3427 for (const InputInfo &I : Inputs) {
3428 if (&I == &Input) {
3429 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003430 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003431 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003432 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003433 if (I.getType() != Expected) {
3434 D.Diag(diag::err_drv_module_header_wrong_kind)
3435 << I.getFilename() << types::getTypeName(I.getType())
3436 << types::getTypeName(Expected);
3437 }
3438 ModuleHeaderInputs.push_back(I);
3439 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3440 CudaDeviceInput = &I;
3441 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3442 OpenMPDeviceInput = &I;
3443 } else {
3444 llvm_unreachable("unexpectedly given multiple inputs");
3445 }
3446 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003447
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003448 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003449 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3450 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3451 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003452 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003453
Yaxun Liu398612b2018-05-08 21:02:12 +00003454 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3455 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3456 // Windows), we need to pass Windows-specific flags to cc1.
3457 if (IsCuda || IsHIP) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003458 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3459 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3460 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3461 }
3462
3463 // C++ is not supported for IAMCU.
3464 if (IsIAMCU && types::isCXX(Input.getType()))
3465 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3466
3467 // Invoke ourselves in -cc1 mode.
3468 //
3469 // FIXME: Implement custom jobs for internal actions.
3470 CmdArgs.push_back("-cc1");
3471
3472 // Add the "effective" target triple.
3473 CmdArgs.push_back("-triple");
3474 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3475
3476 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3477 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3478 Args.ClaimAllArgs(options::OPT_MJ);
3479 }
3480
Yaxun Liu398612b2018-05-08 21:02:12 +00003481 if (IsCuda || IsHIP) {
3482 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3483 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003484 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003485 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3486 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003487 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3488 ->getTriple()
3489 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003490 else {
3491 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003492 NormalizedTriple =
3493 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3494 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3495 ->getTriple()
3496 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003497 if (IsCuda) {
3498 // We need to figure out which CUDA version we're compiling for, as that
3499 // determines how we load and launch GPU kernels.
3500 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3501 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3502 assert(CTC && "Expected valid CUDA Toolchain.");
3503 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3504 CmdArgs.push_back(Args.MakeArgString(
3505 Twine("-target-sdk-version=") +
3506 CudaVersionToString(CTC->CudaInstallation.version())));
3507 }
3508 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003509 CmdArgs.push_back("-aux-triple");
3510 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3511 }
3512
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003513 if (IsOpenMPDevice) {
3514 // We have to pass the triple of the host if compiling for an OpenMP device.
3515 std::string NormalizedTriple =
3516 C.getSingleOffloadToolChain<Action::OFK_Host>()
3517 ->getTriple()
3518 .normalize();
3519 CmdArgs.push_back("-aux-triple");
3520 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3521 }
3522
David L. Jonesf561aba2017-03-08 01:02:16 +00003523 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3524 Triple.getArch() == llvm::Triple::thumb)) {
3525 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3526 unsigned Version;
3527 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3528 if (Version < 7)
3529 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3530 << TripleStr;
3531 }
3532
3533 // Push all default warning arguments that are specific to
3534 // the given target. These come before user provided warning options
3535 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003536 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003537
3538 // Select the appropriate action.
3539 RewriteKind rewriteKind = RK_None;
3540
3541 if (isa<AnalyzeJobAction>(JA)) {
3542 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3543 CmdArgs.push_back("-analyze");
3544 } else if (isa<MigrateJobAction>(JA)) {
3545 CmdArgs.push_back("-migrate");
3546 } else if (isa<PreprocessJobAction>(JA)) {
3547 if (Output.getType() == types::TY_Dependencies)
3548 CmdArgs.push_back("-Eonly");
3549 else {
3550 CmdArgs.push_back("-E");
3551 if (Args.hasArg(options::OPT_rewrite_objc) &&
3552 !Args.hasArg(options::OPT_g_Group))
3553 CmdArgs.push_back("-P");
3554 }
3555 } else if (isa<AssembleJobAction>(JA)) {
3556 CmdArgs.push_back("-emit-obj");
3557
3558 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3559
3560 // Also ignore explicit -force_cpusubtype_ALL option.
3561 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3562 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003563 if (JA.getType() == types::TY_Nothing)
3564 CmdArgs.push_back("-fsyntax-only");
3565 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003566 CmdArgs.push_back(IsHeaderModulePrecompile
3567 ? "-emit-header-module"
3568 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003569 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003570 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003571 } else if (isa<VerifyPCHJobAction>(JA)) {
3572 CmdArgs.push_back("-verify-pch");
3573 } else {
3574 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3575 "Invalid action for clang tool.");
3576 if (JA.getType() == types::TY_Nothing) {
3577 CmdArgs.push_back("-fsyntax-only");
3578 } else if (JA.getType() == types::TY_LLVM_IR ||
3579 JA.getType() == types::TY_LTO_IR) {
3580 CmdArgs.push_back("-emit-llvm");
3581 } else if (JA.getType() == types::TY_LLVM_BC ||
3582 JA.getType() == types::TY_LTO_BC) {
3583 CmdArgs.push_back("-emit-llvm-bc");
3584 } else if (JA.getType() == types::TY_PP_Asm) {
3585 CmdArgs.push_back("-S");
3586 } else if (JA.getType() == types::TY_AST) {
3587 CmdArgs.push_back("-emit-pch");
3588 } else if (JA.getType() == types::TY_ModuleFile) {
3589 CmdArgs.push_back("-module-file-info");
3590 } else if (JA.getType() == types::TY_RewrittenObjC) {
3591 CmdArgs.push_back("-rewrite-objc");
3592 rewriteKind = RK_NonFragile;
3593 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3594 CmdArgs.push_back("-rewrite-objc");
3595 rewriteKind = RK_Fragile;
3596 } else {
3597 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3598 }
3599
3600 // Preserve use-list order by default when emitting bitcode, so that
3601 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3602 // same result as running passes here. For LTO, we don't need to preserve
3603 // the use-list order, since serialization to bitcode is part of the flow.
3604 if (JA.getType() == types::TY_LLVM_BC)
3605 CmdArgs.push_back("-emit-llvm-uselists");
3606
Artem Belevichecb178b2018-03-21 22:22:59 +00003607 // Device-side jobs do not support LTO.
3608 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3609 JA.isDeviceOffloading(Action::OFK_Host));
3610
3611 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003612 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3613
Paul Robinsond23f2a82017-07-13 21:25:47 +00003614 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3615 // does not support LTO unit features (CFI, whole program vtable opt)
3616 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003617 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003618 D.getLTOMode() == LTOK_Full)
3619 CmdArgs.push_back("-flto-unit");
3620 }
3621 }
3622
3623 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3624 if (!types::isLLVMIR(Input.getType()))
3625 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3626 << "-x ir";
3627 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3628 }
3629
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003630 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003631 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3632
David L. Jonesf561aba2017-03-08 01:02:16 +00003633 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003634 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003635 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3636 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3637 // Add flags implied by -fembed-bitcode.
3638 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3639 // Disable all llvm IR level optimizations.
3640 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003641
3642 // reject options that shouldn't be supported in bitcode
3643 // also reject kernel/kext
3644 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3645 options::OPT_mkernel,
3646 options::OPT_fapple_kext,
3647 options::OPT_ffunction_sections,
3648 options::OPT_fno_function_sections,
3649 options::OPT_fdata_sections,
3650 options::OPT_fno_data_sections,
3651 options::OPT_funique_section_names,
3652 options::OPT_fno_unique_section_names,
3653 options::OPT_mrestrict_it,
3654 options::OPT_mno_restrict_it,
3655 options::OPT_mstackrealign,
3656 options::OPT_mno_stackrealign,
3657 options::OPT_mstack_alignment,
3658 options::OPT_mcmodel_EQ,
3659 options::OPT_mlong_calls,
3660 options::OPT_mno_long_calls,
3661 options::OPT_ggnu_pubnames,
3662 options::OPT_gdwarf_aranges,
3663 options::OPT_fdebug_types_section,
3664 options::OPT_fno_debug_types_section,
3665 options::OPT_fdwarf_directory_asm,
3666 options::OPT_fno_dwarf_directory_asm,
3667 options::OPT_mrelax_all,
3668 options::OPT_mno_relax_all,
3669 options::OPT_ftrap_function_EQ,
3670 options::OPT_ffixed_r9,
3671 options::OPT_mfix_cortex_a53_835769,
3672 options::OPT_mno_fix_cortex_a53_835769,
3673 options::OPT_ffixed_x18,
3674 options::OPT_mglobal_merge,
3675 options::OPT_mno_global_merge,
3676 options::OPT_mred_zone,
3677 options::OPT_mno_red_zone,
3678 options::OPT_Wa_COMMA,
3679 options::OPT_Xassembler,
3680 options::OPT_mllvm,
3681 };
3682 for (const auto &A : Args)
3683 if (std::find(std::begin(kBitcodeOptionBlacklist),
3684 std::end(kBitcodeOptionBlacklist),
3685 A->getOption().getID()) !=
3686 std::end(kBitcodeOptionBlacklist))
3687 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3688
3689 // Render the CodeGen options that need to be passed.
3690 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3691 options::OPT_fno_optimize_sibling_calls))
3692 CmdArgs.push_back("-mdisable-tail-calls");
3693
3694 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3695 CmdArgs);
3696
3697 // Render ABI arguments
3698 switch (TC.getArch()) {
3699 default: break;
3700 case llvm::Triple::arm:
3701 case llvm::Triple::armeb:
3702 case llvm::Triple::thumbeb:
3703 RenderARMABI(Triple, Args, CmdArgs);
3704 break;
3705 case llvm::Triple::aarch64:
3706 case llvm::Triple::aarch64_be:
3707 RenderAArch64ABI(Triple, Args, CmdArgs);
3708 break;
3709 }
3710
3711 // Optimization level for CodeGen.
3712 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3713 if (A->getOption().matches(options::OPT_O4)) {
3714 CmdArgs.push_back("-O3");
3715 D.Diag(diag::warn_O4_is_O3);
3716 } else {
3717 A->render(Args, CmdArgs);
3718 }
3719 }
3720
3721 // Input/Output file.
3722 if (Output.getType() == types::TY_Dependencies) {
3723 // Handled with other dependency code.
3724 } else if (Output.isFilename()) {
3725 CmdArgs.push_back("-o");
3726 CmdArgs.push_back(Output.getFilename());
3727 } else {
3728 assert(Output.isNothing() && "Input output.");
3729 }
3730
3731 for (const auto &II : Inputs) {
3732 addDashXForInput(Args, II, CmdArgs);
3733 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003734 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003735 else
3736 II.getInputArg().renderAsInput(Args, CmdArgs);
3737 }
3738
3739 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3740 CmdArgs, Inputs));
3741 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003742 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003743
David L. Jonesf561aba2017-03-08 01:02:16 +00003744 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3745 CmdArgs.push_back("-fembed-bitcode=marker");
3746
3747 // We normally speed up the clang process a bit by skipping destructors at
3748 // exit, but when we're generating diagnostics we can rely on some of the
3749 // cleanup.
3750 if (!C.isForDiagnostics())
3751 CmdArgs.push_back("-disable-free");
3752
David L. Jonesf561aba2017-03-08 01:02:16 +00003753#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003754 const bool IsAssertBuild = false;
3755#else
3756 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003757#endif
3758
Eric Fiselier123c7492018-02-07 18:36:51 +00003759 // Disable the verification pass in -asserts builds.
3760 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003761 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003762
3763 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003764 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3765 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003766 CmdArgs.push_back("-discard-value-names");
3767
David L. Jonesf561aba2017-03-08 01:02:16 +00003768 // Set the main file name, so that debug info works even with
3769 // -save-temps.
3770 CmdArgs.push_back("-main-file-name");
3771 CmdArgs.push_back(getBaseInputName(Args, Input));
3772
3773 // Some flags which affect the language (via preprocessor
3774 // defines).
3775 if (Args.hasArg(options::OPT_static))
3776 CmdArgs.push_back("-static-define");
3777
Martin Storsjo434ef832018-08-06 19:48:44 +00003778 if (Args.hasArg(options::OPT_municode))
3779 CmdArgs.push_back("-DUNICODE");
3780
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003781 if (isa<AnalyzeJobAction>(JA))
3782 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003783
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003784 // Enable compatilibily mode to avoid analyzer-config related errors.
3785 // Since we can't access frontend flags through hasArg, let's manually iterate
3786 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003787 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003788 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003789 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3790 FoundAnalyzerConfig = true;
3791 break;
3792 }
3793 if (!FoundAnalyzerConfig)
3794 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3795 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3796 FoundAnalyzerConfig = true;
3797 break;
3798 }
3799 if (FoundAnalyzerConfig)
3800 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003801
David L. Jonesf561aba2017-03-08 01:02:16 +00003802 CheckCodeGenerationOptions(D, Args);
3803
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003804 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003805 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3806 if (FunctionAlignment) {
3807 CmdArgs.push_back("-function-alignment");
3808 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3809 }
3810
David L. Jonesf561aba2017-03-08 01:02:16 +00003811 llvm::Reloc::Model RelocationModel;
3812 unsigned PICLevel;
3813 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003814 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003815
3816 const char *RMName = RelocationModelName(RelocationModel);
3817
3818 if ((RelocationModel == llvm::Reloc::ROPI ||
3819 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3820 types::isCXX(Input.getType()) &&
3821 !Args.hasArg(options::OPT_fallow_unsupported))
3822 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3823
3824 if (RMName) {
3825 CmdArgs.push_back("-mrelocation-model");
3826 CmdArgs.push_back(RMName);
3827 }
3828 if (PICLevel > 0) {
3829 CmdArgs.push_back("-pic-level");
3830 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3831 if (IsPIE)
3832 CmdArgs.push_back("-pic-is-pie");
3833 }
3834
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003835 if (RelocationModel == llvm::Reloc::ROPI ||
3836 RelocationModel == llvm::Reloc::ROPI_RWPI)
3837 CmdArgs.push_back("-fropi");
3838 if (RelocationModel == llvm::Reloc::RWPI ||
3839 RelocationModel == llvm::Reloc::ROPI_RWPI)
3840 CmdArgs.push_back("-frwpi");
3841
David L. Jonesf561aba2017-03-08 01:02:16 +00003842 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3843 CmdArgs.push_back("-meabi");
3844 CmdArgs.push_back(A->getValue());
3845 }
3846
3847 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003848 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003849 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003850 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3851 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003852 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003853 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003854 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003855 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003856
3857 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3858
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003859 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3860 options::OPT_fno_merge_all_constants, false))
3861 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003862
Manoj Guptada08f6a2018-07-19 00:44:52 +00003863 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3864 options::OPT_fdelete_null_pointer_checks, false))
3865 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3866
David L. Jonesf561aba2017-03-08 01:02:16 +00003867 // LLVM Code Generator Options.
3868
3869 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3870 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3871 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3872 options::OPT_frewrite_map_file_EQ)) {
3873 StringRef Map = A->getValue();
3874 if (!llvm::sys::fs::exists(Map)) {
3875 D.Diag(diag::err_drv_no_such_file) << Map;
3876 } else {
3877 CmdArgs.push_back("-frewrite-map-file");
3878 CmdArgs.push_back(A->getValue());
3879 A->claim();
3880 }
3881 }
3882 }
3883
3884 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3885 StringRef v = A->getValue();
3886 CmdArgs.push_back("-mllvm");
3887 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3888 A->claim();
3889 }
3890
3891 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3892 true))
3893 CmdArgs.push_back("-fno-jump-tables");
3894
Dehao Chen5e97f232017-08-24 21:37:33 +00003895 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3896 options::OPT_fno_profile_sample_accurate, false))
3897 CmdArgs.push_back("-fprofile-sample-accurate");
3898
David L. Jonesf561aba2017-03-08 01:02:16 +00003899 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3900 options::OPT_fno_preserve_as_comments, true))
3901 CmdArgs.push_back("-fno-preserve-as-comments");
3902
3903 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3904 CmdArgs.push_back("-mregparm");
3905 CmdArgs.push_back(A->getValue());
3906 }
3907
3908 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3909 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003910 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003911 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003912 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003913 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3914 CmdArgs.push_back("-fpcc-struct-return");
3915 } else {
3916 assert(A->getOption().matches(options::OPT_freg_struct_return));
3917 CmdArgs.push_back("-freg-struct-return");
3918 }
3919 }
3920
3921 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3922 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3923
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003924 if (shouldUseFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00003925 CmdArgs.push_back("-mdisable-fp-elim");
3926 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3927 options::OPT_fno_zero_initialized_in_bss))
3928 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3929
3930 bool OFastEnabled = isOptimizationLevelFast(Args);
3931 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3932 // enabled. This alias option is being used to simplify the hasFlag logic.
3933 OptSpecifier StrictAliasingAliasOption =
3934 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3935 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3936 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003937 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003938 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3939 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3940 CmdArgs.push_back("-relaxed-aliasing");
3941 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3942 options::OPT_fno_struct_path_tbaa))
3943 CmdArgs.push_back("-no-struct-path-tbaa");
3944 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3945 false))
3946 CmdArgs.push_back("-fstrict-enums");
3947 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3948 true))
3949 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003950 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3951 options::OPT_fno_allow_editor_placeholders, false))
3952 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003953 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3954 options::OPT_fno_strict_vtable_pointers,
3955 false))
3956 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003957 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3958 options::OPT_fno_force_emit_vtables,
3959 false))
3960 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00003961 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3962 options::OPT_fno_optimize_sibling_calls))
3963 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00003964 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00003965 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00003966 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00003967
Wei Mi9b3d6272017-10-16 16:50:27 +00003968 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3969 options::OPT_fno_fine_grained_bitfield_accesses);
3970
David L. Jonesf561aba2017-03-08 01:02:16 +00003971 // Handle segmented stacks.
3972 if (Args.hasArg(options::OPT_fsplit_stack))
3973 CmdArgs.push_back("-split-stacks");
3974
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003975 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003976
3977 // Decide whether to use verbose asm. Verbose assembly is the default on
3978 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003979 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00003980 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3981 IsIntegratedAssemblerDefault) ||
3982 Args.hasArg(options::OPT_dA))
3983 CmdArgs.push_back("-masm-verbose");
3984
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003985 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00003986 CmdArgs.push_back("-no-integrated-as");
3987
3988 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3989 CmdArgs.push_back("-mdebug-pass");
3990 CmdArgs.push_back("Structure");
3991 }
3992 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3993 CmdArgs.push_back("-mdebug-pass");
3994 CmdArgs.push_back("Arguments");
3995 }
3996
3997 // Enable -mconstructor-aliases except on darwin, where we have to work around
3998 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
3999 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004000 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004001 CmdArgs.push_back("-mconstructor-aliases");
4002
4003 // Darwin's kernel doesn't support guard variables; just die if we
4004 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004005 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004006 CmdArgs.push_back("-fforbid-guard-variables");
4007
4008 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4009 false)) {
4010 CmdArgs.push_back("-mms-bitfields");
4011 }
4012
4013 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4014 options::OPT_mno_pie_copy_relocations,
4015 false)) {
4016 CmdArgs.push_back("-mpie-copy-relocations");
4017 }
4018
Sriraman Tallam5c651482017-11-07 19:37:51 +00004019 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4020 CmdArgs.push_back("-fno-plt");
4021 }
4022
Vedant Kumardf502592017-09-12 22:51:53 +00004023 // -fhosted is default.
4024 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4025 // use Freestanding.
4026 bool Freestanding =
4027 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4028 KernelOrKext;
4029 if (Freestanding)
4030 CmdArgs.push_back("-ffreestanding");
4031
David L. Jonesf561aba2017-03-08 01:02:16 +00004032 // This is a coarse approximation of what llvm-gcc actually does, both
4033 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4034 // complicated ways.
4035 bool AsynchronousUnwindTables =
4036 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4037 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004038 (TC.IsUnwindTablesDefault(Args) ||
4039 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004040 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004041 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4042 AsynchronousUnwindTables))
4043 CmdArgs.push_back("-munwind-tables");
4044
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004045 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004046
David L. Jonesf561aba2017-03-08 01:02:16 +00004047 // FIXME: Handle -mtune=.
4048 (void)Args.hasArg(options::OPT_mtune_EQ);
4049
4050 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4051 CmdArgs.push_back("-mcode-model");
4052 CmdArgs.push_back(A->getValue());
4053 }
4054
4055 // Add the target cpu
4056 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4057 if (!CPU.empty()) {
4058 CmdArgs.push_back("-target-cpu");
4059 CmdArgs.push_back(Args.MakeArgString(CPU));
4060 }
4061
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004062 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004063
David L. Jonesf561aba2017-03-08 01:02:16 +00004064 // These two are potentially updated by AddClangCLArgs.
4065 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4066 bool EmitCodeView = false;
4067
4068 // Add clang-cl arguments.
4069 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004070 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004071 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4072
George Rimar91829ee2018-11-14 09:22:16 +00004073 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004074 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004075 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004076
4077 // Add the split debug info name to the command lines here so we
4078 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004079 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Petr Hosekd3265352018-10-15 21:30:32 +00004080 (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004081 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4082 isa<BackendJobAction>(JA));
4083 const char *SplitDWARFOut;
4084 if (SplitDWARF) {
4085 CmdArgs.push_back("-split-dwarf-file");
George Rimarab090332018-12-05 11:09:10 +00004086 SplitDWARFOut = SplitDebugName(Args, Output);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004087 CmdArgs.push_back(SplitDWARFOut);
4088 }
4089
David L. Jonesf561aba2017-03-08 01:02:16 +00004090 // Pass the linker version in use.
4091 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4092 CmdArgs.push_back("-target-linker-version");
4093 CmdArgs.push_back(A->getValue());
4094 }
4095
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004096 if (!shouldUseLeafFramePointer(Args, RawTriple))
David L. Jonesf561aba2017-03-08 01:02:16 +00004097 CmdArgs.push_back("-momit-leaf-frame-pointer");
4098
4099 // Explicitly error on some things we know we don't support and can't just
4100 // ignore.
4101 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4102 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004103 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004104 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004105 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4106 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4107 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4108 << Unsupported->getOption().getName();
4109 }
Eric Christopher758aad72017-03-21 22:06:18 +00004110 // The faltivec option has been superseded by the maltivec option.
4111 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4112 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4113 << Unsupported->getOption().getName()
4114 << "please use -maltivec and include altivec.h explicitly";
4115 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4116 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4117 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004118 }
4119
4120 Args.AddAllArgs(CmdArgs, options::OPT_v);
4121 Args.AddLastArg(CmdArgs, options::OPT_H);
4122 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4123 CmdArgs.push_back("-header-include-file");
4124 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4125 : "-");
4126 }
4127 Args.AddLastArg(CmdArgs, options::OPT_P);
4128 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4129
4130 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4131 CmdArgs.push_back("-diagnostic-log-file");
4132 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4133 : "-");
4134 }
4135
David L. Jonesf561aba2017-03-08 01:02:16 +00004136 bool UseSeparateSections = isUseSeparateSections(Triple);
4137
4138 if (Args.hasFlag(options::OPT_ffunction_sections,
4139 options::OPT_fno_function_sections, UseSeparateSections)) {
4140 CmdArgs.push_back("-ffunction-sections");
4141 }
4142
4143 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4144 UseSeparateSections)) {
4145 CmdArgs.push_back("-fdata-sections");
4146 }
4147
4148 if (!Args.hasFlag(options::OPT_funique_section_names,
4149 options::OPT_fno_unique_section_names, true))
4150 CmdArgs.push_back("-fno-unique-section-names");
4151
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00004152 if (auto *A = Args.getLastArg(
4153 options::OPT_finstrument_functions,
4154 options::OPT_finstrument_functions_after_inlining,
4155 options::OPT_finstrument_function_entry_bare))
4156 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004157
Artem Belevichc30bcad2018-01-24 17:41:02 +00004158 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4159 // sampling, overhead of call arc collection is way too high and there's no
4160 // way to collect the output.
4161 if (!Triple.isNVPTX())
4162 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004163
Richard Smithf667ad52017-08-26 01:04:35 +00004164 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4165 ABICompatArg->render(Args, CmdArgs);
4166
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004167 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004168 if (RawTriple.isPS4CPU() &&
4169 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004170 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4171 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004172 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004173
4174 // Pass options for controlling the default header search paths.
4175 if (Args.hasArg(options::OPT_nostdinc)) {
4176 CmdArgs.push_back("-nostdsysteminc");
4177 CmdArgs.push_back("-nobuiltininc");
4178 } else {
4179 if (Args.hasArg(options::OPT_nostdlibinc))
4180 CmdArgs.push_back("-nostdsysteminc");
4181 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4182 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4183 }
4184
4185 // Pass the path to compiler resource files.
4186 CmdArgs.push_back("-resource-dir");
4187 CmdArgs.push_back(D.ResourceDir.c_str());
4188
4189 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4190
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004191 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004192
4193 // Add preprocessing options like -I, -D, etc. if we are using the
4194 // preprocessor.
4195 //
4196 // FIXME: Support -fpreprocessed
4197 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4198 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4199
4200 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4201 // that "The compiler can only warn and ignore the option if not recognized".
4202 // When building with ccache, it will pass -D options to clang even on
4203 // preprocessed inputs and configure concludes that -fPIC is not supported.
4204 Args.ClaimAllArgs(options::OPT_D);
4205
4206 // Manually translate -O4 to -O3; let clang reject others.
4207 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4208 if (A->getOption().matches(options::OPT_O4)) {
4209 CmdArgs.push_back("-O3");
4210 D.Diag(diag::warn_O4_is_O3);
4211 } else {
4212 A->render(Args, CmdArgs);
4213 }
4214 }
4215
4216 // Warn about ignored options to clang.
4217 for (const Arg *A :
4218 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4219 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4220 A->claim();
4221 }
4222
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004223 for (const Arg *A :
4224 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4225 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4226 A->claim();
4227 }
4228
David L. Jonesf561aba2017-03-08 01:02:16 +00004229 claimNoWarnArgs(Args);
4230
4231 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4232
4233 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4234 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4235 CmdArgs.push_back("-pedantic");
4236 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4237 Args.AddLastArg(CmdArgs, options::OPT_w);
4238
Leonard Chanf921d852018-06-04 16:07:52 +00004239 // Fixed point flags
4240 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4241 /*Default=*/false))
4242 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4243
David L. Jonesf561aba2017-03-08 01:02:16 +00004244 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4245 // (-ansi is equivalent to -std=c89 or -std=c++98).
4246 //
4247 // If a std is supplied, only add -trigraphs if it follows the
4248 // option.
4249 bool ImplyVCPPCXXVer = false;
4250 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4251 if (Std->getOption().matches(options::OPT_ansi))
4252 if (types::isCXX(InputType))
4253 CmdArgs.push_back("-std=c++98");
4254 else
4255 CmdArgs.push_back("-std=c89");
4256 else
4257 Std->render(Args, CmdArgs);
4258
4259 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4260 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4261 options::OPT_ftrigraphs,
4262 options::OPT_fno_trigraphs))
4263 if (A != Std)
4264 A->render(Args, CmdArgs);
4265 } else {
4266 // Honor -std-default.
4267 //
4268 // FIXME: Clang doesn't correctly handle -std= when the input language
4269 // doesn't match. For the time being just ignore this for C++ inputs;
4270 // eventually we want to do all the standard defaulting here instead of
4271 // splitting it between the driver and clang -cc1.
4272 if (!types::isCXX(InputType))
4273 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4274 /*Joined=*/true);
4275 else if (IsWindowsMSVC)
4276 ImplyVCPPCXXVer = true;
4277
4278 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4279 options::OPT_fno_trigraphs);
4280 }
4281
4282 // GCC's behavior for -Wwrite-strings is a bit strange:
4283 // * In C, this "warning flag" changes the types of string literals from
4284 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4285 // for the discarded qualifier.
4286 // * In C++, this is just a normal warning flag.
4287 //
4288 // Implementing this warning correctly in C is hard, so we follow GCC's
4289 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4290 // a non-const char* in C, rather than using this crude hack.
4291 if (!types::isCXX(InputType)) {
4292 // FIXME: This should behave just like a warning flag, and thus should also
4293 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4294 Arg *WriteStrings =
4295 Args.getLastArg(options::OPT_Wwrite_strings,
4296 options::OPT_Wno_write_strings, options::OPT_w);
4297 if (WriteStrings &&
4298 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4299 CmdArgs.push_back("-fconst-strings");
4300 }
4301
4302 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4303 // during C++ compilation, which it is by default. GCC keeps this define even
4304 // in the presence of '-w', match this behavior bug-for-bug.
4305 if (types::isCXX(InputType) &&
4306 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4307 true)) {
4308 CmdArgs.push_back("-fdeprecated-macro");
4309 }
4310
4311 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4312 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4313 if (Asm->getOption().matches(options::OPT_fasm))
4314 CmdArgs.push_back("-fgnu-keywords");
4315 else
4316 CmdArgs.push_back("-fno-gnu-keywords");
4317 }
4318
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004319 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004320 CmdArgs.push_back("-fno-dwarf-directory-asm");
4321
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004322 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004323 CmdArgs.push_back("-fno-autolink");
4324
4325 // Add in -fdebug-compilation-dir if necessary.
4326 addDebugCompDirArg(Args, CmdArgs);
4327
Paul Robinson9b292b42018-07-10 15:15:24 +00004328 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004329
4330 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4331 options::OPT_ftemplate_depth_EQ)) {
4332 CmdArgs.push_back("-ftemplate-depth");
4333 CmdArgs.push_back(A->getValue());
4334 }
4335
4336 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4337 CmdArgs.push_back("-foperator-arrow-depth");
4338 CmdArgs.push_back(A->getValue());
4339 }
4340
4341 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4342 CmdArgs.push_back("-fconstexpr-depth");
4343 CmdArgs.push_back(A->getValue());
4344 }
4345
4346 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4347 CmdArgs.push_back("-fconstexpr-steps");
4348 CmdArgs.push_back(A->getValue());
4349 }
4350
4351 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4352 CmdArgs.push_back("-fbracket-depth");
4353 CmdArgs.push_back(A->getValue());
4354 }
4355
4356 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4357 options::OPT_Wlarge_by_value_copy_def)) {
4358 if (A->getNumValues()) {
4359 StringRef bytes = A->getValue();
4360 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4361 } else
4362 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4363 }
4364
4365 if (Args.hasArg(options::OPT_relocatable_pch))
4366 CmdArgs.push_back("-relocatable-pch");
4367
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004368 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4369 static const char *kCFABIs[] = {
4370 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4371 };
4372
4373 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4374 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4375 else
4376 A->render(Args, CmdArgs);
4377 }
4378
David L. Jonesf561aba2017-03-08 01:02:16 +00004379 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4380 CmdArgs.push_back("-fconstant-string-class");
4381 CmdArgs.push_back(A->getValue());
4382 }
4383
4384 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4385 CmdArgs.push_back("-ftabstop");
4386 CmdArgs.push_back(A->getValue());
4387 }
4388
Sean Eveson5110d4f2018-01-08 13:42:26 +00004389 if (Args.hasFlag(options::OPT_fstack_size_section,
4390 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4391 CmdArgs.push_back("-fstack-size-section");
4392
David L. Jonesf561aba2017-03-08 01:02:16 +00004393 CmdArgs.push_back("-ferror-limit");
4394 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4395 CmdArgs.push_back(A->getValue());
4396 else
4397 CmdArgs.push_back("19");
4398
4399 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4400 CmdArgs.push_back("-fmacro-backtrace-limit");
4401 CmdArgs.push_back(A->getValue());
4402 }
4403
4404 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4405 CmdArgs.push_back("-ftemplate-backtrace-limit");
4406 CmdArgs.push_back(A->getValue());
4407 }
4408
4409 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4410 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4411 CmdArgs.push_back(A->getValue());
4412 }
4413
4414 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4415 CmdArgs.push_back("-fspell-checking-limit");
4416 CmdArgs.push_back(A->getValue());
4417 }
4418
4419 // Pass -fmessage-length=.
4420 CmdArgs.push_back("-fmessage-length");
4421 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4422 CmdArgs.push_back(A->getValue());
4423 } else {
4424 // If -fmessage-length=N was not specified, determine whether this is a
4425 // terminal and, if so, implicitly define -fmessage-length appropriately.
4426 unsigned N = llvm::sys::Process::StandardErrColumns();
4427 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4428 }
4429
4430 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4431 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4432 options::OPT_fvisibility_ms_compat)) {
4433 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4434 CmdArgs.push_back("-fvisibility");
4435 CmdArgs.push_back(A->getValue());
4436 } else {
4437 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4438 CmdArgs.push_back("-fvisibility");
4439 CmdArgs.push_back("hidden");
4440 CmdArgs.push_back("-ftype-visibility");
4441 CmdArgs.push_back("default");
4442 }
4443 }
4444
4445 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004446 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004447
4448 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4449
David L. Jonesf561aba2017-03-08 01:02:16 +00004450 // Forward -f (flag) options which we can pass directly.
4451 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4452 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004453 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004454 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004455 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4456 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004457 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004458
David L. Jonesf561aba2017-03-08 01:02:16 +00004459 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004460 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004461 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004462
David L. Jonesf561aba2017-03-08 01:02:16 +00004463 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4464 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4465
4466 // Forward flags for OpenMP. We don't do this if the current action is an
4467 // device offloading action other than OpenMP.
4468 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4469 options::OPT_fno_openmp, false) &&
4470 (JA.isDeviceOffloading(Action::OFK_None) ||
4471 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004472 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004473 case Driver::OMPRT_OMP:
4474 case Driver::OMPRT_IOMP5:
4475 // Clang can generate useful OpenMP code for these two runtime libraries.
4476 CmdArgs.push_back("-fopenmp");
4477
4478 // If no option regarding the use of TLS in OpenMP codegeneration is
4479 // given, decide a default based on the target. Otherwise rely on the
4480 // options and pass the right information to the frontend.
4481 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4482 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4483 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004484 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4485 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004486 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004487 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4488 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004489 Args.AddAllArgs(CmdArgs,
4490 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004491 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4492 options::OPT_fno_openmp_optimistic_collapse,
4493 /*Default=*/false))
4494 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004495
4496 // When in OpenMP offloading mode with NVPTX target, forward
4497 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004498 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4499 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4500 CmdArgs.push_back("-fopenmp-cuda-mode");
4501
4502 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4503 // is required.
4504 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4505 options::OPT_fno_openmp_cuda_force_full_runtime,
4506 /*Default=*/false))
4507 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004508 break;
4509 default:
4510 // By default, if Clang doesn't know how to generate useful OpenMP code
4511 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4512 // down to the actual compilation.
4513 // FIXME: It would be better to have a mode which *only* omits IR
4514 // generation based on the OpenMP support so that we get consistent
4515 // semantic analysis, etc.
4516 break;
4517 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004518 } else {
4519 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4520 options::OPT_fno_openmp_simd);
4521 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004522 }
4523
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004524 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4525 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004526
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004527 const XRayArgs &XRay = TC.getXRayArgs();
4528 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004529
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004530 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004531 Args.AddLastArg(CmdArgs, options::OPT_pg);
4532
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004533 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004534 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4535
4536 // -flax-vector-conversions is default.
4537 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4538 options::OPT_fno_lax_vector_conversions))
4539 CmdArgs.push_back("-fno-lax-vector-conversions");
4540
4541 if (Args.getLastArg(options::OPT_fapple_kext) ||
4542 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4543 CmdArgs.push_back("-fapple-kext");
4544
4545 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4546 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4547 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4548 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4549 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4550
4551 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4552 CmdArgs.push_back("-ftrapv-handler");
4553 CmdArgs.push_back(A->getValue());
4554 }
4555
4556 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4557
4558 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4559 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4560 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4561 if (A->getOption().matches(options::OPT_fwrapv))
4562 CmdArgs.push_back("-fwrapv");
4563 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4564 options::OPT_fno_strict_overflow)) {
4565 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4566 CmdArgs.push_back("-fwrapv");
4567 }
4568
4569 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4570 options::OPT_fno_reroll_loops))
4571 if (A->getOption().matches(options::OPT_freroll_loops))
4572 CmdArgs.push_back("-freroll-loops");
4573
4574 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4575 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4576 options::OPT_fno_unroll_loops);
4577
4578 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4579
Zola Bridgesc8666792018-11-26 18:13:31 +00004580 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4581 false))
4582 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004583
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004584 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004585 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004586
4587 // Translate -mstackrealign
4588 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4589 false))
4590 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4591
4592 if (Args.hasArg(options::OPT_mstack_alignment)) {
4593 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4594 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4595 }
4596
4597 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4598 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4599
4600 if (!Size.empty())
4601 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4602 else
4603 CmdArgs.push_back("-mstack-probe-size=0");
4604 }
4605
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004606 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4607 options::OPT_mno_stack_arg_probe, true))
4608 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4609
David L. Jonesf561aba2017-03-08 01:02:16 +00004610 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4611 options::OPT_mno_restrict_it)) {
4612 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004613 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004614 CmdArgs.push_back("-arm-restrict-it");
4615 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004616 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004617 CmdArgs.push_back("-arm-no-restrict-it");
4618 }
4619 } else if (Triple.isOSWindows() &&
4620 (Triple.getArch() == llvm::Triple::arm ||
4621 Triple.getArch() == llvm::Triple::thumb)) {
4622 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004623 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004624 CmdArgs.push_back("-arm-restrict-it");
4625 }
4626
4627 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004628 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004629
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004630 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4631 CmdArgs.push_back(
4632 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4633 }
4634
David L. Jonesf561aba2017-03-08 01:02:16 +00004635 // Forward -f options with positive and negative forms; we translate
4636 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004637 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004638 auto *PGOArg = Args.getLastArg(
4639 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4640 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4641 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4642 if (PGOArg)
4643 D.Diag(diag::err_drv_argument_not_allowed_with)
4644 << "SampleUse with PGO options";
4645
David L. Jonesf561aba2017-03-08 01:02:16 +00004646 StringRef fname = A->getValue();
4647 if (!llvm::sys::fs::exists(fname))
4648 D.Diag(diag::err_drv_no_such_file) << fname;
4649 else
4650 A->render(Args, CmdArgs);
4651 }
Richard Smith8654ae52018-10-10 23:13:35 +00004652 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004653
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004654 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004655
4656 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4657 options::OPT_fno_assume_sane_operator_new))
4658 CmdArgs.push_back("-fno-assume-sane-operator-new");
4659
4660 // -fblocks=0 is default.
4661 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004662 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004663 (Args.hasArg(options::OPT_fgnu_runtime) &&
4664 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4665 !Args.hasArg(options::OPT_fno_blocks))) {
4666 CmdArgs.push_back("-fblocks");
4667
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004668 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004669 CmdArgs.push_back("-fblocks-runtime-optional");
4670 }
4671
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004672 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004673 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004674 CmdArgs.push_back("-fencode-extended-block-signature");
4675
David L. Jonesf561aba2017-03-08 01:02:16 +00004676 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4677 false) &&
4678 types::isCXX(InputType)) {
4679 CmdArgs.push_back("-fcoroutines-ts");
4680 }
4681
Aaron Ballman61736552017-10-21 20:28:58 +00004682 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4683 options::OPT_fno_double_square_bracket_attributes);
4684
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00004685 bool HaveModules = false;
4686 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
David L. Jonesf561aba2017-03-08 01:02:16 +00004687
4688 // -faccess-control is default.
4689 if (Args.hasFlag(options::OPT_fno_access_control,
4690 options::OPT_faccess_control, false))
4691 CmdArgs.push_back("-fno-access-control");
4692
4693 // -felide-constructors is the default.
4694 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4695 options::OPT_felide_constructors, false))
4696 CmdArgs.push_back("-fno-elide-constructors");
4697
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004698 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004699
4700 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004701 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004702 CmdArgs.push_back("-fno-rtti");
4703
4704 // -fshort-enums=0 is default for all architectures except Hexagon.
4705 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004706 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004707 CmdArgs.push_back("-fshort-enums");
4708
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004709 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004710
4711 // -fuse-cxa-atexit is default.
4712 if (!Args.hasFlag(
4713 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004714 !RawTriple.isOSWindows() &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004715 RawTriple.getOS() != llvm::Triple::Solaris &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004716 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004717 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4718 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004719 KernelOrKext)
4720 CmdArgs.push_back("-fno-use-cxa-atexit");
4721
Akira Hatanaka617e2612018-04-17 18:41:52 +00004722 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4723 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004724 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004725 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4726
David L. Jonesf561aba2017-03-08 01:02:16 +00004727 // -fms-extensions=0 is default.
4728 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4729 IsWindowsMSVC))
4730 CmdArgs.push_back("-fms-extensions");
4731
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004732 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004733 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004734 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004735 CmdArgs.push_back("-fuse-line-directives");
4736
4737 // -fms-compatibility=0 is default.
4738 if (Args.hasFlag(options::OPT_fms_compatibility,
4739 options::OPT_fno_ms_compatibility,
4740 (IsWindowsMSVC &&
4741 Args.hasFlag(options::OPT_fms_extensions,
4742 options::OPT_fno_ms_extensions, true))))
4743 CmdArgs.push_back("-fms-compatibility");
4744
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004745 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004746 if (!MSVT.empty())
4747 CmdArgs.push_back(
4748 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4749
4750 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4751 if (ImplyVCPPCXXVer) {
4752 StringRef LanguageStandard;
4753 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4754 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4755 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004756 .Case("c++17", "-std=c++17")
4757 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004758 .Default("");
4759 if (LanguageStandard.empty())
4760 D.Diag(clang::diag::warn_drv_unused_argument)
4761 << StdArg->getAsString(Args);
4762 }
4763
4764 if (LanguageStandard.empty()) {
4765 if (IsMSVC2015Compatible)
4766 LanguageStandard = "-std=c++14";
4767 else
4768 LanguageStandard = "-std=c++11";
4769 }
4770
4771 CmdArgs.push_back(LanguageStandard.data());
4772 }
4773
4774 // -fno-borland-extensions is default.
4775 if (Args.hasFlag(options::OPT_fborland_extensions,
4776 options::OPT_fno_borland_extensions, false))
4777 CmdArgs.push_back("-fborland-extensions");
4778
4779 // -fno-declspec is default, except for PS4.
4780 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004781 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004782 CmdArgs.push_back("-fdeclspec");
4783 else if (Args.hasArg(options::OPT_fno_declspec))
4784 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4785
4786 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4787 // than 19.
4788 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4789 options::OPT_fno_threadsafe_statics,
4790 !IsWindowsMSVC || IsMSVC2015Compatible))
4791 CmdArgs.push_back("-fno-threadsafe-statics");
4792
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004793 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004794 // Many old Windows SDK versions require this to parse.
4795 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4796 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004797 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4798 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4799 CmdArgs.push_back("-fdelayed-template-parsing");
4800
4801 // -fgnu-keywords default varies depending on language; only pass if
4802 // specified.
4803 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4804 options::OPT_fno_gnu_keywords))
4805 A->render(Args, CmdArgs);
4806
4807 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4808 false))
4809 CmdArgs.push_back("-fgnu89-inline");
4810
4811 if (Args.hasArg(options::OPT_fno_inline))
4812 CmdArgs.push_back("-fno-inline");
4813
4814 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4815 options::OPT_finline_hint_functions,
4816 options::OPT_fno_inline_functions))
4817 InlineArg->render(Args, CmdArgs);
4818
4819 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4820 options::OPT_fno_experimental_new_pass_manager);
4821
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004822 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004823 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4824 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004825
4826 if (Args.hasFlag(options::OPT_fapplication_extension,
4827 options::OPT_fno_application_extension, false))
4828 CmdArgs.push_back("-fapplication-extension");
4829
4830 // Handle GCC-style exception args.
4831 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004832 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004833
Martell Malonec950c652017-11-29 07:25:12 +00004834 // Handle exception personalities
4835 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4836 options::OPT_fseh_exceptions,
4837 options::OPT_fdwarf_exceptions);
4838 if (A) {
4839 const Option &Opt = A->getOption();
4840 if (Opt.matches(options::OPT_fsjlj_exceptions))
4841 CmdArgs.push_back("-fsjlj-exceptions");
4842 if (Opt.matches(options::OPT_fseh_exceptions))
4843 CmdArgs.push_back("-fseh-exceptions");
4844 if (Opt.matches(options::OPT_fdwarf_exceptions))
4845 CmdArgs.push_back("-fdwarf-exceptions");
4846 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004847 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004848 default:
4849 break;
4850 case llvm::ExceptionHandling::DwarfCFI:
4851 CmdArgs.push_back("-fdwarf-exceptions");
4852 break;
4853 case llvm::ExceptionHandling::SjLj:
4854 CmdArgs.push_back("-fsjlj-exceptions");
4855 break;
4856 case llvm::ExceptionHandling::WinEH:
4857 CmdArgs.push_back("-fseh-exceptions");
4858 break;
Martell Malonec950c652017-11-29 07:25:12 +00004859 }
4860 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004861
4862 // C++ "sane" operator new.
4863 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4864 options::OPT_fno_assume_sane_operator_new))
4865 CmdArgs.push_back("-fno-assume-sane-operator-new");
4866
4867 // -frelaxed-template-template-args is off by default, as it is a severe
4868 // breaking change until a corresponding change to template partial ordering
4869 // is provided.
4870 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4871 options::OPT_fno_relaxed_template_template_args, false))
4872 CmdArgs.push_back("-frelaxed-template-template-args");
4873
4874 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4875 // most platforms.
4876 if (Args.hasFlag(options::OPT_fsized_deallocation,
4877 options::OPT_fno_sized_deallocation, false))
4878 CmdArgs.push_back("-fsized-deallocation");
4879
4880 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4881 // by default.
4882 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4883 options::OPT_fno_aligned_allocation,
4884 options::OPT_faligned_new_EQ)) {
4885 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4886 CmdArgs.push_back("-fno-aligned-allocation");
4887 else
4888 CmdArgs.push_back("-faligned-allocation");
4889 }
4890
4891 // The default new alignment can be specified using a dedicated option or via
4892 // a GCC-compatible option that also turns on aligned allocation.
4893 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4894 options::OPT_faligned_new_EQ))
4895 CmdArgs.push_back(
4896 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4897
4898 // -fconstant-cfstrings is default, and may be subject to argument translation
4899 // on Darwin.
4900 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4901 options::OPT_fno_constant_cfstrings) ||
4902 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4903 options::OPT_mno_constant_cfstrings))
4904 CmdArgs.push_back("-fno-constant-cfstrings");
4905
David L. Jonesf561aba2017-03-08 01:02:16 +00004906 // -fno-pascal-strings is default, only pass non-default.
4907 if (Args.hasFlag(options::OPT_fpascal_strings,
4908 options::OPT_fno_pascal_strings, false))
4909 CmdArgs.push_back("-fpascal-strings");
4910
4911 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4912 // -fno-pack-struct doesn't apply to -fpack-struct=.
4913 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4914 std::string PackStructStr = "-fpack-struct=";
4915 PackStructStr += A->getValue();
4916 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4917 } else if (Args.hasFlag(options::OPT_fpack_struct,
4918 options::OPT_fno_pack_struct, false)) {
4919 CmdArgs.push_back("-fpack-struct=1");
4920 }
4921
4922 // Handle -fmax-type-align=N and -fno-type-align
4923 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4924 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4925 if (!SkipMaxTypeAlign) {
4926 std::string MaxTypeAlignStr = "-fmax-type-align=";
4927 MaxTypeAlignStr += A->getValue();
4928 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4929 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004930 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004931 if (!SkipMaxTypeAlign) {
4932 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4933 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4934 }
4935 }
4936
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004937 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4938 CmdArgs.push_back("-Qn");
4939
David L. Jonesf561aba2017-03-08 01:02:16 +00004940 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004941 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004942 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4943 !NoCommonDefault))
4944 CmdArgs.push_back("-fno-common");
4945
4946 // -fsigned-bitfields is default, and clang doesn't yet support
4947 // -funsigned-bitfields.
4948 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4949 options::OPT_funsigned_bitfields))
4950 D.Diag(diag::warn_drv_clang_unsupported)
4951 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4952
4953 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4954 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4955 D.Diag(diag::err_drv_clang_unsupported)
4956 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4957
4958 // -finput_charset=UTF-8 is default. Reject others
4959 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4960 StringRef value = inputCharset->getValue();
4961 if (!value.equals_lower("utf-8"))
4962 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4963 << value;
4964 }
4965
4966 // -fexec_charset=UTF-8 is default. Reject others
4967 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4968 StringRef value = execCharset->getValue();
4969 if (!value.equals_lower("utf-8"))
4970 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4971 << value;
4972 }
4973
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00004974 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004975
4976 // -fno-asm-blocks is default.
4977 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4978 false))
4979 CmdArgs.push_back("-fasm-blocks");
4980
4981 // -fgnu-inline-asm is default.
4982 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4983 options::OPT_fno_gnu_inline_asm, true))
4984 CmdArgs.push_back("-fno-gnu-inline-asm");
4985
4986 // Enable vectorization per default according to the optimization level
4987 // selected. For optimization levels that want vectorization we use the alias
4988 // option to simplify the hasFlag logic.
4989 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4990 OptSpecifier VectorizeAliasOption =
4991 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4992 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4993 options::OPT_fno_vectorize, EnableVec))
4994 CmdArgs.push_back("-vectorize-loops");
4995
4996 // -fslp-vectorize is enabled based on the optimization level selected.
4997 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
4998 OptSpecifier SLPVectAliasOption =
4999 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5000 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5001 options::OPT_fno_slp_vectorize, EnableSLPVec))
5002 CmdArgs.push_back("-vectorize-slp");
5003
Craig Topper9a724aa2017-12-11 21:09:19 +00005004 ParseMPreferVectorWidth(D, Args, CmdArgs);
5005
David L. Jonesf561aba2017-03-08 01:02:16 +00005006 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5007 A->render(Args, CmdArgs);
5008
5009 if (Arg *A = Args.getLastArg(
5010 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5011 A->render(Args, CmdArgs);
5012
5013 // -fdollars-in-identifiers default varies depending on platform and
5014 // language; only pass if specified.
5015 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5016 options::OPT_fno_dollars_in_identifiers)) {
5017 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5018 CmdArgs.push_back("-fdollars-in-identifiers");
5019 else
5020 CmdArgs.push_back("-fno-dollars-in-identifiers");
5021 }
5022
5023 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5024 // practical purposes.
5025 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5026 options::OPT_fno_unit_at_a_time)) {
5027 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5028 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5029 }
5030
5031 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5032 options::OPT_fno_apple_pragma_pack, false))
5033 CmdArgs.push_back("-fapple-pragma-pack");
5034
David L. Jonesf561aba2017-03-08 01:02:16 +00005035 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005036 options::OPT_foptimization_record_file_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005037 options::OPT_fno_save_optimization_record, false)) {
5038 CmdArgs.push_back("-opt-record-file");
5039
5040 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5041 if (A) {
5042 CmdArgs.push_back(A->getValue());
5043 } else {
5044 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005045
5046 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5047 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5048 F = FinalOutput->getValue();
5049 }
5050
5051 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005052 // Use the input filename.
5053 F = llvm::sys::path::stem(Input.getBaseInput());
5054
5055 // If we're compiling for an offload architecture (i.e. a CUDA device),
5056 // we need to make the file name for the device compilation different
5057 // from the host compilation.
5058 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5059 !JA.isDeviceOffloading(Action::OFK_Host)) {
5060 llvm::sys::path::replace_extension(F, "");
5061 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5062 Triple.normalize());
5063 F += "-";
5064 F += JA.getOffloadingArch();
5065 }
5066 }
5067
5068 llvm::sys::path::replace_extension(F, "opt.yaml");
5069 CmdArgs.push_back(Args.MakeArgString(F));
5070 }
5071 }
5072
Richard Smith86a3ef52017-06-09 21:24:02 +00005073 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5074 options::OPT_fno_rewrite_imports, false);
5075 if (RewriteImports)
5076 CmdArgs.push_back("-frewrite-imports");
5077
David L. Jonesf561aba2017-03-08 01:02:16 +00005078 // Enable rewrite includes if the user's asked for it or if we're generating
5079 // diagnostics.
5080 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5081 // nice to enable this when doing a crashdump for modules as well.
5082 if (Args.hasFlag(options::OPT_frewrite_includes,
5083 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005084 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005085 CmdArgs.push_back("-frewrite-includes");
5086
5087 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5088 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5089 options::OPT_traditional_cpp)) {
5090 if (isa<PreprocessJobAction>(JA))
5091 CmdArgs.push_back("-traditional-cpp");
5092 else
5093 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5094 }
5095
5096 Args.AddLastArg(CmdArgs, options::OPT_dM);
5097 Args.AddLastArg(CmdArgs, options::OPT_dD);
5098
5099 // Handle serialized diagnostics.
5100 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5101 CmdArgs.push_back("-serialize-diagnostic-file");
5102 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5103 }
5104
5105 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5106 CmdArgs.push_back("-fretain-comments-from-system-headers");
5107
5108 // Forward -fcomment-block-commands to -cc1.
5109 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5110 // Forward -fparse-all-comments to -cc1.
5111 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5112
5113 // Turn -fplugin=name.so into -load name.so
5114 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5115 CmdArgs.push_back("-load");
5116 CmdArgs.push_back(A->getValue());
5117 A->claim();
5118 }
5119
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005120 // Forward -fpass-plugin=name.so to -cc1.
5121 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5122 CmdArgs.push_back(
5123 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5124 A->claim();
5125 }
5126
David L. Jonesf561aba2017-03-08 01:02:16 +00005127 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005128 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5129 if (!StatsFile.empty())
5130 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005131
5132 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5133 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005134 // -finclude-default-header flag is for preprocessor,
5135 // do not pass it to other cc1 commands when save-temps is enabled
5136 if (C.getDriver().isSaveTempsEnabled() &&
5137 !isa<PreprocessJobAction>(JA)) {
5138 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5139 Arg->claim();
5140 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5141 CmdArgs.push_back(Arg->getValue());
5142 }
5143 }
5144 else {
5145 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5146 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005147 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5148 A->claim();
5149
5150 // We translate this by hand to the -cc1 argument, since nightly test uses
5151 // it and developers have been trained to spell it with -mllvm. Both
5152 // spellings are now deprecated and should be removed.
5153 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5154 CmdArgs.push_back("-disable-llvm-optzns");
5155 } else {
5156 A->render(Args, CmdArgs);
5157 }
5158 }
5159
5160 // With -save-temps, we want to save the unoptimized bitcode output from the
5161 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5162 // by the frontend.
5163 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5164 // has slightly different breakdown between stages.
5165 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5166 // pristine IR generated by the frontend. Ideally, a new compile action should
5167 // be added so both IR can be captured.
5168 if (C.getDriver().isSaveTempsEnabled() &&
5169 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5170 isa<CompileJobAction>(JA))
5171 CmdArgs.push_back("-disable-llvm-passes");
5172
5173 if (Output.getType() == types::TY_Dependencies) {
5174 // Handled with other dependency code.
5175 } else if (Output.isFilename()) {
5176 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00005177 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00005178 } else {
5179 assert(Output.isNothing() && "Invalid output.");
5180 }
5181
5182 addDashXForInput(Args, Input, CmdArgs);
5183
Richard Smithcd35eff2018-09-15 01:21:16 +00005184 ArrayRef<InputInfo> FrontendInputs = Input;
5185 if (IsHeaderModulePrecompile)
5186 FrontendInputs = ModuleHeaderInputs;
5187 else if (Input.isNothing())
5188 FrontendInputs = {};
5189
5190 for (const InputInfo &Input : FrontendInputs) {
5191 if (Input.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00005192 CmdArgs.push_back(Input.getFilename());
Richard Smithcd35eff2018-09-15 01:21:16 +00005193 else
5194 Input.getInputArg().renderAsInput(Args, CmdArgs);
5195 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005196
5197 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5198
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005199 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005200
Scott Linderde6beb02018-12-14 15:38:15 +00005201 // Optionally embed the -cc1 level arguments into the debug info or a
5202 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005203 // Also record command line arguments into the debug info if
5204 // -grecord-gcc-switches options is set on.
5205 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005206 auto GRecordSwitches =
5207 Args.hasFlag(options::OPT_grecord_command_line,
5208 options::OPT_gno_record_command_line, false);
5209 auto FRecordSwitches =
5210 Args.hasFlag(options::OPT_frecord_command_line,
5211 options::OPT_fno_record_command_line, false);
5212 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5213 D.Diag(diag::err_drv_unsupported_opt_for_target)
5214 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5215 << TripleStr;
5216 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005217 ArgStringList OriginalArgs;
5218 for (const auto &Arg : Args)
5219 Arg->render(Args, OriginalArgs);
5220
5221 SmallString<256> Flags;
5222 Flags += Exec;
5223 for (const char *OriginalArg : OriginalArgs) {
5224 SmallString<128> EscapedArg;
5225 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5226 Flags += " ";
5227 Flags += EscapedArg;
5228 }
Scott Linderde6beb02018-12-14 15:38:15 +00005229 auto FlagsArgString = Args.MakeArgString(Flags);
5230 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5231 CmdArgs.push_back("-dwarf-debug-flags");
5232 CmdArgs.push_back(FlagsArgString);
5233 }
5234 if (FRecordSwitches) {
5235 CmdArgs.push_back("-record-command-line");
5236 CmdArgs.push_back(FlagsArgString);
5237 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005238 }
5239
Yaxun Liu97670892018-10-02 17:48:54 +00005240 // Host-side cuda compilation receives all device-side outputs in a single
5241 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5242 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005243 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005244 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005245 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5246 CmdArgs.push_back("-fgpu-rdc");
5247 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005248
Yaxun Liu97670892018-10-02 17:48:54 +00005249 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005250 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5251 options::OPT_fno_cuda_short_ptr, false))
5252 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005253 }
5254
David L. Jonesf561aba2017-03-08 01:02:16 +00005255 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5256 // to specify the result of the compile phase on the host, so the meaningful
5257 // device declarations can be identified. Also, -fopenmp-is-device is passed
5258 // along to tell the frontend that it is generating code for a device, so that
5259 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005260 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005261 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005262 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005263 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005264 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005265 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005266 }
5267
5268 // For all the host OpenMP offloading compile jobs we need to pass the targets
5269 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005270 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005271 SmallString<128> TargetInfo("-fopenmp-targets=");
5272
5273 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5274 assert(Tgts && Tgts->getNumValues() &&
5275 "OpenMP offloading has to have targets specified.");
5276 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5277 if (i)
5278 TargetInfo += ',';
5279 // We need to get the string from the triple because it may be not exactly
5280 // the same as the one we get directly from the arguments.
5281 llvm::Triple T(Tgts->getValue(i));
5282 TargetInfo += T.getTriple();
5283 }
5284 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5285 }
5286
5287 bool WholeProgramVTables =
5288 Args.hasFlag(options::OPT_fwhole_program_vtables,
5289 options::OPT_fno_whole_program_vtables, false);
5290 if (WholeProgramVTables) {
5291 if (!D.isUsingLTO())
5292 D.Diag(diag::err_drv_argument_only_allowed_with)
5293 << "-fwhole-program-vtables"
5294 << "-flto";
5295 CmdArgs.push_back("-fwhole-program-vtables");
5296 }
5297
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005298 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5299 bool SplitLTOUnit =
5300 Args.hasFlag(options::OPT_fsplit_lto_unit,
5301 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5302 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5303 D.Diag(diag::err_drv_argument_not_allowed_with)
5304 << "-fno-split-lto-unit"
5305 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5306 if (SplitLTOUnit)
5307 CmdArgs.push_back("-fsplit-lto-unit");
5308
Amara Emerson4ee9f822018-01-26 00:27:22 +00005309 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5310 options::OPT_fno_experimental_isel)) {
5311 CmdArgs.push_back("-mllvm");
5312 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5313 CmdArgs.push_back("-global-isel=1");
5314
5315 // GISel is on by default on AArch64 -O0, so don't bother adding
5316 // the fallback remarks for it. Other combinations will add a warning of
5317 // some kind.
5318 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5319 bool IsOptLevelSupported = false;
5320
5321 Arg *A = Args.getLastArg(options::OPT_O_Group);
5322 if (Triple.getArch() == llvm::Triple::aarch64) {
5323 if (!A || A->getOption().matches(options::OPT_O0))
5324 IsOptLevelSupported = true;
5325 }
5326 if (!IsArchSupported || !IsOptLevelSupported) {
5327 CmdArgs.push_back("-mllvm");
5328 CmdArgs.push_back("-global-isel-abort=2");
5329
5330 if (!IsArchSupported)
5331 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5332 else
5333 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5334 }
5335 } else {
5336 CmdArgs.push_back("-global-isel=0");
5337 }
5338 }
5339
Manman Ren394d4cc2019-03-04 20:30:30 +00005340 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5341 CmdArgs.push_back("-forder-file-instrumentation");
5342 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5343 // on, we need to pass these flags as linker flags and that will be handled
5344 // outside of the compiler.
5345 if (!D.isUsingLTO()) {
5346 CmdArgs.push_back("-mllvm");
5347 CmdArgs.push_back("-enable-order-file-instrumentation");
5348 }
5349 }
5350
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005351 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5352 options::OPT_fno_force_enable_int128)) {
5353 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5354 CmdArgs.push_back("-fforce-enable-int128");
5355 }
5356
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005357 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5358 options::OPT_fno_complete_member_pointers, false))
5359 CmdArgs.push_back("-fcomplete-member-pointers");
5360
Erik Pilkington5a559e62018-08-21 17:24:06 +00005361 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5362 options::OPT_fno_cxx_static_destructors, true))
5363 CmdArgs.push_back("-fno-c++-static-destructors");
5364
Jessica Paquette36a25672018-06-29 18:06:10 +00005365 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5366 options::OPT_mno_outline)) {
5367 if (A->getOption().matches(options::OPT_moutline)) {
5368 // We only support -moutline in AArch64 right now. If we're not compiling
5369 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5370 // proper mllvm flags.
5371 if (Triple.getArch() != llvm::Triple::aarch64) {
5372 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5373 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005374 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005375 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005376 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005377 } else {
5378 // Disable all outlining behaviour.
5379 CmdArgs.push_back("-mllvm");
5380 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005381 }
5382 }
5383
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005384 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005385 (TC.getTriple().isOSBinFormatELF() ||
5386 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005387 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005388 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005389 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005390 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005391 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005392 CmdArgs.push_back("-faddrsig");
5393
David L. Jonesf561aba2017-03-08 01:02:16 +00005394 // Finally add the compile command to the compilation.
5395 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5396 Output.getType() == types::TY_Object &&
5397 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5398 auto CLCommand =
5399 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5400 C.addCommand(llvm::make_unique<FallbackCommand>(
5401 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5402 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5403 isa<PrecompileJobAction>(JA)) {
5404 // In /fallback builds, run the main compilation even if the pch generation
5405 // fails, so that the main compilation's fallback to cl.exe runs.
5406 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5407 CmdArgs, Inputs));
5408 } else {
5409 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5410 }
5411
Hans Wennborg2fe01042018-10-13 19:13:14 +00005412 // Make the compile command echo its inputs for /showFilenames.
5413 if (Output.getType() == types::TY_Object &&
5414 Args.hasFlag(options::OPT__SLASH_showFilenames,
5415 options::OPT__SLASH_showFilenames_, false)) {
5416 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5417 }
5418
David L. Jonesf561aba2017-03-08 01:02:16 +00005419 if (Arg *A = Args.getLastArg(options::OPT_pg))
David Blaikie5941da32018-09-18 20:11:45 +00005420 if (!shouldUseFramePointer(Args, Triple))
David L. Jonesf561aba2017-03-08 01:02:16 +00005421 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5422 << A->getAsString(Args);
5423
5424 // Claim some arguments which clang supports automatically.
5425
5426 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005427 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005428 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5429
5430 // Claim some arguments which clang doesn't support, but we don't
5431 // care to warn the user about.
5432 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5433 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5434
5435 // Disable warnings for clang -E -emit-llvm foo.c
5436 Args.ClaimAllArgs(options::OPT_emit_llvm);
5437}
5438
5439Clang::Clang(const ToolChain &TC)
5440 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5441 // as it is for other tools. Some operations on a Tool actually test
5442 // whether that tool is Clang based on the Tool's Name as a string.
5443 : Tool("clang", "clang frontend", TC, RF_Full) {}
5444
5445Clang::~Clang() {}
5446
5447/// Add options related to the Objective-C runtime/ABI.
5448///
5449/// Returns true if the runtime is non-fragile.
5450ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5451 ArgStringList &cmdArgs,
5452 RewriteKind rewriteKind) const {
5453 // Look for the controlling runtime option.
5454 Arg *runtimeArg =
5455 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5456 options::OPT_fobjc_runtime_EQ);
5457
5458 // Just forward -fobjc-runtime= to the frontend. This supercedes
5459 // options about fragility.
5460 if (runtimeArg &&
5461 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5462 ObjCRuntime runtime;
5463 StringRef value = runtimeArg->getValue();
5464 if (runtime.tryParse(value)) {
5465 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5466 << value;
5467 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005468 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5469 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005470 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5471 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005472 getToolChain().getDriver().Diag(
5473 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5474 << runtime.getVersion().getMajor();
5475 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005476
5477 runtimeArg->render(args, cmdArgs);
5478 return runtime;
5479 }
5480
5481 // Otherwise, we'll need the ABI "version". Version numbers are
5482 // slightly confusing for historical reasons:
5483 // 1 - Traditional "fragile" ABI
5484 // 2 - Non-fragile ABI, version 1
5485 // 3 - Non-fragile ABI, version 2
5486 unsigned objcABIVersion = 1;
5487 // If -fobjc-abi-version= is present, use that to set the version.
5488 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5489 StringRef value = abiArg->getValue();
5490 if (value == "1")
5491 objcABIVersion = 1;
5492 else if (value == "2")
5493 objcABIVersion = 2;
5494 else if (value == "3")
5495 objcABIVersion = 3;
5496 else
5497 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5498 } else {
5499 // Otherwise, determine if we are using the non-fragile ABI.
5500 bool nonFragileABIIsDefault =
5501 (rewriteKind == RK_NonFragile ||
5502 (rewriteKind == RK_None &&
5503 getToolChain().IsObjCNonFragileABIDefault()));
5504 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5505 options::OPT_fno_objc_nonfragile_abi,
5506 nonFragileABIIsDefault)) {
5507// Determine the non-fragile ABI version to use.
5508#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5509 unsigned nonFragileABIVersion = 1;
5510#else
5511 unsigned nonFragileABIVersion = 2;
5512#endif
5513
5514 if (Arg *abiArg =
5515 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5516 StringRef value = abiArg->getValue();
5517 if (value == "1")
5518 nonFragileABIVersion = 1;
5519 else if (value == "2")
5520 nonFragileABIVersion = 2;
5521 else
5522 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5523 << value;
5524 }
5525
5526 objcABIVersion = 1 + nonFragileABIVersion;
5527 } else {
5528 objcABIVersion = 1;
5529 }
5530 }
5531
5532 // We don't actually care about the ABI version other than whether
5533 // it's non-fragile.
5534 bool isNonFragile = objcABIVersion != 1;
5535
5536 // If we have no runtime argument, ask the toolchain for its default runtime.
5537 // However, the rewriter only really supports the Mac runtime, so assume that.
5538 ObjCRuntime runtime;
5539 if (!runtimeArg) {
5540 switch (rewriteKind) {
5541 case RK_None:
5542 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5543 break;
5544 case RK_Fragile:
5545 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5546 break;
5547 case RK_NonFragile:
5548 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5549 break;
5550 }
5551
5552 // -fnext-runtime
5553 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5554 // On Darwin, make this use the default behavior for the toolchain.
5555 if (getToolChain().getTriple().isOSDarwin()) {
5556 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5557
5558 // Otherwise, build for a generic macosx port.
5559 } else {
5560 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5561 }
5562
5563 // -fgnu-runtime
5564 } else {
5565 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5566 // Legacy behaviour is to target the gnustep runtime if we are in
5567 // non-fragile mode or the GCC runtime in fragile mode.
5568 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005569 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005570 else
5571 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5572 }
5573
5574 cmdArgs.push_back(
5575 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5576 return runtime;
5577}
5578
5579static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5580 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5581 I += HaveDash;
5582 return !HaveDash;
5583}
5584
5585namespace {
5586struct EHFlags {
5587 bool Synch = false;
5588 bool Asynch = false;
5589 bool NoUnwindC = false;
5590};
5591} // end anonymous namespace
5592
5593/// /EH controls whether to run destructor cleanups when exceptions are
5594/// thrown. There are three modifiers:
5595/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5596/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5597/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5598/// - c: Assume that extern "C" functions are implicitly nounwind.
5599/// The default is /EHs-c-, meaning cleanups are disabled.
5600static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5601 EHFlags EH;
5602
5603 std::vector<std::string> EHArgs =
5604 Args.getAllArgValues(options::OPT__SLASH_EH);
5605 for (auto EHVal : EHArgs) {
5606 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5607 switch (EHVal[I]) {
5608 case 'a':
5609 EH.Asynch = maybeConsumeDash(EHVal, I);
5610 if (EH.Asynch)
5611 EH.Synch = false;
5612 continue;
5613 case 'c':
5614 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5615 continue;
5616 case 's':
5617 EH.Synch = maybeConsumeDash(EHVal, I);
5618 if (EH.Synch)
5619 EH.Asynch = false;
5620 continue;
5621 default:
5622 break;
5623 }
5624 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5625 break;
5626 }
5627 }
5628 // The /GX, /GX- flags are only processed if there are not /EH flags.
5629 // The default is that /GX is not specified.
5630 if (EHArgs.empty() &&
5631 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5632 /*default=*/false)) {
5633 EH.Synch = true;
5634 EH.NoUnwindC = true;
5635 }
5636
5637 return EH;
5638}
5639
5640void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5641 ArgStringList &CmdArgs,
5642 codegenoptions::DebugInfoKind *DebugInfoKind,
5643 bool *EmitCodeView) const {
5644 unsigned RTOptionID = options::OPT__SLASH_MT;
5645
5646 if (Args.hasArg(options::OPT__SLASH_LDd))
5647 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5648 // but defining _DEBUG is sticky.
5649 RTOptionID = options::OPT__SLASH_MTd;
5650
5651 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5652 RTOptionID = A->getOption().getID();
5653
5654 StringRef FlagForCRT;
5655 switch (RTOptionID) {
5656 case options::OPT__SLASH_MD:
5657 if (Args.hasArg(options::OPT__SLASH_LDd))
5658 CmdArgs.push_back("-D_DEBUG");
5659 CmdArgs.push_back("-D_MT");
5660 CmdArgs.push_back("-D_DLL");
5661 FlagForCRT = "--dependent-lib=msvcrt";
5662 break;
5663 case options::OPT__SLASH_MDd:
5664 CmdArgs.push_back("-D_DEBUG");
5665 CmdArgs.push_back("-D_MT");
5666 CmdArgs.push_back("-D_DLL");
5667 FlagForCRT = "--dependent-lib=msvcrtd";
5668 break;
5669 case options::OPT__SLASH_MT:
5670 if (Args.hasArg(options::OPT__SLASH_LDd))
5671 CmdArgs.push_back("-D_DEBUG");
5672 CmdArgs.push_back("-D_MT");
5673 CmdArgs.push_back("-flto-visibility-public-std");
5674 FlagForCRT = "--dependent-lib=libcmt";
5675 break;
5676 case options::OPT__SLASH_MTd:
5677 CmdArgs.push_back("-D_DEBUG");
5678 CmdArgs.push_back("-D_MT");
5679 CmdArgs.push_back("-flto-visibility-public-std");
5680 FlagForCRT = "--dependent-lib=libcmtd";
5681 break;
5682 default:
5683 llvm_unreachable("Unexpected option ID.");
5684 }
5685
5686 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5687 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5688 } else {
5689 CmdArgs.push_back(FlagForCRT.data());
5690
5691 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5692 // users want. The /Za flag to cl.exe turns this off, but it's not
5693 // implemented in clang.
5694 CmdArgs.push_back("--dependent-lib=oldnames");
5695 }
5696
Erich Keane425f48d2018-05-04 15:58:31 +00005697 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5698 A->render(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005699
5700 // This controls whether or not we emit RTTI data for polymorphic types.
5701 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5702 /*default=*/false))
5703 CmdArgs.push_back("-fno-rtti-data");
5704
5705 // This controls whether or not we emit stack-protector instrumentation.
5706 // In MSVC, Buffer Security Check (/GS) is on by default.
5707 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5708 /*default=*/true)) {
5709 CmdArgs.push_back("-stack-protector");
5710 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5711 }
5712
5713 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5714 if (Arg *DebugInfoArg =
5715 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5716 options::OPT_gline_tables_only)) {
5717 *EmitCodeView = true;
5718 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5719 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5720 else
5721 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005722 } else {
5723 *EmitCodeView = false;
5724 }
5725
5726 const Driver &D = getToolChain().getDriver();
5727 EHFlags EH = parseClangCLEHFlags(D, Args);
5728 if (EH.Synch || EH.Asynch) {
5729 if (types::isCXX(InputType))
5730 CmdArgs.push_back("-fcxx-exceptions");
5731 CmdArgs.push_back("-fexceptions");
5732 }
5733 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5734 CmdArgs.push_back("-fexternc-nounwind");
5735
5736 // /EP should expand to -E -P.
5737 if (Args.hasArg(options::OPT__SLASH_EP)) {
5738 CmdArgs.push_back("-E");
5739 CmdArgs.push_back("-P");
5740 }
5741
5742 unsigned VolatileOptionID;
5743 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5744 getToolChain().getArch() == llvm::Triple::x86)
5745 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5746 else
5747 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5748
5749 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5750 VolatileOptionID = A->getOption().getID();
5751
5752 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5753 CmdArgs.push_back("-fms-volatile");
5754
Takuto Ikuta302c6432018-11-03 06:45:00 +00005755 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5756 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005757 false)) {
5758 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5759 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5760 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005761 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005762 }
5763 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005764
David L. Jonesf561aba2017-03-08 01:02:16 +00005765 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5766 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5767 if (MostGeneralArg && BestCaseArg)
5768 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5769 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5770
5771 if (MostGeneralArg) {
5772 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5773 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5774 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5775
5776 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5777 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5778 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5779 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5780 << FirstConflict->getAsString(Args)
5781 << SecondConflict->getAsString(Args);
5782
5783 if (SingleArg)
5784 CmdArgs.push_back("-fms-memptr-rep=single");
5785 else if (MultipleArg)
5786 CmdArgs.push_back("-fms-memptr-rep=multiple");
5787 else
5788 CmdArgs.push_back("-fms-memptr-rep=virtual");
5789 }
5790
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005791 // Parse the default calling convention options.
5792 if (Arg *CCArg =
5793 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005794 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5795 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005796 unsigned DCCOptId = CCArg->getOption().getID();
5797 const char *DCCFlag = nullptr;
5798 bool ArchSupported = true;
5799 llvm::Triple::ArchType Arch = getToolChain().getArch();
5800 switch (DCCOptId) {
5801 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005802 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005803 break;
5804 case options::OPT__SLASH_Gr:
5805 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005806 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005807 break;
5808 case options::OPT__SLASH_Gz:
5809 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005810 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005811 break;
5812 case options::OPT__SLASH_Gv:
5813 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005814 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005815 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005816 case options::OPT__SLASH_Gregcall:
5817 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5818 DCCFlag = "-fdefault-calling-conv=regcall";
5819 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005820 }
5821
5822 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5823 if (ArchSupported && DCCFlag)
5824 CmdArgs.push_back(DCCFlag);
5825 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005826
5827 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5828 A->render(Args, CmdArgs);
5829
5830 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5831 CmdArgs.push_back("-fdiagnostics-format");
5832 if (Args.hasArg(options::OPT__SLASH_fallback))
5833 CmdArgs.push_back("msvc-fallback");
5834 else
5835 CmdArgs.push_back("msvc");
5836 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005837
Hans Wennborga912e3e2018-08-10 09:49:21 +00005838 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5839 SmallVector<StringRef, 1> SplitArgs;
5840 StringRef(A->getValue()).split(SplitArgs, ",");
5841 bool Instrument = false;
5842 bool NoChecks = false;
5843 for (StringRef Arg : SplitArgs) {
5844 if (Arg.equals_lower("cf"))
5845 Instrument = true;
5846 else if (Arg.equals_lower("cf-"))
5847 Instrument = false;
5848 else if (Arg.equals_lower("nochecks"))
5849 NoChecks = true;
5850 else if (Arg.equals_lower("nochecks-"))
5851 NoChecks = false;
5852 else
5853 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5854 }
5855 // Currently there's no support emitting CFG instrumentation; the flag only
5856 // emits the table of address-taken functions.
5857 if (Instrument || NoChecks)
5858 CmdArgs.push_back("-cfguard");
5859 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005860}
5861
5862visualstudio::Compiler *Clang::getCLFallback() const {
5863 if (!CLFallback)
5864 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5865 return CLFallback.get();
5866}
5867
5868
5869const char *Clang::getBaseInputName(const ArgList &Args,
5870 const InputInfo &Input) {
5871 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5872}
5873
5874const char *Clang::getBaseInputStem(const ArgList &Args,
5875 const InputInfoList &Inputs) {
5876 const char *Str = getBaseInputName(Args, Inputs[0]);
5877
5878 if (const char *End = strrchr(Str, '.'))
5879 return Args.MakeArgString(std::string(Str, End));
5880
5881 return Str;
5882}
5883
5884const char *Clang::getDependencyFileName(const ArgList &Args,
5885 const InputInfoList &Inputs) {
5886 // FIXME: Think about this more.
5887 std::string Res;
5888
5889 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5890 std::string Str(OutputOpt->getValue());
5891 Res = Str.substr(0, Str.rfind('.'));
5892 } else {
5893 Res = getBaseInputStem(Args, Inputs);
5894 }
5895 return Args.MakeArgString(Res + ".d");
5896}
5897
5898// Begin ClangAs
5899
5900void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5901 ArgStringList &CmdArgs) const {
5902 StringRef CPUName;
5903 StringRef ABIName;
5904 const llvm::Triple &Triple = getToolChain().getTriple();
5905 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5906
5907 CmdArgs.push_back("-target-abi");
5908 CmdArgs.push_back(ABIName.data());
5909}
5910
5911void ClangAs::AddX86TargetArgs(const ArgList &Args,
5912 ArgStringList &CmdArgs) const {
5913 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5914 StringRef Value = A->getValue();
5915 if (Value == "intel" || Value == "att") {
5916 CmdArgs.push_back("-mllvm");
5917 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5918 } else {
5919 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5920 << A->getOption().getName() << Value;
5921 }
5922 }
5923}
5924
5925void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5926 const InputInfo &Output, const InputInfoList &Inputs,
5927 const ArgList &Args,
5928 const char *LinkingOutput) const {
5929 ArgStringList CmdArgs;
5930
5931 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5932 const InputInfo &Input = Inputs[0];
5933
Martin Storsjob547ef22018-10-26 08:33:29 +00005934 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00005935 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00005936 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00005937
5938 // Don't warn about "clang -w -c foo.s"
5939 Args.ClaimAllArgs(options::OPT_w);
5940 // and "clang -emit-llvm -c foo.s"
5941 Args.ClaimAllArgs(options::OPT_emit_llvm);
5942
5943 claimNoWarnArgs(Args);
5944
5945 // Invoke ourselves in -cc1as mode.
5946 //
5947 // FIXME: Implement custom jobs for internal actions.
5948 CmdArgs.push_back("-cc1as");
5949
5950 // Add the "effective" target triple.
5951 CmdArgs.push_back("-triple");
5952 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5953
5954 // Set the output mode, we currently only expect to be used as a real
5955 // assembler.
5956 CmdArgs.push_back("-filetype");
5957 CmdArgs.push_back("obj");
5958
5959 // Set the main file name, so that debug info works even with
5960 // -save-temps or preprocessed assembly.
5961 CmdArgs.push_back("-main-file-name");
5962 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5963
5964 // Add the target cpu
5965 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5966 if (!CPU.empty()) {
5967 CmdArgs.push_back("-target-cpu");
5968 CmdArgs.push_back(Args.MakeArgString(CPU));
5969 }
5970
5971 // Add the target features
5972 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5973
5974 // Ignore explicit -force_cpusubtype_ALL option.
5975 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5976
5977 // Pass along any -I options so we get proper .include search paths.
5978 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5979
5980 // Determine the original source input.
5981 const Action *SourceAction = &JA;
5982 while (SourceAction->getKind() != Action::InputClass) {
5983 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5984 SourceAction = SourceAction->getInputs()[0];
5985 }
5986
5987 // Forward -g and handle debug info related flags, assuming we are dealing
5988 // with an actual assembly file.
5989 bool WantDebug = false;
5990 unsigned DwarfVersion = 0;
5991 Args.ClaimAllArgs(options::OPT_g_Group);
5992 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5993 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5994 !A->getOption().matches(options::OPT_ggdb0);
5995 if (WantDebug)
5996 DwarfVersion = DwarfVersionNum(A->getSpelling());
5997 }
5998 if (DwarfVersion == 0)
5999 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6000
6001 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6002
6003 if (SourceAction->getType() == types::TY_Asm ||
6004 SourceAction->getType() == types::TY_PP_Asm) {
6005 // You might think that it would be ok to set DebugInfoKind outside of
6006 // the guard for source type, however there is a test which asserts
6007 // that some assembler invocation receives no -debug-info-kind,
6008 // and it's not clear whether that test is just overly restrictive.
6009 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6010 : codegenoptions::NoDebugInfo);
6011 // Add the -fdebug-compilation-dir flag if needed.
6012 addDebugCompDirArg(Args, CmdArgs);
6013
Paul Robinson9b292b42018-07-10 15:15:24 +00006014 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6015
David L. Jonesf561aba2017-03-08 01:02:16 +00006016 // Set the AT_producer to the clang version when using the integrated
6017 // assembler on assembly source files.
6018 CmdArgs.push_back("-dwarf-debug-producer");
6019 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6020
6021 // And pass along -I options
6022 Args.AddAllArgs(CmdArgs, options::OPT_I);
6023 }
6024 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6025 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006026 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006027
David L. Jonesf561aba2017-03-08 01:02:16 +00006028
6029 // Handle -fPIC et al -- the relocation-model affects the assembler
6030 // for some targets.
6031 llvm::Reloc::Model RelocationModel;
6032 unsigned PICLevel;
6033 bool IsPIE;
6034 std::tie(RelocationModel, PICLevel, IsPIE) =
6035 ParsePICArgs(getToolChain(), Args);
6036
6037 const char *RMName = RelocationModelName(RelocationModel);
6038 if (RMName) {
6039 CmdArgs.push_back("-mrelocation-model");
6040 CmdArgs.push_back(RMName);
6041 }
6042
6043 // Optionally embed the -cc1as level arguments into the debug info, for build
6044 // analysis.
6045 if (getToolChain().UseDwarfDebugFlags()) {
6046 ArgStringList OriginalArgs;
6047 for (const auto &Arg : Args)
6048 Arg->render(Args, OriginalArgs);
6049
6050 SmallString<256> Flags;
6051 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6052 Flags += Exec;
6053 for (const char *OriginalArg : OriginalArgs) {
6054 SmallString<128> EscapedArg;
6055 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6056 Flags += " ";
6057 Flags += EscapedArg;
6058 }
6059 CmdArgs.push_back("-dwarf-debug-flags");
6060 CmdArgs.push_back(Args.MakeArgString(Flags));
6061 }
6062
6063 // FIXME: Add -static support, once we have it.
6064
6065 // Add target specific flags.
6066 switch (getToolChain().getArch()) {
6067 default:
6068 break;
6069
6070 case llvm::Triple::mips:
6071 case llvm::Triple::mipsel:
6072 case llvm::Triple::mips64:
6073 case llvm::Triple::mips64el:
6074 AddMIPSTargetArgs(Args, CmdArgs);
6075 break;
6076
6077 case llvm::Triple::x86:
6078 case llvm::Triple::x86_64:
6079 AddX86TargetArgs(Args, CmdArgs);
6080 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006081
6082 case llvm::Triple::arm:
6083 case llvm::Triple::armeb:
6084 case llvm::Triple::thumb:
6085 case llvm::Triple::thumbeb:
6086 // This isn't in AddARMTargetArgs because we want to do this for assembly
6087 // only, not C/C++.
6088 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6089 options::OPT_mno_default_build_attributes, true)) {
6090 CmdArgs.push_back("-mllvm");
6091 CmdArgs.push_back("-arm-add-build-attributes");
6092 }
6093 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006094 }
6095
6096 // Consume all the warning flags. Usually this would be handled more
6097 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6098 // doesn't handle that so rather than warning about unused flags that are
6099 // actually used, we'll lie by omission instead.
6100 // FIXME: Stop lying and consume only the appropriate driver flags
6101 Args.ClaimAllArgs(options::OPT_W_Group);
6102
6103 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6104 getToolChain().getDriver());
6105
6106 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6107
6108 assert(Output.isFilename() && "Unexpected lipo output.");
6109 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006110 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006111
Petr Hosekd3265352018-10-15 21:30:32 +00006112 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006113 Arg *A;
6114 if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) &&
Petr Hosekd3265352018-10-15 21:30:32 +00006115 (T.isOSLinux() || T.isOSFuchsia())) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00006116 CmdArgs.push_back("-split-dwarf-file");
George Rimarab090332018-12-05 11:09:10 +00006117 CmdArgs.push_back(SplitDebugName(Args, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006118 }
6119
David L. Jonesf561aba2017-03-08 01:02:16 +00006120 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006121 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006122
6123 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6124 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006125}
6126
6127// Begin OffloadBundler
6128
6129void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6130 const InputInfo &Output,
6131 const InputInfoList &Inputs,
6132 const llvm::opt::ArgList &TCArgs,
6133 const char *LinkingOutput) const {
6134 // The version with only one output is expected to refer to a bundling job.
6135 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6136
6137 // The bundling command looks like this:
6138 // clang-offload-bundler -type=bc
6139 // -targets=host-triple,openmp-triple1,openmp-triple2
6140 // -outputs=input_file
6141 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6142
6143 ArgStringList CmdArgs;
6144
6145 // Get the type.
6146 CmdArgs.push_back(TCArgs.MakeArgString(
6147 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6148
6149 assert(JA.getInputs().size() == Inputs.size() &&
6150 "Not have inputs for all dependence actions??");
6151
6152 // Get the targets.
6153 SmallString<128> Triples;
6154 Triples += "-targets=";
6155 for (unsigned I = 0; I < Inputs.size(); ++I) {
6156 if (I)
6157 Triples += ',';
6158
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006159 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006160 Action::OffloadKind CurKind = Action::OFK_Host;
6161 const ToolChain *CurTC = &getToolChain();
6162 const Action *CurDep = JA.getInputs()[I];
6163
6164 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006165 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006166 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006167 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006168 CurKind = A->getOffloadingDeviceKind();
6169 CurTC = TC;
6170 });
6171 }
6172 Triples += Action::GetOffloadKindName(CurKind);
6173 Triples += '-';
6174 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006175 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6176 Triples += '-';
6177 Triples += CurDep->getOffloadingArch();
6178 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006179 }
6180 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6181
6182 // Get bundled file command.
6183 CmdArgs.push_back(
6184 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6185
6186 // Get unbundled files command.
6187 SmallString<128> UB;
6188 UB += "-inputs=";
6189 for (unsigned I = 0; I < Inputs.size(); ++I) {
6190 if (I)
6191 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006192
6193 // Find ToolChain for this input.
6194 const ToolChain *CurTC = &getToolChain();
6195 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6196 CurTC = nullptr;
6197 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6198 assert(CurTC == nullptr && "Expected one dependence!");
6199 CurTC = TC;
6200 });
6201 }
6202 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006203 }
6204 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6205
6206 // All the inputs are encoded as commands.
6207 C.addCommand(llvm::make_unique<Command>(
6208 JA, *this,
6209 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6210 CmdArgs, None));
6211}
6212
6213void OffloadBundler::ConstructJobMultipleOutputs(
6214 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6215 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6216 const char *LinkingOutput) const {
6217 // The version with multiple outputs is expected to refer to a unbundling job.
6218 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6219
6220 // The unbundling command looks like this:
6221 // clang-offload-bundler -type=bc
6222 // -targets=host-triple,openmp-triple1,openmp-triple2
6223 // -inputs=input_file
6224 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6225 // -unbundle
6226
6227 ArgStringList CmdArgs;
6228
6229 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6230 InputInfo Input = Inputs.front();
6231
6232 // Get the type.
6233 CmdArgs.push_back(TCArgs.MakeArgString(
6234 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6235
6236 // Get the targets.
6237 SmallString<128> Triples;
6238 Triples += "-targets=";
6239 auto DepInfo = UA.getDependentActionsInfo();
6240 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6241 if (I)
6242 Triples += ',';
6243
6244 auto &Dep = DepInfo[I];
6245 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6246 Triples += '-';
6247 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006248 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6249 !Dep.DependentBoundArch.empty()) {
6250 Triples += '-';
6251 Triples += Dep.DependentBoundArch;
6252 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006253 }
6254
6255 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6256
6257 // Get bundled file command.
6258 CmdArgs.push_back(
6259 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6260
6261 // Get unbundled files command.
6262 SmallString<128> UB;
6263 UB += "-outputs=";
6264 for (unsigned I = 0; I < Outputs.size(); ++I) {
6265 if (I)
6266 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006267 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006268 }
6269 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6270 CmdArgs.push_back("-unbundle");
6271
6272 // All the inputs are encoded as commands.
6273 C.addCommand(llvm::make_unique<Command>(
6274 JA, *this,
6275 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6276 CmdArgs, None));
6277}