blob: 07fededd3a15385d75ebebae65c419e285b8a0a0 [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"
Yuanfang Chenff22ec32019-07-20 22:50:50 +000025#include "clang/Basic/CodeGenOptions.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/ObjCRuntime.h"
28#include "clang/Basic/Version.h"
Michal Gornydae01c32018-12-23 15:07:26 +000029#include "clang/Driver/Distro.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000030#include "clang/Driver/DriverDiagnostic.h"
31#include "clang/Driver/Options.h"
32#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000033#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000035#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000036#include "llvm/Option/ArgList.h"
37#include "llvm/Support/CodeGen.h"
38#include "llvm/Support/Compression.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000042#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000043#include "llvm/Support/YAMLParser.h"
44
45#ifdef LLVM_ON_UNIX
46#include <unistd.h> // For getuid().
47#endif
48
49using namespace clang::driver;
50using namespace clang::driver::tools;
51using namespace clang;
52using namespace llvm::opt;
53
54static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
55 if (Arg *A =
56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60 << A->getBaseArg().getAsString(Args)
61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
62 }
63 }
64}
65
66static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67 // In gcc, only ARM checks this, but it seems reasonable to check universally.
68 if (Args.hasArg(options::OPT_static))
69 if (const Arg *A =
70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
72 << "-static";
73}
74
75// Add backslashes to escape spaces and other backslashes.
76// This is used for the space-separated argument list specified with
77// the -dwarf-debug-flags option.
78static void EscapeSpacesAndBackslashes(const char *Arg,
79 SmallVectorImpl<char> &Res) {
80 for (; *Arg; ++Arg) {
81 switch (*Arg) {
82 default:
83 break;
84 case ' ':
85 case '\\':
86 Res.push_back('\\');
87 break;
88 }
89 Res.push_back(*Arg);
90 }
91}
92
93// Quote target names for inclusion in GNU Make dependency files.
94// Only the characters '$', '#', ' ', '\t' are quoted.
95static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
97 switch (Target[i]) {
98 case ' ':
99 case '\t':
100 // Escape the preceding backslashes
101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
102 Res.push_back('\\');
103
104 // Escape the space/tab
105 Res.push_back('\\');
106 break;
107 case '$':
108 Res.push_back('$');
109 break;
110 case '#':
111 Res.push_back('\\');
112 break;
113 default:
114 break;
115 }
116
117 Res.push_back(Target[i]);
118 }
119}
120
121/// Apply \a Work on the current tool chain \a RegularToolChain and any other
122/// offloading tool chain that is associated with the current action \a JA.
123static void
124forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125 const ToolChain &RegularToolChain,
126 llvm::function_ref<void(const ToolChain &)> Work) {
127 // Apply Work on the current/regular tool chain.
128 Work(RegularToolChain);
129
130 // Apply Work on all the offloading tool chains associated with the current
131 // action.
132 if (JA.isHostOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000136 else if (JA.isHostOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138 else if (JA.isDeviceOffloading(Action::OFK_HIP))
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000140
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000141 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
144 Work(*II->second);
145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
147
David L. Jonesf561aba2017-03-08 01:02:16 +0000148 //
149 // TODO: Add support for other offloading programming models here.
150 //
151}
152
153/// This is a helper function for validating the optional refinement step
154/// parameter in reciprocal argument strings. Return false if there is an error
155/// parsing the refinement step. Otherwise, return true and set the Position
156/// of the refinement step in the input string.
157static bool getRefinementStep(StringRef In, const Driver &D,
158 const Arg &A, size_t &Position) {
159 const char RefinementStepToken = ':';
160 Position = In.find(RefinementStepToken);
161 if (Position != StringRef::npos) {
162 StringRef Option = A.getOption().getName();
163 StringRef RefStep = In.substr(Position + 1);
164 // Allow exactly one numeric character for the additional refinement
165 // step parameter. This is reasonable for all currently-supported
166 // operations and architectures because we would expect that a larger value
167 // of refinement steps would cause the estimate "optimization" to
168 // under-perform the native operation. Also, if the estimate does not
169 // converge quickly, it probably will not ever converge, so further
170 // refinement steps will not produce a better answer.
171 if (RefStep.size() != 1) {
172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
173 return false;
174 }
175 char RefStepChar = RefStep[0];
176 if (RefStepChar < '0' || RefStepChar > '9') {
177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
178 return false;
179 }
180 }
181 return true;
182}
183
184/// The -mrecip flag requires processing of many optional parameters.
185static void ParseMRecip(const Driver &D, const ArgList &Args,
186 ArgStringList &OutStrings) {
187 StringRef DisabledPrefixIn = "!";
188 StringRef DisabledPrefixOut = "!";
189 StringRef EnabledPrefixOut = "";
190 StringRef Out = "-mrecip=";
191
192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
193 if (!A)
194 return;
195
196 unsigned NumOptions = A->getNumValues();
197 if (NumOptions == 0) {
198 // No option is the same as "all".
199 OutStrings.push_back(Args.MakeArgString(Out + "all"));
200 return;
201 }
202
203 // Pass through "all", "none", or "default" with an optional refinement step.
204 if (NumOptions == 1) {
205 StringRef Val = A->getValue(0);
206 size_t RefStepLoc;
207 if (!getRefinementStep(Val, D, *A, RefStepLoc))
208 return;
209 StringRef ValBase = Val.slice(0, RefStepLoc);
210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211 OutStrings.push_back(Args.MakeArgString(Out + Val));
212 return;
213 }
214 }
215
216 // Each reciprocal type may be enabled or disabled individually.
217 // Check each input value for validity, concatenate them all back together,
218 // and pass through.
219
220 llvm::StringMap<bool> OptionStrings;
221 OptionStrings.insert(std::make_pair("divd", false));
222 OptionStrings.insert(std::make_pair("divf", false));
223 OptionStrings.insert(std::make_pair("vec-divd", false));
224 OptionStrings.insert(std::make_pair("vec-divf", false));
225 OptionStrings.insert(std::make_pair("sqrtd", false));
226 OptionStrings.insert(std::make_pair("sqrtf", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
229
230 for (unsigned i = 0; i != NumOptions; ++i) {
231 StringRef Val = A->getValue(i);
232
233 bool IsDisabled = Val.startswith(DisabledPrefixIn);
234 // Ignore the disablement token for string matching.
235 if (IsDisabled)
236 Val = Val.substr(1);
237
238 size_t RefStep;
239 if (!getRefinementStep(Val, D, *A, RefStep))
240 return;
241
242 StringRef ValBase = Val.slice(0, RefStep);
243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244 if (OptionIter == OptionStrings.end()) {
245 // Try again specifying float suffix.
246 OptionIter = OptionStrings.find(ValBase.str() + 'f');
247 if (OptionIter == OptionStrings.end()) {
248 // The input name did not match any known option string.
249 D.Diag(diag::err_drv_unknown_argument) << Val;
250 return;
251 }
252 // The option was specified without a float or double suffix.
253 // Make sure that the double entry was not already specified.
254 // The float entry will be checked below.
255 if (OptionStrings[ValBase.str() + 'd']) {
256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
257 return;
258 }
259 }
260
261 if (OptionIter->second == true) {
262 // Duplicate option specified.
263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
264 return;
265 }
266
267 // Mark the matched option as found. Do not allow duplicate specifiers.
268 OptionIter->second = true;
269
270 // If the precision was not specified, also mark the double entry as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd')
272 OptionStrings[ValBase.str() + 'd'] = true;
273
274 // Build the output string.
275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276 Out = Args.MakeArgString(Out + Prefix + Val);
277 if (i != NumOptions - 1)
278 Out = Args.MakeArgString(Out + ",");
279 }
280
281 OutStrings.push_back(Args.MakeArgString(Out));
282}
283
Craig Topper9a724aa2017-12-11 21:09:19 +0000284/// The -mprefer-vector-width option accepts either a positive integer
285/// or the string "none".
286static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287 ArgStringList &CmdArgs) {
288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
289 if (!A)
290 return;
291
292 StringRef Value = A->getValue();
293 if (Value == "none") {
294 CmdArgs.push_back("-mprefer-vector-width=none");
295 } else {
296 unsigned Width;
297 if (Value.getAsInteger(10, Width)) {
298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
299 return;
300 }
301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302 }
303}
304
David L. Jonesf561aba2017-03-08 01:02:16 +0000305static void getWebAssemblyTargetFeatures(const ArgList &Args,
306 std::vector<StringRef> &Features) {
307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308}
309
David L. Jonesf561aba2017-03-08 01:02:16 +0000310static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
311 const ArgList &Args, ArgStringList &CmdArgs,
312 bool ForAS) {
313 const Driver &D = TC.getDriver();
314 std::vector<StringRef> Features;
315 switch (Triple.getArch()) {
316 default:
317 break;
318 case llvm::Triple::mips:
319 case llvm::Triple::mipsel:
320 case llvm::Triple::mips64:
321 case llvm::Triple::mips64el:
322 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
323 break;
324
325 case llvm::Triple::arm:
326 case llvm::Triple::armeb:
327 case llvm::Triple::thumb:
328 case llvm::Triple::thumbeb:
329 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
330 break;
331
332 case llvm::Triple::ppc:
333 case llvm::Triple::ppc64:
334 case llvm::Triple::ppc64le:
335 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
336 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000337 case llvm::Triple::riscv32:
338 case llvm::Triple::riscv64:
339 riscv::getRISCVTargetFeatures(D, Args, Features);
340 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000341 case llvm::Triple::systemz:
342 systemz::getSystemZTargetFeatures(Args, Features);
343 break;
344 case llvm::Triple::aarch64:
345 case llvm::Triple::aarch64_be:
Alex Lorenz9b20a992018-12-17 19:30:46 +0000346 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000347 break;
348 case llvm::Triple::x86:
349 case llvm::Triple::x86_64:
350 x86::getX86TargetFeatures(D, Triple, Args, Features);
351 break;
352 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000353 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000354 break;
355 case llvm::Triple::wasm32:
356 case llvm::Triple::wasm64:
357 getWebAssemblyTargetFeatures(Args, Features);
358 break;
359 case llvm::Triple::sparc:
360 case llvm::Triple::sparcel:
361 case llvm::Triple::sparcv9:
362 sparc::getSparcTargetFeatures(D, Args, Features);
363 break;
364 case llvm::Triple::r600:
365 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000366 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000367 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +0000368 case llvm::Triple::msp430:
369 msp430::getMSP430TargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000370 }
371
372 // Find the last of each feature.
373 llvm::StringMap<unsigned> LastOpt;
374 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
375 StringRef Name = Features[I];
376 assert(Name[0] == '-' || Name[0] == '+');
377 LastOpt[Name.drop_front(1)] = I;
378 }
379
380 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
381 // If this feature was overridden, ignore it.
382 StringRef Name = Features[I];
383 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
384 assert(LastI != LastOpt.end());
385 unsigned Last = LastI->second;
386 if (Last != I)
387 continue;
388
389 CmdArgs.push_back("-target-feature");
390 CmdArgs.push_back(Name.data());
391 }
392}
393
394static bool
395shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
396 const llvm::Triple &Triple) {
397 // We use the zero-cost exception tables for Objective-C if the non-fragile
398 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
399 // later.
400 if (runtime.isNonFragile())
401 return true;
402
403 if (!Triple.isMacOSX())
404 return false;
405
406 return (!Triple.isMacOSXVersionLT(10, 5) &&
407 (Triple.getArch() == llvm::Triple::x86_64 ||
408 Triple.getArch() == llvm::Triple::arm));
409}
410
411/// Adds exception related arguments to the driver command arguments. There's a
412/// master flag, -fexceptions and also language specific flags to enable/disable
413/// C++ and Objective-C exceptions. This makes it possible to for example
414/// disable C++ exceptions but enable Objective-C exceptions.
415static void addExceptionArgs(const ArgList &Args, types::ID InputType,
416 const ToolChain &TC, bool KernelOrKext,
417 const ObjCRuntime &objcRuntime,
418 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000419 const llvm::Triple &Triple = TC.getTriple();
420
421 if (KernelOrKext) {
422 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
423 // arguments now to avoid warnings about unused arguments.
424 Args.ClaimAllArgs(options::OPT_fexceptions);
425 Args.ClaimAllArgs(options::OPT_fno_exceptions);
426 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
428 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
429 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
430 return;
431 }
432
433 // See if the user explicitly enabled exceptions.
434 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
435 false);
436
437 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
438 // is not necessarily sensible, but follows GCC.
439 if (types::isObjC(InputType) &&
440 Args.hasFlag(options::OPT_fobjc_exceptions,
441 options::OPT_fno_objc_exceptions, true)) {
442 CmdArgs.push_back("-fobjc-exceptions");
443
444 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
445 }
446
447 if (types::isCXX(InputType)) {
448 // Disable C++ EH by default on XCore and PS4.
449 bool CXXExceptionsEnabled =
450 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
451 Arg *ExceptionArg = Args.getLastArg(
452 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
453 options::OPT_fexceptions, options::OPT_fno_exceptions);
454 if (ExceptionArg)
455 CXXExceptionsEnabled =
456 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
457 ExceptionArg->getOption().matches(options::OPT_fexceptions);
458
459 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000460 CmdArgs.push_back("-fcxx-exceptions");
461
462 EH = true;
463 }
464 }
465
466 if (EH)
467 CmdArgs.push_back("-fexceptions");
468}
469
470static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
471 bool Default = true;
472 if (TC.getTriple().isOSDarwin()) {
473 // The native darwin assembler doesn't support the linker_option directives,
474 // so we disable them if we think the .s file will be passed to it.
475 Default = TC.useIntegratedAs();
476 }
477 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
478 Default);
479}
480
481static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482 const ToolChain &TC) {
483 bool UseDwarfDirectory =
484 Args.hasFlag(options::OPT_fdwarf_directory_asm,
485 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486 return !UseDwarfDirectory;
487}
488
489// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490// to the corresponding DebugInfoKind.
491static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492 assert(A.getOption().matches(options::OPT_gN_Group) &&
493 "Not a -g option that specifies a debug-info level");
494 if (A.getOption().matches(options::OPT_g0) ||
495 A.getOption().matches(options::OPT_ggdb0))
496 return codegenoptions::NoDebugInfo;
497 if (A.getOption().matches(options::OPT_gline_tables_only) ||
498 A.getOption().matches(options::OPT_ggdb1))
499 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000500 if (A.getOption().matches(options::OPT_gline_directives_only))
501 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000502 return codegenoptions::LimitedDebugInfo;
503}
504
505static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506 switch (Triple.getArch()){
507 default:
508 return false;
509 case llvm::Triple::arm:
510 case llvm::Triple::thumb:
511 // ARM Darwin targets require a frame pointer to be always present to aid
512 // offline debugging via backtraces.
513 return Triple.isOSDarwin();
514 }
515}
516
517static bool useFramePointerForTargetByDefault(const ArgList &Args,
518 const llvm::Triple &Triple) {
Fangrui Songdc039662019-07-12 02:01:51 +0000519 if (Args.hasArg(options::OPT_pg))
520 return true;
521
David L. Jonesf561aba2017-03-08 01:02:16 +0000522 switch (Triple.getArch()) {
523 case llvm::Triple::xcore:
524 case llvm::Triple::wasm32:
525 case llvm::Triple::wasm64:
Anton Korobeynikovf1f897c2019-02-05 20:15:03 +0000526 case llvm::Triple::msp430:
David L. Jonesf561aba2017-03-08 01:02:16 +0000527 // XCore never wants frame pointers, regardless of OS.
528 // WebAssembly never wants frame pointers.
529 return false;
Fangrui Song8c0b58f2019-07-12 02:14:08 +0000530 case llvm::Triple::ppc:
531 case llvm::Triple::ppc64:
532 case llvm::Triple::ppc64le:
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000533 case llvm::Triple::riscv32:
534 case llvm::Triple::riscv64:
535 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000536 default:
537 break;
538 }
539
Michal Gorny5a409d02018-12-20 13:09:30 +0000540 if (Triple.isOSNetBSD()) {
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000541 return !areOptimizationsEnabled(Args);
542 }
543
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000544 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
545 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000546 switch (Triple.getArch()) {
547 // Don't use a frame pointer on linux if optimizing for certain targets.
548 case llvm::Triple::mips64:
549 case llvm::Triple::mips64el:
550 case llvm::Triple::mips:
551 case llvm::Triple::mipsel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000552 case llvm::Triple::systemz:
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 return !areOptimizationsEnabled(Args);
556 default:
557 return true;
558 }
559 }
560
561 if (Triple.isOSWindows()) {
562 switch (Triple.getArch()) {
563 case llvm::Triple::x86:
564 return !areOptimizationsEnabled(Args);
565 case llvm::Triple::x86_64:
566 return Triple.isOSBinFormatMachO();
567 case llvm::Triple::arm:
568 case llvm::Triple::thumb:
569 // Windows on ARM builds with FPO disabled to aid fast stack walking
570 return true;
571 default:
572 // All other supported Windows ISAs use xdata unwind information, so frame
573 // pointers are not generally useful.
574 return false;
575 }
576 }
577
578 return true;
579}
580
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000581static CodeGenOptions::FramePointerKind
582getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
Fangrui Songdc039662019-07-12 02:01:51 +0000583 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
584 options::OPT_fno_omit_frame_pointer);
585 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
586 bool NoOmitFP =
587 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
588 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
589 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
590 if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
591 options::OPT_mno_omit_leaf_frame_pointer,
592 Triple.isPS4CPU()))
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000593 return CodeGenOptions::FramePointerKind::NonLeaf;
594 return CodeGenOptions::FramePointerKind::All;
Fangrui Songdc039662019-07-12 02:01:51 +0000595 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000596 return CodeGenOptions::FramePointerKind::None;
David L. Jonesf561aba2017-03-08 01:02:16 +0000597}
598
599/// Add a CC1 option to specify the debug compilation directory.
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000600static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
601 const llvm::vfs::FileSystem &VFS) {
Nico Weber37b75332019-06-17 12:10:40 +0000602 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
603 CmdArgs.push_back("-fdebug-compilation-dir");
604 CmdArgs.push_back(A->getValue());
605 } else if (llvm::ErrorOr<std::string> CWD =
606 VFS.getCurrentWorkingDirectory()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000607 CmdArgs.push_back("-fdebug-compilation-dir");
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000608 CmdArgs.push_back(Args.MakeArgString(*CWD));
David L. Jonesf561aba2017-03-08 01:02:16 +0000609 }
610}
611
Paul Robinson9b292b42018-07-10 15:15:24 +0000612/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
613static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
614 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
615 StringRef Map = A->getValue();
616 if (Map.find('=') == StringRef::npos)
617 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
618 else
619 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
620 A->claim();
621 }
622}
623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000624/// Vectorize at all optimization levels greater than 1 except for -Oz.
Nico Weber37b75332019-06-17 12:10:40 +0000625/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
626/// enabled.
David L. Jonesf561aba2017-03-08 01:02:16 +0000627static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
628 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
629 if (A->getOption().matches(options::OPT_O4) ||
630 A->getOption().matches(options::OPT_Ofast))
631 return true;
632
633 if (A->getOption().matches(options::OPT_O0))
634 return false;
635
636 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
637
638 // Vectorize -Os.
639 StringRef S(A->getValue());
640 if (S == "s")
641 return true;
642
643 // Don't vectorize -Oz, unless it's the slp vectorizer.
644 if (S == "z")
645 return isSlpVec;
646
647 unsigned OptLevel = 0;
648 if (S.getAsInteger(10, OptLevel))
649 return false;
650
651 return OptLevel > 1;
652 }
653
654 return false;
655}
656
657/// Add -x lang to \p CmdArgs for \p Input.
658static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
659 ArgStringList &CmdArgs) {
660 // When using -verify-pch, we don't want to provide the type
661 // 'precompiled-header' if it was inferred from the file extension
662 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
663 return;
664
665 CmdArgs.push_back("-x");
666 if (Args.hasArg(options::OPT_rewrite_objc))
667 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000668 else {
669 // Map the driver type to the frontend type. This is mostly an identity
670 // mapping, except that the distinction between module interface units
671 // and other source files does not exist at the frontend layer.
672 const char *ClangType;
673 switch (Input.getType()) {
674 case types::TY_CXXModule:
675 ClangType = "c++";
676 break;
677 case types::TY_PP_CXXModule:
678 ClangType = "c++-cpp-output";
679 break;
680 default:
681 ClangType = types::getTypeName(Input.getType());
682 break;
683 }
684 CmdArgs.push_back(ClangType);
685 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000686}
687
688static void appendUserToPath(SmallVectorImpl<char> &Result) {
689#ifdef LLVM_ON_UNIX
690 const char *Username = getenv("LOGNAME");
691#else
692 const char *Username = getenv("USERNAME");
693#endif
694 if (Username) {
695 // Validate that LoginName can be used in a path, and get its length.
696 size_t Len = 0;
697 for (const char *P = Username; *P; ++P, ++Len) {
698 if (!clang::isAlphanumeric(*P) && *P != '_') {
699 Username = nullptr;
700 break;
701 }
702 }
703
704 if (Username && Len > 0) {
705 Result.append(Username, Username + Len);
706 return;
707 }
708 }
709
710// Fallback to user id.
711#ifdef LLVM_ON_UNIX
712 std::string UID = llvm::utostr(getuid());
713#else
714 // FIXME: Windows seems to have an 'SID' that might work.
715 std::string UID = "9999";
716#endif
717 Result.append(UID.begin(), UID.end());
718}
719
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000720static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
721 const Driver &D, const InputInfo &Output,
722 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000723 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");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000773 if (TC.getTriple().isWindowsMSVCEnvironment()) {
774 // Add dependent lib for clang_rt.profile
775 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
776 TC.getCompilerRT(Args, "profile")));
777 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000778 }
779
Rong Xua4a09b22019-03-04 20:21:31 +0000780 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000781 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000782 assert(!CSPGOGenerateArg);
783 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000784 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000785 }
786 if (CSPGOGenerateArg) {
787 assert(!PGOGenerateArg);
788 PGOGenArg = CSPGOGenerateArg;
789 CmdArgs.push_back("-fprofile-instrument=csllvm");
790 }
791 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000792 if (TC.getTriple().isWindowsMSVCEnvironment()) {
793 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
794 TC.getCompilerRT(Args, "profile")));
795 }
Rong Xua4a09b22019-03-04 20:21:31 +0000796 if (PGOGenArg->getOption().matches(
797 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
798 : options::OPT_fcs_profile_generate_EQ)) {
799 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 llvm::sys::path::append(Path, "default_%m.profraw");
801 CmdArgs.push_back(
802 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
803 }
804 }
805
806 if (ProfileUseArg) {
807 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
808 CmdArgs.push_back(Args.MakeArgString(
809 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
810 else if ((ProfileUseArg->getOption().matches(
811 options::OPT_fprofile_use_EQ) ||
812 ProfileUseArg->getOption().matches(
813 options::OPT_fprofile_instr_use))) {
814 SmallString<128> Path(
815 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
816 if (Path.empty() || llvm::sys::fs::is_directory(Path))
817 llvm::sys::path::append(Path, "default.profdata");
818 CmdArgs.push_back(
819 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
820 }
821 }
822
823 if (Args.hasArg(options::OPT_ftest_coverage) ||
824 Args.hasArg(options::OPT_coverage))
825 CmdArgs.push_back("-femit-coverage-notes");
826 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
827 false) ||
828 Args.hasArg(options::OPT_coverage))
829 CmdArgs.push_back("-femit-coverage-data");
830
831 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000832 options::OPT_fno_coverage_mapping, false)) {
833 if (!ProfileGenerateArg)
834 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
835 << "-fcoverage-mapping"
836 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000837
David L. Jonesf561aba2017-03-08 01:02:16 +0000838 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000839 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000840
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000841 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
842 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
843 if (!Args.hasArg(options::OPT_coverage))
844 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
845 << "-fprofile-exclude-files="
846 << "--coverage";
847
848 StringRef v = Arg->getValue();
849 CmdArgs.push_back(
850 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
851 }
852
853 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
854 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
855 if (!Args.hasArg(options::OPT_coverage))
856 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
857 << "-fprofile-filter-files="
858 << "--coverage";
859
860 StringRef v = Arg->getValue();
861 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
862 }
863
David L. Jonesf561aba2017-03-08 01:02:16 +0000864 if (C.getArgs().hasArg(options::OPT_c) ||
865 C.getArgs().hasArg(options::OPT_S)) {
866 if (Output.isFilename()) {
867 CmdArgs.push_back("-coverage-notes-file");
868 SmallString<128> OutputFilename;
869 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
870 OutputFilename = FinalOutput->getValue();
871 else
872 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
873 SmallString<128> CoverageFilename = OutputFilename;
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000874 if (llvm::sys::path::is_relative(CoverageFilename))
875 (void)D.getVFS().makeAbsolute(CoverageFilename);
David L. Jonesf561aba2017-03-08 01:02:16 +0000876 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
877 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
878
879 // Leave -fprofile-dir= an unused argument unless .gcda emission is
880 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
881 // the flag used. There is no -fno-profile-dir, so the user has no
882 // targeted way to suppress the warning.
883 if (Args.hasArg(options::OPT_fprofile_arcs) ||
884 Args.hasArg(options::OPT_coverage)) {
885 CmdArgs.push_back("-coverage-data-file");
886 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
887 CoverageFilename = FProfileDir->getValue();
888 llvm::sys::path::append(CoverageFilename, OutputFilename);
889 }
890 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
891 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
892 }
893 }
894 }
895}
896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000897/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000898static bool ContainsCompileAction(const Action *A) {
899 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
900 return true;
901
902 for (const auto &AI : A->inputs())
903 if (ContainsCompileAction(AI))
904 return true;
905
906 return false;
907}
908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000909/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000910/// This is done by default when compiling non-assembler source with -O0.
911static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
912 bool RelaxDefault = true;
913
914 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
915 RelaxDefault = A->getOption().matches(options::OPT_O0);
916
917 if (RelaxDefault) {
918 RelaxDefault = false;
919 for (const auto &Act : C.getActions()) {
920 if (ContainsCompileAction(Act)) {
921 RelaxDefault = true;
922 break;
923 }
924 }
925 }
926
927 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
928 RelaxDefault);
929}
930
931// Extract the integer N from a string spelled "-dwarf-N", returning 0
932// on mismatch. The StringRef input (rather than an Arg) allows
933// for use by the "-Xassembler" option parser.
934static unsigned DwarfVersionNum(StringRef ArgValue) {
935 return llvm::StringSwitch<unsigned>(ArgValue)
936 .Case("-gdwarf-2", 2)
937 .Case("-gdwarf-3", 3)
938 .Case("-gdwarf-4", 4)
939 .Case("-gdwarf-5", 5)
940 .Default(0);
941}
942
943static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
944 codegenoptions::DebugInfoKind DebugInfoKind,
945 unsigned DwarfVersion,
946 llvm::DebuggerKind DebuggerTuning) {
947 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000948 case codegenoptions::DebugDirectivesOnly:
949 CmdArgs.push_back("-debug-info-kind=line-directives-only");
950 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000951 case codegenoptions::DebugLineTablesOnly:
952 CmdArgs.push_back("-debug-info-kind=line-tables-only");
953 break;
954 case codegenoptions::LimitedDebugInfo:
955 CmdArgs.push_back("-debug-info-kind=limited");
956 break;
957 case codegenoptions::FullDebugInfo:
958 CmdArgs.push_back("-debug-info-kind=standalone");
959 break;
960 default:
961 break;
962 }
963 if (DwarfVersion > 0)
964 CmdArgs.push_back(
965 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
966 switch (DebuggerTuning) {
967 case llvm::DebuggerKind::GDB:
968 CmdArgs.push_back("-debugger-tuning=gdb");
969 break;
970 case llvm::DebuggerKind::LLDB:
971 CmdArgs.push_back("-debugger-tuning=lldb");
972 break;
973 case llvm::DebuggerKind::SCE:
974 CmdArgs.push_back("-debugger-tuning=sce");
975 break;
976 default:
977 break;
978 }
979}
980
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000981static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
982 const Driver &D, const ToolChain &TC) {
983 assert(A && "Expected non-nullptr argument.");
984 if (TC.supportsDebugInfoOption(A))
985 return true;
986 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
987 << A->getAsString(Args) << TC.getTripleString();
988 return false;
989}
990
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000991static void RenderDebugInfoCompressionArgs(const ArgList &Args,
992 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000993 const Driver &D,
994 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000995 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
996 if (!A)
997 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000998 if (checkDebugInfoOption(A, Args, D, TC)) {
999 if (A->getOption().getID() == options::OPT_gz) {
1000 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001001 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001002 else
1003 D.Diag(diag::warn_debug_compression_unavailable);
1004 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001005 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001006
1007 StringRef Value = A->getValue();
1008 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001009 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001010 } else if (Value == "zlib" || Value == "zlib-gnu") {
1011 if (llvm::zlib::isAvailable()) {
1012 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001013 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001014 } else {
1015 D.Diag(diag::warn_debug_compression_unavailable);
1016 }
1017 } else {
1018 D.Diag(diag::err_drv_unsupported_option_argument)
1019 << A->getOption().getName() << Value;
1020 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001021 }
1022}
1023
David L. Jonesf561aba2017-03-08 01:02:16 +00001024static const char *RelocationModelName(llvm::Reloc::Model Model) {
1025 switch (Model) {
1026 case llvm::Reloc::Static:
1027 return "static";
1028 case llvm::Reloc::PIC_:
1029 return "pic";
1030 case llvm::Reloc::DynamicNoPIC:
1031 return "dynamic-no-pic";
1032 case llvm::Reloc::ROPI:
1033 return "ropi";
1034 case llvm::Reloc::RWPI:
1035 return "rwpi";
1036 case llvm::Reloc::ROPI_RWPI:
1037 return "ropi-rwpi";
1038 }
1039 llvm_unreachable("Unknown Reloc::Model kind");
1040}
1041
1042void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1043 const Driver &D, const ArgList &Args,
1044 ArgStringList &CmdArgs,
1045 const InputInfo &Output,
1046 const InputInfoList &Inputs) const {
1047 Arg *A;
1048 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1049
1050 CheckPreprocessingOptions(D, Args);
1051
1052 Args.AddLastArg(CmdArgs, options::OPT_C);
1053 Args.AddLastArg(CmdArgs, options::OPT_CC);
1054
1055 // Handle dependency file generation.
1056 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1057 (A = Args.getLastArg(options::OPT_MD)) ||
1058 (A = Args.getLastArg(options::OPT_MMD))) {
1059 // Determine the output location.
1060 const char *DepFile;
1061 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1062 DepFile = MF->getValue();
1063 C.addFailureResultFile(DepFile, &JA);
1064 } else if (Output.getType() == types::TY_Dependencies) {
1065 DepFile = Output.getFilename();
1066 } else if (A->getOption().matches(options::OPT_M) ||
1067 A->getOption().matches(options::OPT_MM)) {
1068 DepFile = "-";
1069 } else {
1070 DepFile = getDependencyFileName(Args, Inputs);
1071 C.addFailureResultFile(DepFile, &JA);
1072 }
1073 CmdArgs.push_back("-dependency-file");
1074 CmdArgs.push_back(DepFile);
1075
1076 // Add a default target if one wasn't specified.
1077 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1078 const char *DepTarget;
1079
1080 // If user provided -o, that is the dependency target, except
1081 // when we are only generating a dependency file.
1082 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1083 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1084 DepTarget = OutputOpt->getValue();
1085 } else {
1086 // Otherwise derive from the base input.
1087 //
1088 // FIXME: This should use the computed output file location.
1089 SmallString<128> P(Inputs[0].getBaseInput());
1090 llvm::sys::path::replace_extension(P, "o");
1091 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1092 }
1093
Yuka Takahashicdb53482017-06-16 16:01:13 +00001094 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1095 CmdArgs.push_back("-w");
1096 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001097 CmdArgs.push_back("-MT");
1098 SmallString<128> Quoted;
1099 QuoteTarget(DepTarget, Quoted);
1100 CmdArgs.push_back(Args.MakeArgString(Quoted));
1101 }
1102
1103 if (A->getOption().matches(options::OPT_M) ||
1104 A->getOption().matches(options::OPT_MD))
1105 CmdArgs.push_back("-sys-header-deps");
1106 if ((isa<PrecompileJobAction>(JA) &&
1107 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1108 Args.hasArg(options::OPT_fmodule_file_deps))
1109 CmdArgs.push_back("-module-file-deps");
1110 }
1111
1112 if (Args.hasArg(options::OPT_MG)) {
1113 if (!A || A->getOption().matches(options::OPT_MD) ||
1114 A->getOption().matches(options::OPT_MMD))
1115 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1116 CmdArgs.push_back("-MG");
1117 }
1118
1119 Args.AddLastArg(CmdArgs, options::OPT_MP);
1120 Args.AddLastArg(CmdArgs, options::OPT_MV);
1121
1122 // Convert all -MQ <target> args to -MT <quoted target>
1123 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1124 A->claim();
1125
1126 if (A->getOption().matches(options::OPT_MQ)) {
1127 CmdArgs.push_back("-MT");
1128 SmallString<128> Quoted;
1129 QuoteTarget(A->getValue(), Quoted);
1130 CmdArgs.push_back(Args.MakeArgString(Quoted));
1131
1132 // -MT flag - no change
1133 } else {
1134 A->render(Args, CmdArgs);
1135 }
1136 }
1137
1138 // Add offload include arguments specific for CUDA. This must happen before
1139 // we -I or -include anything else, because we must pick up the CUDA headers
1140 // from the particular CUDA installation, rather than from e.g.
1141 // /usr/local/include.
1142 if (JA.isOffloading(Action::OFK_Cuda))
1143 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1144
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001145 // If we are offloading to a target via OpenMP we need to include the
1146 // openmp_wrappers folder which contains alternative system headers.
1147 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1148 getToolChain().getTriple().isNVPTX()){
1149 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1150 // Add openmp_wrappers/* to our system include path. This lets us wrap
1151 // standard library headers.
1152 SmallString<128> P(D.ResourceDir);
1153 llvm::sys::path::append(P, "include");
1154 llvm::sys::path::append(P, "openmp_wrappers");
1155 CmdArgs.push_back("-internal-isystem");
1156 CmdArgs.push_back(Args.MakeArgString(P));
1157 }
1158
1159 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001160 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001161 }
1162
David L. Jonesf561aba2017-03-08 01:02:16 +00001163 // Add -i* options, and automatically translate to
1164 // -include-pch/-include-pth for transparent PCH support. It's
1165 // wonky, but we include looking for .gch so we can support seamless
1166 // replacement into a build system already set up to be generating
1167 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001168
1169 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001170 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1171 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001172 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1173 JA.getKind() <= Action::AssembleJobClass) {
1174 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001175 }
Erich Keane76675de2018-07-05 17:22:13 +00001176 if (YcArg || YuArg) {
1177 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1178 if (!isa<PrecompileJobAction>(JA)) {
1179 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001180 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1181 C, !ThroughHeader.empty()
1182 ? ThroughHeader
1183 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001184 }
Mike Rice58df1af2018-09-11 17:10:44 +00001185
1186 if (ThroughHeader.empty()) {
1187 CmdArgs.push_back(Args.MakeArgString(
1188 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1189 } else {
1190 CmdArgs.push_back(
1191 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1192 }
Erich Keane76675de2018-07-05 17:22:13 +00001193 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001194 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001195
1196 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001197 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001198 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001199 // Handling of gcc-style gch precompiled headers.
1200 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1201 RenderedImplicitInclude = true;
1202
David L. Jonesf561aba2017-03-08 01:02:16 +00001203 bool FoundPCH = false;
1204 SmallString<128> P(A->getValue());
1205 // We want the files to have a name like foo.h.pch. Add a dummy extension
1206 // so that replace_extension does the right thing.
1207 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001208 llvm::sys::path::replace_extension(P, "pch");
1209 if (llvm::sys::fs::exists(P))
1210 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001211
1212 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001213 llvm::sys::path::replace_extension(P, "gch");
1214 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001215 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001216 }
1217 }
1218
Erich Keane0a6b5b62018-12-04 14:34:09 +00001219 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001220 if (IsFirstImplicitInclude) {
1221 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001222 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001223 CmdArgs.push_back(Args.MakeArgString(P));
1224 continue;
1225 } else {
1226 // Ignore the PCH if not first on command line and emit warning.
1227 D.Diag(diag::warn_drv_pch_not_first_include) << P
1228 << A->getAsString(Args);
1229 }
1230 }
1231 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1232 // Handling of paths which must come late. These entries are handled by
1233 // the toolchain itself after the resource dir is inserted in the right
1234 // search order.
1235 // Do not claim the argument so that the use of the argument does not
1236 // silently go unnoticed on toolchains which do not honour the option.
1237 continue;
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001238 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1239 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1240 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00001241 }
1242
1243 // Not translated, render as usual.
1244 A->claim();
1245 A->render(Args, CmdArgs);
1246 }
1247
1248 Args.AddAllArgs(CmdArgs,
1249 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1250 options::OPT_F, options::OPT_index_header_map});
1251
1252 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1253
1254 // FIXME: There is a very unfortunate problem here, some troubled
1255 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1256 // really support that we would have to parse and then translate
1257 // those options. :(
1258 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1259 options::OPT_Xpreprocessor);
1260
1261 // -I- is a deprecated GCC feature, reject it.
1262 if (Arg *A = Args.getLastArg(options::OPT_I_))
1263 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1264
1265 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1266 // -isysroot to the CC1 invocation.
1267 StringRef sysroot = C.getSysRoot();
1268 if (sysroot != "") {
1269 if (!Args.hasArg(options::OPT_isysroot)) {
1270 CmdArgs.push_back("-isysroot");
1271 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1272 }
1273 }
1274
1275 // Parse additional include paths from environment variables.
1276 // FIXME: We should probably sink the logic for handling these from the
1277 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1278 // CPATH - included following the user specified includes (but prior to
1279 // builtin and standard includes).
1280 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1281 // C_INCLUDE_PATH - system includes enabled when compiling C.
1282 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1283 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1284 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1285 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1286 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1287 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1288 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1289
1290 // While adding the include arguments, we also attempt to retrieve the
1291 // arguments of related offloading toolchains or arguments that are specific
1292 // of an offloading programming model.
1293
1294 // Add C++ include arguments, if needed.
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001295 if (types::isCXX(Inputs[0].getType())) {
1296 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1297 forAllAssociatedToolChains(
1298 C, JA, getToolChain(),
1299 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1300 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1301 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1302 });
1303 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001304
1305 // Add system include arguments for all targets but IAMCU.
1306 if (!IsIAMCU)
1307 forAllAssociatedToolChains(C, JA, getToolChain(),
1308 [&Args, &CmdArgs](const ToolChain &TC) {
1309 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1310 });
1311 else {
1312 // For IAMCU add special include arguments.
1313 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1314 }
1315}
1316
1317// FIXME: Move to target hook.
1318static bool isSignedCharDefault(const llvm::Triple &Triple) {
1319 switch (Triple.getArch()) {
1320 default:
1321 return true;
1322
1323 case llvm::Triple::aarch64:
1324 case llvm::Triple::aarch64_be:
1325 case llvm::Triple::arm:
1326 case llvm::Triple::armeb:
1327 case llvm::Triple::thumb:
1328 case llvm::Triple::thumbeb:
1329 if (Triple.isOSDarwin() || Triple.isOSWindows())
1330 return true;
1331 return false;
1332
1333 case llvm::Triple::ppc:
1334 case llvm::Triple::ppc64:
1335 if (Triple.isOSDarwin())
1336 return true;
1337 return false;
1338
1339 case llvm::Triple::hexagon:
1340 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001341 case llvm::Triple::riscv32:
1342 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001343 case llvm::Triple::systemz:
1344 case llvm::Triple::xcore:
1345 return false;
1346 }
1347}
1348
1349static bool isNoCommonDefault(const llvm::Triple &Triple) {
1350 switch (Triple.getArch()) {
1351 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001352 if (Triple.isOSFuchsia())
1353 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001354 return false;
1355
1356 case llvm::Triple::xcore:
1357 case llvm::Triple::wasm32:
1358 case llvm::Triple::wasm64:
1359 return true;
1360 }
1361}
1362
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001363namespace {
1364void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1365 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001366 // Select the ABI to use.
1367 // FIXME: Support -meabi.
1368 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1369 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001370 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001371 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001372 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001373 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001374 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001375 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001376
David L. Jonesf561aba2017-03-08 01:02:16 +00001377 CmdArgs.push_back("-target-abi");
1378 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001379}
1380}
1381
1382void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1383 ArgStringList &CmdArgs, bool KernelOrKext) const {
1384 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001385
1386 // Determine floating point ABI from the options & target defaults.
1387 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1388 if (ABI == arm::FloatABI::Soft) {
1389 // Floating point operations and argument passing are soft.
1390 // FIXME: This changes CPP defines, we need -target-soft-float.
1391 CmdArgs.push_back("-msoft-float");
1392 CmdArgs.push_back("-mfloat-abi");
1393 CmdArgs.push_back("soft");
1394 } else if (ABI == arm::FloatABI::SoftFP) {
1395 // Floating point operations are hard, but argument passing is soft.
1396 CmdArgs.push_back("-mfloat-abi");
1397 CmdArgs.push_back("soft");
1398 } else {
1399 // Floating point operations and argument passing are hard.
1400 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1401 CmdArgs.push_back("-mfloat-abi");
1402 CmdArgs.push_back("hard");
1403 }
1404
1405 // Forward the -mglobal-merge option for explicit control over the pass.
1406 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1407 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001408 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001409 if (A->getOption().matches(options::OPT_mno_global_merge))
1410 CmdArgs.push_back("-arm-global-merge=false");
1411 else
1412 CmdArgs.push_back("-arm-global-merge=true");
1413 }
1414
1415 if (!Args.hasFlag(options::OPT_mimplicit_float,
1416 options::OPT_mno_implicit_float, true))
1417 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001418
1419 if (Args.getLastArg(options::OPT_mcmse))
1420 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001421}
1422
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001423void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1424 const ArgList &Args, bool KernelOrKext,
1425 ArgStringList &CmdArgs) const {
1426 const ToolChain &TC = getToolChain();
1427
1428 // Add the target features
1429 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1430
1431 // Add target specific flags.
1432 switch (TC.getArch()) {
1433 default:
1434 break;
1435
1436 case llvm::Triple::arm:
1437 case llvm::Triple::armeb:
1438 case llvm::Triple::thumb:
1439 case llvm::Triple::thumbeb:
1440 // Use the effective triple, which takes into account the deployment target.
1441 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1442 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1443 break;
1444
1445 case llvm::Triple::aarch64:
1446 case llvm::Triple::aarch64_be:
1447 AddAArch64TargetArgs(Args, CmdArgs);
1448 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1449 break;
1450
1451 case llvm::Triple::mips:
1452 case llvm::Triple::mipsel:
1453 case llvm::Triple::mips64:
1454 case llvm::Triple::mips64el:
1455 AddMIPSTargetArgs(Args, CmdArgs);
1456 break;
1457
1458 case llvm::Triple::ppc:
1459 case llvm::Triple::ppc64:
1460 case llvm::Triple::ppc64le:
1461 AddPPCTargetArgs(Args, CmdArgs);
1462 break;
1463
Alex Bradbury71f45452018-01-11 13:36:56 +00001464 case llvm::Triple::riscv32:
1465 case llvm::Triple::riscv64:
1466 AddRISCVTargetArgs(Args, CmdArgs);
1467 break;
1468
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001469 case llvm::Triple::sparc:
1470 case llvm::Triple::sparcel:
1471 case llvm::Triple::sparcv9:
1472 AddSparcTargetArgs(Args, CmdArgs);
1473 break;
1474
1475 case llvm::Triple::systemz:
1476 AddSystemZTargetArgs(Args, CmdArgs);
1477 break;
1478
1479 case llvm::Triple::x86:
1480 case llvm::Triple::x86_64:
1481 AddX86TargetArgs(Args, CmdArgs);
1482 break;
1483
1484 case llvm::Triple::lanai:
1485 AddLanaiTargetArgs(Args, CmdArgs);
1486 break;
1487
1488 case llvm::Triple::hexagon:
1489 AddHexagonTargetArgs(Args, CmdArgs);
1490 break;
1491
1492 case llvm::Triple::wasm32:
1493 case llvm::Triple::wasm64:
1494 AddWebAssemblyTargetArgs(Args, CmdArgs);
1495 break;
1496 }
1497}
1498
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001499// Parse -mbranch-protection=<protection>[+<protection>]* where
1500// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1501// Returns a triple of (return address signing Scope, signing key, require
1502// landing pads)
1503static std::tuple<StringRef, StringRef, bool>
1504ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1505 const Arg *A) {
1506 StringRef Scope = "none";
1507 StringRef Key = "a_key";
1508 bool IndirectBranches = false;
1509
1510 StringRef Value = A->getValue();
1511 // This maps onto -mbranch-protection=<scope>+<key>
1512
1513 if (Value.equals("standard")) {
1514 Scope = "non-leaf";
1515 Key = "a_key";
1516 IndirectBranches = true;
1517
1518 } else if (!Value.equals("none")) {
1519 SmallVector<StringRef, 4> BranchProtection;
1520 StringRef(A->getValue()).split(BranchProtection, '+');
1521
1522 auto Protection = BranchProtection.begin();
1523 while (Protection != BranchProtection.end()) {
1524 if (Protection->equals("bti"))
1525 IndirectBranches = true;
1526 else if (Protection->equals("pac-ret")) {
1527 Scope = "non-leaf";
1528 while (++Protection != BranchProtection.end()) {
1529 // Inner loop as "leaf" and "b-key" options must only appear attached
1530 // to pac-ret.
1531 if (Protection->equals("leaf"))
1532 Scope = "all";
1533 else if (Protection->equals("b-key"))
1534 Key = "b_key";
1535 else
1536 break;
1537 }
1538 Protection--;
1539 } else
1540 D.Diag(diag::err_invalid_branch_protection)
1541 << *Protection << A->getAsString(Args);
1542 Protection++;
1543 }
1544 }
1545
1546 return std::make_tuple(Scope, Key, IndirectBranches);
1547}
1548
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001549namespace {
1550void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1551 ArgStringList &CmdArgs) {
1552 const char *ABIName = nullptr;
1553 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1554 ABIName = A->getValue();
1555 else if (Triple.isOSDarwin())
1556 ABIName = "darwinpcs";
1557 else
1558 ABIName = "aapcs";
1559
1560 CmdArgs.push_back("-target-abi");
1561 CmdArgs.push_back(ABIName);
1562}
1563}
1564
David L. Jonesf561aba2017-03-08 01:02:16 +00001565void Clang::AddAArch64TargetArgs(const ArgList &Args,
1566 ArgStringList &CmdArgs) const {
1567 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1568
1569 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1570 Args.hasArg(options::OPT_mkernel) ||
1571 Args.hasArg(options::OPT_fapple_kext))
1572 CmdArgs.push_back("-disable-red-zone");
1573
1574 if (!Args.hasFlag(options::OPT_mimplicit_float,
1575 options::OPT_mno_implicit_float, true))
1576 CmdArgs.push_back("-no-implicit-float");
1577
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001578 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001579
1580 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1581 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001582 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001583 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1584 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1585 else
1586 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1587 } else if (Triple.isAndroid()) {
1588 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001589 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001590 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1591 }
1592
1593 // Forward the -mglobal-merge option for explicit control over the pass.
1594 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1595 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001596 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001597 if (A->getOption().matches(options::OPT_mno_global_merge))
1598 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1599 else
1600 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1601 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001602
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001603 // Enable/disable return address signing and indirect branch targets.
1604 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1605 options::OPT_mbranch_protection_EQ)) {
1606
1607 const Driver &D = getToolChain().getDriver();
1608
1609 StringRef Scope, Key;
1610 bool IndirectBranches;
1611
1612 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1613 Scope = A->getValue();
1614 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1615 !Scope.equals("all"))
1616 D.Diag(diag::err_invalid_branch_protection)
1617 << Scope << A->getAsString(Args);
1618 Key = "a_key";
1619 IndirectBranches = false;
1620 } else
1621 std::tie(Scope, Key, IndirectBranches) =
1622 ParseAArch64BranchProtection(D, Args, A);
1623
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001624 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001625 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1626 CmdArgs.push_back(
1627 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1628 if (IndirectBranches)
1629 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001630 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001631}
1632
1633void Clang::AddMIPSTargetArgs(const ArgList &Args,
1634 ArgStringList &CmdArgs) const {
1635 const Driver &D = getToolChain().getDriver();
1636 StringRef CPUName;
1637 StringRef ABIName;
1638 const llvm::Triple &Triple = getToolChain().getTriple();
1639 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1640
1641 CmdArgs.push_back("-target-abi");
1642 CmdArgs.push_back(ABIName.data());
1643
1644 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1645 if (ABI == mips::FloatABI::Soft) {
1646 // Floating point operations and argument passing are soft.
1647 CmdArgs.push_back("-msoft-float");
1648 CmdArgs.push_back("-mfloat-abi");
1649 CmdArgs.push_back("soft");
1650 } else {
1651 // Floating point operations and argument passing are hard.
1652 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1653 CmdArgs.push_back("-mfloat-abi");
1654 CmdArgs.push_back("hard");
1655 }
1656
1657 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1658 if (A->getOption().matches(options::OPT_mxgot)) {
1659 CmdArgs.push_back("-mllvm");
1660 CmdArgs.push_back("-mxgot");
1661 }
1662 }
1663
1664 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1665 options::OPT_mno_ldc1_sdc1)) {
1666 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1667 CmdArgs.push_back("-mllvm");
1668 CmdArgs.push_back("-mno-ldc1-sdc1");
1669 }
1670 }
1671
1672 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1673 options::OPT_mno_check_zero_division)) {
1674 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1675 CmdArgs.push_back("-mllvm");
1676 CmdArgs.push_back("-mno-check-zero-division");
1677 }
1678 }
1679
1680 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1681 StringRef v = A->getValue();
1682 CmdArgs.push_back("-mllvm");
1683 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1684 A->claim();
1685 }
1686
Simon Dardis31636a12017-07-20 14:04:12 +00001687 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1688 Arg *ABICalls =
1689 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1690
1691 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1692 // -mgpopt is the default for static, -fno-pic environments but these two
1693 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1694 // the only case where -mllvm -mgpopt is passed.
1695 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1696 // passed explicitly when compiling something with -mabicalls
1697 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001698 //
1699 // When the ABI in use is N64, we also need to determine the PIC mode that
1700 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001701 bool NoABICalls =
1702 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001703
1704 llvm::Reloc::Model RelocationModel;
1705 unsigned PICLevel;
1706 bool IsPIE;
1707 std::tie(RelocationModel, PICLevel, IsPIE) =
1708 ParsePICArgs(getToolChain(), Args);
1709
1710 NoABICalls = NoABICalls ||
1711 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1712
Simon Dardis31636a12017-07-20 14:04:12 +00001713 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1714 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1715 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1716 CmdArgs.push_back("-mllvm");
1717 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001718
1719 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1720 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001721 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001722 options::OPT_mno_extern_sdata);
1723 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1724 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001725 if (LocalSData) {
1726 CmdArgs.push_back("-mllvm");
1727 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1728 CmdArgs.push_back("-mlocal-sdata=1");
1729 } else {
1730 CmdArgs.push_back("-mlocal-sdata=0");
1731 }
1732 LocalSData->claim();
1733 }
1734
Simon Dardis7d318782017-07-24 14:02:09 +00001735 if (ExternSData) {
1736 CmdArgs.push_back("-mllvm");
1737 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1738 CmdArgs.push_back("-mextern-sdata=1");
1739 } else {
1740 CmdArgs.push_back("-mextern-sdata=0");
1741 }
1742 ExternSData->claim();
1743 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001744
1745 if (EmbeddedData) {
1746 CmdArgs.push_back("-mllvm");
1747 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1748 CmdArgs.push_back("-membedded-data=1");
1749 } else {
1750 CmdArgs.push_back("-membedded-data=0");
1751 }
1752 EmbeddedData->claim();
1753 }
1754
Simon Dardis31636a12017-07-20 14:04:12 +00001755 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1756 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1757
1758 if (GPOpt)
1759 GPOpt->claim();
1760
David L. Jonesf561aba2017-03-08 01:02:16 +00001761 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1762 StringRef Val = StringRef(A->getValue());
1763 if (mips::hasCompactBranches(CPUName)) {
1764 if (Val == "never" || Val == "always" || Val == "optimal") {
1765 CmdArgs.push_back("-mllvm");
1766 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1767 } else
1768 D.Diag(diag::err_drv_unsupported_option_argument)
1769 << A->getOption().getName() << Val;
1770 } else
1771 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1772 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001773
1774 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1775 options::OPT_mno_relax_pic_calls)) {
1776 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1777 CmdArgs.push_back("-mllvm");
1778 CmdArgs.push_back("-mips-jalr-reloc=0");
1779 }
1780 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001781}
1782
1783void Clang::AddPPCTargetArgs(const ArgList &Args,
1784 ArgStringList &CmdArgs) const {
1785 // Select the ABI to use.
1786 const char *ABIName = nullptr;
1787 if (getToolChain().getTriple().isOSLinux())
1788 switch (getToolChain().getArch()) {
1789 case llvm::Triple::ppc64: {
1790 // When targeting a processor that supports QPX, or if QPX is
1791 // specifically enabled, default to using the ABI that supports QPX (so
1792 // long as it is not specifically disabled).
1793 bool HasQPX = false;
1794 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1795 HasQPX = A->getValue() == StringRef("a2q");
1796 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1797 if (HasQPX) {
1798 ABIName = "elfv1-qpx";
1799 break;
1800 }
1801
1802 ABIName = "elfv1";
1803 break;
1804 }
1805 case llvm::Triple::ppc64le:
1806 ABIName = "elfv2";
1807 break;
1808 default:
1809 break;
1810 }
1811
Fangrui Song6bd02a42019-07-15 07:25:11 +00001812 bool IEEELongDouble = false;
1813 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1814 StringRef V = A->getValue();
1815 if (V == "ieeelongdouble")
1816 IEEELongDouble = true;
1817 else if (V == "ibmlongdouble")
1818 IEEELongDouble = false;
1819 else if (V != "altivec")
1820 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1821 // the option if given as we don't have backend support for any targets
1822 // that don't use the altivec abi.
David L. Jonesf561aba2017-03-08 01:02:16 +00001823 ABIName = A->getValue();
Fangrui Song6bd02a42019-07-15 07:25:11 +00001824 }
1825 if (IEEELongDouble)
1826 CmdArgs.push_back("-mabi=ieeelongdouble");
David L. Jonesf561aba2017-03-08 01:02:16 +00001827
1828 ppc::FloatABI FloatABI =
1829 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1830
1831 if (FloatABI == ppc::FloatABI::Soft) {
1832 // Floating point operations and argument passing are soft.
1833 CmdArgs.push_back("-msoft-float");
1834 CmdArgs.push_back("-mfloat-abi");
1835 CmdArgs.push_back("soft");
1836 } else {
1837 // Floating point operations and argument passing are hard.
1838 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1839 CmdArgs.push_back("-mfloat-abi");
1840 CmdArgs.push_back("hard");
1841 }
1842
1843 if (ABIName) {
1844 CmdArgs.push_back("-target-abi");
1845 CmdArgs.push_back(ABIName);
1846 }
1847}
1848
Alex Bradbury71f45452018-01-11 13:36:56 +00001849void Clang::AddRISCVTargetArgs(const ArgList &Args,
1850 ArgStringList &CmdArgs) const {
Alex Bradbury71f45452018-01-11 13:36:56 +00001851 const llvm::Triple &Triple = getToolChain().getTriple();
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001852 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
Alex Bradbury71f45452018-01-11 13:36:56 +00001853
1854 CmdArgs.push_back("-target-abi");
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001855 CmdArgs.push_back(ABIName.data());
Alex Bradbury71f45452018-01-11 13:36:56 +00001856}
1857
David L. Jonesf561aba2017-03-08 01:02:16 +00001858void Clang::AddSparcTargetArgs(const ArgList &Args,
1859 ArgStringList &CmdArgs) const {
1860 sparc::FloatABI FloatABI =
1861 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1862
1863 if (FloatABI == sparc::FloatABI::Soft) {
1864 // Floating point operations and argument passing are soft.
1865 CmdArgs.push_back("-msoft-float");
1866 CmdArgs.push_back("-mfloat-abi");
1867 CmdArgs.push_back("soft");
1868 } else {
1869 // Floating point operations and argument passing are hard.
1870 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1871 CmdArgs.push_back("-mfloat-abi");
1872 CmdArgs.push_back("hard");
1873 }
1874}
1875
1876void Clang::AddSystemZTargetArgs(const ArgList &Args,
1877 ArgStringList &CmdArgs) const {
1878 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1879 CmdArgs.push_back("-mbackchain");
1880}
1881
1882void Clang::AddX86TargetArgs(const ArgList &Args,
1883 ArgStringList &CmdArgs) const {
1884 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1885 Args.hasArg(options::OPT_mkernel) ||
1886 Args.hasArg(options::OPT_fapple_kext))
1887 CmdArgs.push_back("-disable-red-zone");
1888
Kristina Brooks7f569b72018-10-18 14:07:02 +00001889 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1890 options::OPT_mno_tls_direct_seg_refs, true))
1891 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1892
David L. Jonesf561aba2017-03-08 01:02:16 +00001893 // Default to avoid implicit floating-point for kernel/kext code, but allow
1894 // that to be overridden with -mno-soft-float.
1895 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1896 Args.hasArg(options::OPT_fapple_kext));
1897 if (Arg *A = Args.getLastArg(
1898 options::OPT_msoft_float, options::OPT_mno_soft_float,
1899 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1900 const Option &O = A->getOption();
1901 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1902 O.matches(options::OPT_msoft_float));
1903 }
1904 if (NoImplicitFloat)
1905 CmdArgs.push_back("-no-implicit-float");
1906
1907 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1908 StringRef Value = A->getValue();
1909 if (Value == "intel" || Value == "att") {
1910 CmdArgs.push_back("-mllvm");
1911 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1912 } else {
1913 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1914 << A->getOption().getName() << Value;
1915 }
Nico Webere3712cf2018-01-17 13:34:20 +00001916 } else if (getToolChain().getDriver().IsCLMode()) {
1917 CmdArgs.push_back("-mllvm");
1918 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001919 }
1920
1921 // Set flags to support MCU ABI.
1922 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1923 CmdArgs.push_back("-mfloat-abi");
1924 CmdArgs.push_back("soft");
1925 CmdArgs.push_back("-mstack-alignment=4");
1926 }
1927}
1928
1929void Clang::AddHexagonTargetArgs(const ArgList &Args,
1930 ArgStringList &CmdArgs) const {
1931 CmdArgs.push_back("-mqdsp6-compat");
1932 CmdArgs.push_back("-Wreturn-type");
1933
1934 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001935 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001936 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1937 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001938 }
1939
1940 if (!Args.hasArg(options::OPT_fno_short_enums))
1941 CmdArgs.push_back("-fshort-enums");
1942 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1943 CmdArgs.push_back("-mllvm");
1944 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1945 }
1946 CmdArgs.push_back("-mllvm");
1947 CmdArgs.push_back("-machine-sink-split=0");
1948}
1949
1950void Clang::AddLanaiTargetArgs(const ArgList &Args,
1951 ArgStringList &CmdArgs) const {
1952 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1953 StringRef CPUName = A->getValue();
1954
1955 CmdArgs.push_back("-target-cpu");
1956 CmdArgs.push_back(Args.MakeArgString(CPUName));
1957 }
1958 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1959 StringRef Value = A->getValue();
1960 // Only support mregparm=4 to support old usage. Report error for all other
1961 // cases.
1962 int Mregparm;
1963 if (Value.getAsInteger(10, Mregparm)) {
1964 if (Mregparm != 4) {
1965 getToolChain().getDriver().Diag(
1966 diag::err_drv_unsupported_option_argument)
1967 << A->getOption().getName() << Value;
1968 }
1969 }
1970 }
1971}
1972
1973void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1974 ArgStringList &CmdArgs) const {
1975 // Default to "hidden" visibility.
1976 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1977 options::OPT_fvisibility_ms_compat)) {
1978 CmdArgs.push_back("-fvisibility");
1979 CmdArgs.push_back("hidden");
1980 }
1981}
1982
1983void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1984 StringRef Target, const InputInfo &Output,
1985 const InputInfo &Input, const ArgList &Args) const {
1986 // If this is a dry run, do not create the compilation database file.
1987 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1988 return;
1989
1990 using llvm::yaml::escape;
1991 const Driver &D = getToolChain().getDriver();
1992
1993 if (!CompilationDatabase) {
1994 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00001995 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC,
1996 llvm::sys::fs::OF_Text);
David L. Jonesf561aba2017-03-08 01:02:16 +00001997 if (EC) {
1998 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1999 << EC.message();
2000 return;
2001 }
2002 CompilationDatabase = std::move(File);
2003 }
2004 auto &CDB = *CompilationDatabase;
2005 SmallString<128> Buf;
2006 if (llvm::sys::fs::current_path(Buf))
2007 Buf = ".";
2008 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
2009 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2010 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2011 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2012 Buf = "-x";
2013 Buf += types::getTypeName(Input.getType());
2014 CDB << ", \"" << escape(Buf) << "\"";
2015 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2016 Buf = "--sysroot=";
2017 Buf += D.SysRoot;
2018 CDB << ", \"" << escape(Buf) << "\"";
2019 }
2020 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2021 for (auto &A: Args) {
2022 auto &O = A->getOption();
2023 // Skip language selection, which is positional.
2024 if (O.getID() == options::OPT_x)
2025 continue;
2026 // Skip writing dependency output and the compilation database itself.
2027 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2028 continue;
2029 // Skip inputs.
2030 if (O.getKind() == Option::InputClass)
2031 continue;
2032 // All other arguments are quoted and appended.
2033 ArgStringList ASL;
2034 A->render(Args, ASL);
2035 for (auto &it: ASL)
2036 CDB << ", \"" << escape(it) << "\"";
2037 }
2038 Buf = "--target=";
2039 Buf += Target;
2040 CDB << ", \"" << escape(Buf) << "\"]},\n";
2041}
2042
2043static void CollectArgsForIntegratedAssembler(Compilation &C,
2044 const ArgList &Args,
2045 ArgStringList &CmdArgs,
2046 const Driver &D) {
2047 if (UseRelaxAll(C, Args))
2048 CmdArgs.push_back("-mrelax-all");
2049
2050 // Only default to -mincremental-linker-compatible if we think we are
2051 // targeting the MSVC linker.
2052 bool DefaultIncrementalLinkerCompatible =
2053 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2054 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2055 options::OPT_mno_incremental_linker_compatible,
2056 DefaultIncrementalLinkerCompatible))
2057 CmdArgs.push_back("-mincremental-linker-compatible");
2058
2059 switch (C.getDefaultToolChain().getArch()) {
2060 case llvm::Triple::arm:
2061 case llvm::Triple::armeb:
2062 case llvm::Triple::thumb:
2063 case llvm::Triple::thumbeb:
2064 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2065 StringRef Value = A->getValue();
2066 if (Value == "always" || Value == "never" || Value == "arm" ||
2067 Value == "thumb") {
2068 CmdArgs.push_back("-mllvm");
2069 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2070 } else {
2071 D.Diag(diag::err_drv_unsupported_option_argument)
2072 << A->getOption().getName() << Value;
2073 }
2074 }
2075 break;
2076 default:
2077 break;
2078 }
2079
Nico Weberb28ffd82019-07-27 01:13:00 +00002080 // If you add more args here, also add them to the block below that
2081 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2082
David L. Jonesf561aba2017-03-08 01:02:16 +00002083 // When passing -I arguments to the assembler we sometimes need to
2084 // unconditionally take the next argument. For example, when parsing
2085 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2086 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2087 // arg after parsing the '-I' arg.
2088 bool TakeNextArg = false;
2089
Petr Hosek5668d832017-11-22 01:38:31 +00002090 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002091 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002092 const char *MipsTargetFeature = nullptr;
2093 for (const Arg *A :
2094 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2095 A->claim();
2096
2097 for (StringRef Value : A->getValues()) {
2098 if (TakeNextArg) {
2099 CmdArgs.push_back(Value.data());
2100 TakeNextArg = false;
2101 continue;
2102 }
2103
2104 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2105 Value == "-mbig-obj")
2106 continue; // LLVM handles bigobj automatically
2107
2108 switch (C.getDefaultToolChain().getArch()) {
2109 default:
2110 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002111 case llvm::Triple::thumb:
2112 case llvm::Triple::thumbeb:
2113 case llvm::Triple::arm:
2114 case llvm::Triple::armeb:
2115 if (Value == "-mthumb")
2116 // -mthumb has already been processed in ComputeLLVMTriple()
2117 // recognize but skip over here.
2118 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002119 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002120 case llvm::Triple::mips:
2121 case llvm::Triple::mipsel:
2122 case llvm::Triple::mips64:
2123 case llvm::Triple::mips64el:
2124 if (Value == "--trap") {
2125 CmdArgs.push_back("-target-feature");
2126 CmdArgs.push_back("+use-tcc-in-div");
2127 continue;
2128 }
2129 if (Value == "--break") {
2130 CmdArgs.push_back("-target-feature");
2131 CmdArgs.push_back("-use-tcc-in-div");
2132 continue;
2133 }
2134 if (Value.startswith("-msoft-float")) {
2135 CmdArgs.push_back("-target-feature");
2136 CmdArgs.push_back("+soft-float");
2137 continue;
2138 }
2139 if (Value.startswith("-mhard-float")) {
2140 CmdArgs.push_back("-target-feature");
2141 CmdArgs.push_back("-soft-float");
2142 continue;
2143 }
2144
2145 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2146 .Case("-mips1", "+mips1")
2147 .Case("-mips2", "+mips2")
2148 .Case("-mips3", "+mips3")
2149 .Case("-mips4", "+mips4")
2150 .Case("-mips5", "+mips5")
2151 .Case("-mips32", "+mips32")
2152 .Case("-mips32r2", "+mips32r2")
2153 .Case("-mips32r3", "+mips32r3")
2154 .Case("-mips32r5", "+mips32r5")
2155 .Case("-mips32r6", "+mips32r6")
2156 .Case("-mips64", "+mips64")
2157 .Case("-mips64r2", "+mips64r2")
2158 .Case("-mips64r3", "+mips64r3")
2159 .Case("-mips64r5", "+mips64r5")
2160 .Case("-mips64r6", "+mips64r6")
2161 .Default(nullptr);
2162 if (MipsTargetFeature)
2163 continue;
2164 }
2165
2166 if (Value == "-force_cpusubtype_ALL") {
2167 // Do nothing, this is the default and we don't support anything else.
2168 } else if (Value == "-L") {
2169 CmdArgs.push_back("-msave-temp-labels");
2170 } else if (Value == "--fatal-warnings") {
2171 CmdArgs.push_back("-massembler-fatal-warnings");
Brian Cain7b953b62019-08-08 19:19:20 +00002172 } else if (Value == "--no-warn") {
2173 CmdArgs.push_back("-massembler-no-warn");
David L. Jonesf561aba2017-03-08 01:02:16 +00002174 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002175 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002176 } else if (Value.startswith("-compress-debug-sections") ||
2177 Value.startswith("--compress-debug-sections") ||
2178 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002179 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002180 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002181 } else if (Value == "-mrelax-relocations=yes" ||
2182 Value == "--mrelax-relocations=yes") {
2183 UseRelaxRelocations = true;
2184 } else if (Value == "-mrelax-relocations=no" ||
2185 Value == "--mrelax-relocations=no") {
2186 UseRelaxRelocations = false;
2187 } else if (Value.startswith("-I")) {
2188 CmdArgs.push_back(Value.data());
2189 // We need to consume the next argument if the current arg is a plain
2190 // -I. The next arg will be the include directory.
2191 if (Value == "-I")
2192 TakeNextArg = true;
2193 } else if (Value.startswith("-gdwarf-")) {
2194 // "-gdwarf-N" options are not cc1as options.
2195 unsigned DwarfVersion = DwarfVersionNum(Value);
2196 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2197 CmdArgs.push_back(Value.data());
2198 } else {
2199 RenderDebugEnablingArgs(Args, CmdArgs,
2200 codegenoptions::LimitedDebugInfo,
2201 DwarfVersion, llvm::DebuggerKind::Default);
2202 }
2203 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2204 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2205 // Do nothing, we'll validate it later.
2206 } else if (Value == "-defsym") {
2207 if (A->getNumValues() != 2) {
2208 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2209 break;
2210 }
2211 const char *S = A->getValue(1);
2212 auto Pair = StringRef(S).split('=');
2213 auto Sym = Pair.first;
2214 auto SVal = Pair.second;
2215
2216 if (Sym.empty() || SVal.empty()) {
2217 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2218 break;
2219 }
2220 int64_t IVal;
2221 if (SVal.getAsInteger(0, IVal)) {
2222 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2223 break;
2224 }
2225 CmdArgs.push_back(Value.data());
2226 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002227 } else if (Value == "-fdebug-compilation-dir") {
2228 CmdArgs.push_back("-fdebug-compilation-dir");
2229 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002230 } else {
2231 D.Diag(diag::err_drv_unsupported_option_argument)
2232 << A->getOption().getName() << Value;
2233 }
2234 }
2235 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002236 if (UseRelaxRelocations)
2237 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002238 if (UseNoExecStack)
2239 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002240 if (MipsTargetFeature != nullptr) {
2241 CmdArgs.push_back("-target-feature");
2242 CmdArgs.push_back(MipsTargetFeature);
2243 }
Steven Wu098742f2018-12-12 17:30:16 +00002244
2245 // forward -fembed-bitcode to assmebler
2246 if (C.getDriver().embedBitcodeEnabled() ||
2247 C.getDriver().embedBitcodeMarkerOnly())
2248 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002249}
2250
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002251static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2252 bool OFastEnabled, const ArgList &Args,
2253 ArgStringList &CmdArgs) {
2254 // Handle various floating point optimization flags, mapping them to the
2255 // appropriate LLVM code generation flags. This is complicated by several
2256 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002257 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002258 // LLVM flags based on the final state.
2259 bool HonorINFs = true;
2260 bool HonorNaNs = true;
2261 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2262 bool MathErrno = TC.IsMathErrnoDefault();
2263 bool AssociativeMath = false;
2264 bool ReciprocalMath = false;
2265 bool SignedZeros = true;
2266 bool TrappingMath = true;
2267 StringRef DenormalFPMath = "";
2268 StringRef FPContract = "";
2269
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002270 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2271 CmdArgs.push_back("-mlimit-float-precision");
2272 CmdArgs.push_back(A->getValue());
2273 }
2274
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002275 for (const Arg *A : Args) {
2276 switch (A->getOption().getID()) {
2277 // If this isn't an FP option skip the claim below
2278 default: continue;
2279
2280 // Options controlling individual features
2281 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2282 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2283 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2284 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2285 case options::OPT_fmath_errno: MathErrno = true; break;
2286 case options::OPT_fno_math_errno: MathErrno = false; break;
2287 case options::OPT_fassociative_math: AssociativeMath = true; break;
2288 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2289 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2290 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2291 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2292 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2293 case options::OPT_ftrapping_math: TrappingMath = true; break;
2294 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2295
2296 case options::OPT_fdenormal_fp_math_EQ:
2297 DenormalFPMath = A->getValue();
2298 break;
2299
2300 // Validate and pass through -fp-contract option.
2301 case options::OPT_ffp_contract: {
2302 StringRef Val = A->getValue();
2303 if (Val == "fast" || Val == "on" || Val == "off")
2304 FPContract = Val;
2305 else
2306 D.Diag(diag::err_drv_unsupported_option_argument)
2307 << A->getOption().getName() << Val;
2308 break;
2309 }
2310
2311 case options::OPT_ffinite_math_only:
2312 HonorINFs = false;
2313 HonorNaNs = false;
2314 break;
2315 case options::OPT_fno_finite_math_only:
2316 HonorINFs = true;
2317 HonorNaNs = true;
2318 break;
2319
2320 case options::OPT_funsafe_math_optimizations:
2321 AssociativeMath = true;
2322 ReciprocalMath = true;
2323 SignedZeros = false;
2324 TrappingMath = false;
2325 break;
2326 case options::OPT_fno_unsafe_math_optimizations:
2327 AssociativeMath = false;
2328 ReciprocalMath = false;
2329 SignedZeros = true;
2330 TrappingMath = true;
2331 // -fno_unsafe_math_optimizations restores default denormal handling
2332 DenormalFPMath = "";
2333 break;
2334
2335 case options::OPT_Ofast:
2336 // If -Ofast is the optimization level, then -ffast-math should be enabled
2337 if (!OFastEnabled)
2338 continue;
2339 LLVM_FALLTHROUGH;
2340 case options::OPT_ffast_math:
2341 HonorINFs = false;
2342 HonorNaNs = false;
2343 MathErrno = false;
2344 AssociativeMath = true;
2345 ReciprocalMath = true;
2346 SignedZeros = false;
2347 TrappingMath = false;
2348 // If fast-math is set then set the fp-contract mode to fast.
2349 FPContract = "fast";
2350 break;
2351 case options::OPT_fno_fast_math:
2352 HonorINFs = true;
2353 HonorNaNs = true;
2354 // Turning on -ffast-math (with either flag) removes the need for
2355 // MathErrno. However, turning *off* -ffast-math merely restores the
2356 // toolchain default (which may be false).
2357 MathErrno = TC.IsMathErrnoDefault();
2358 AssociativeMath = false;
2359 ReciprocalMath = false;
2360 SignedZeros = true;
2361 TrappingMath = true;
2362 // -fno_fast_math restores default denormal and fpcontract handling
2363 DenormalFPMath = "";
2364 FPContract = "";
2365 break;
2366 }
2367
2368 // If we handled this option claim it
2369 A->claim();
2370 }
2371
2372 if (!HonorINFs)
2373 CmdArgs.push_back("-menable-no-infs");
2374
2375 if (!HonorNaNs)
2376 CmdArgs.push_back("-menable-no-nans");
2377
2378 if (MathErrno)
2379 CmdArgs.push_back("-fmath-errno");
2380
2381 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2382 !TrappingMath)
2383 CmdArgs.push_back("-menable-unsafe-fp-math");
2384
2385 if (!SignedZeros)
2386 CmdArgs.push_back("-fno-signed-zeros");
2387
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002388 if (AssociativeMath && !SignedZeros && !TrappingMath)
2389 CmdArgs.push_back("-mreassociate");
2390
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002391 if (ReciprocalMath)
2392 CmdArgs.push_back("-freciprocal-math");
2393
2394 if (!TrappingMath)
2395 CmdArgs.push_back("-fno-trapping-math");
2396
2397 if (!DenormalFPMath.empty())
2398 CmdArgs.push_back(
2399 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2400
2401 if (!FPContract.empty())
2402 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2403
2404 ParseMRecip(D, Args, CmdArgs);
2405
2406 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2407 // individual features enabled by -ffast-math instead of the option itself as
2408 // that's consistent with gcc's behaviour.
2409 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2410 ReciprocalMath && !SignedZeros && !TrappingMath)
2411 CmdArgs.push_back("-ffast-math");
2412
2413 // Handle __FINITE_MATH_ONLY__ similarly.
2414 if (!HonorINFs && !HonorNaNs)
2415 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002416
2417 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2418 CmdArgs.push_back("-mfpmath");
2419 CmdArgs.push_back(A->getValue());
2420 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002421
2422 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002423 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2424 options::OPT_fstrict_float_cast_overflow, false))
2425 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002426}
2427
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002428static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2429 const llvm::Triple &Triple,
2430 const InputInfo &Input) {
2431 // Enable region store model by default.
2432 CmdArgs.push_back("-analyzer-store=region");
2433
2434 // Treat blocks as analysis entry points.
2435 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2436
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002437 // Add default argument set.
2438 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2439 CmdArgs.push_back("-analyzer-checker=core");
2440 CmdArgs.push_back("-analyzer-checker=apiModeling");
2441
2442 if (!Triple.isWindowsMSVCEnvironment()) {
2443 CmdArgs.push_back("-analyzer-checker=unix");
2444 } else {
2445 // Enable "unix" checkers that also work on Windows.
2446 CmdArgs.push_back("-analyzer-checker=unix.API");
2447 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2448 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2449 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2450 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2451 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2452 }
2453
2454 // Disable some unix checkers for PS4.
2455 if (Triple.isPS4CPU()) {
2456 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2457 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2458 }
2459
2460 if (Triple.isOSDarwin())
2461 CmdArgs.push_back("-analyzer-checker=osx");
2462
2463 CmdArgs.push_back("-analyzer-checker=deadcode");
2464
2465 if (types::isCXX(Input.getType()))
2466 CmdArgs.push_back("-analyzer-checker=cplusplus");
2467
2468 if (!Triple.isPS4CPU()) {
2469 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2470 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2471 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2472 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2473 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2474 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2475 }
2476
2477 // Default nullability checks.
2478 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2479 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2480 }
2481
2482 // Set the output format. The default is plist, for (lame) historical reasons.
2483 CmdArgs.push_back("-analyzer-output");
2484 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2485 CmdArgs.push_back(A->getValue());
2486 else
2487 CmdArgs.push_back("plist");
2488
2489 // Disable the presentation of standard compiler warnings when using
2490 // --analyze. We only want to show static analyzer diagnostics or frontend
2491 // errors.
2492 CmdArgs.push_back("-w");
2493
2494 // Add -Xanalyzer arguments when running as analyzer.
2495 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2496}
2497
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002498static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002499 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002500 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2501
2502 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2503 // doesn't even have a stack!
2504 if (EffectiveTriple.isNVPTX())
2505 return;
2506
2507 // -stack-protector=0 is default.
2508 unsigned StackProtectorLevel = 0;
2509 unsigned DefaultStackProtectorLevel =
2510 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2511
2512 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2513 options::OPT_fstack_protector_all,
2514 options::OPT_fstack_protector_strong,
2515 options::OPT_fstack_protector)) {
2516 if (A->getOption().matches(options::OPT_fstack_protector))
2517 StackProtectorLevel =
2518 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2519 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2520 StackProtectorLevel = LangOptions::SSPStrong;
2521 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2522 StackProtectorLevel = LangOptions::SSPReq;
2523 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002524 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002525 }
2526
2527 if (StackProtectorLevel) {
2528 CmdArgs.push_back("-stack-protector");
2529 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2530 }
2531
2532 // --param ssp-buffer-size=
2533 for (const Arg *A : Args.filtered(options::OPT__param)) {
2534 StringRef Str(A->getValue());
2535 if (Str.startswith("ssp-buffer-size=")) {
2536 if (StackProtectorLevel) {
2537 CmdArgs.push_back("-stack-protector-buffer-size");
2538 // FIXME: Verify the argument is a valid integer.
2539 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2540 }
2541 A->claim();
2542 }
2543 }
2544}
2545
JF Bastien14daa202018-12-18 05:12:21 +00002546static void RenderTrivialAutoVarInitOptions(const Driver &D,
2547 const ToolChain &TC,
2548 const ArgList &Args,
2549 ArgStringList &CmdArgs) {
2550 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2551 StringRef TrivialAutoVarInit = "";
2552
2553 for (const Arg *A : Args) {
2554 switch (A->getOption().getID()) {
2555 default:
2556 continue;
2557 case options::OPT_ftrivial_auto_var_init: {
2558 A->claim();
2559 StringRef Val = A->getValue();
2560 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2561 TrivialAutoVarInit = Val;
2562 else
2563 D.Diag(diag::err_drv_unsupported_option_argument)
2564 << A->getOption().getName() << Val;
2565 break;
2566 }
2567 }
2568 }
2569
2570 if (TrivialAutoVarInit.empty())
2571 switch (DefaultTrivialAutoVarInit) {
2572 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2573 break;
2574 case LangOptions::TrivialAutoVarInitKind::Pattern:
2575 TrivialAutoVarInit = "pattern";
2576 break;
2577 case LangOptions::TrivialAutoVarInitKind::Zero:
2578 TrivialAutoVarInit = "zero";
2579 break;
2580 }
2581
2582 if (!TrivialAutoVarInit.empty()) {
2583 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2584 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2585 CmdArgs.push_back(
2586 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2587 }
2588}
2589
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002590static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2591 const unsigned ForwardedArguments[] = {
2592 options::OPT_cl_opt_disable,
2593 options::OPT_cl_strict_aliasing,
2594 options::OPT_cl_single_precision_constant,
2595 options::OPT_cl_finite_math_only,
2596 options::OPT_cl_kernel_arg_info,
2597 options::OPT_cl_unsafe_math_optimizations,
2598 options::OPT_cl_fast_relaxed_math,
2599 options::OPT_cl_mad_enable,
2600 options::OPT_cl_no_signed_zeros,
2601 options::OPT_cl_denorms_are_zero,
2602 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002603 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002604 };
2605
2606 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2607 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2608 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2609 }
2610
2611 for (const auto &Arg : ForwardedArguments)
2612 if (const auto *A = Args.getLastArg(Arg))
2613 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2614}
2615
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002616static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2617 ArgStringList &CmdArgs) {
2618 bool ARCMTEnabled = false;
2619 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2620 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2621 options::OPT_ccc_arcmt_modify,
2622 options::OPT_ccc_arcmt_migrate)) {
2623 ARCMTEnabled = true;
2624 switch (A->getOption().getID()) {
2625 default: llvm_unreachable("missed a case");
2626 case options::OPT_ccc_arcmt_check:
2627 CmdArgs.push_back("-arcmt-check");
2628 break;
2629 case options::OPT_ccc_arcmt_modify:
2630 CmdArgs.push_back("-arcmt-modify");
2631 break;
2632 case options::OPT_ccc_arcmt_migrate:
2633 CmdArgs.push_back("-arcmt-migrate");
2634 CmdArgs.push_back("-mt-migrate-directory");
2635 CmdArgs.push_back(A->getValue());
2636
2637 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2638 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2639 break;
2640 }
2641 }
2642 } else {
2643 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2644 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2645 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2646 }
2647
2648 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2649 if (ARCMTEnabled)
2650 D.Diag(diag::err_drv_argument_not_allowed_with)
2651 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2652
2653 CmdArgs.push_back("-mt-migrate-directory");
2654 CmdArgs.push_back(A->getValue());
2655
2656 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2657 options::OPT_objcmt_migrate_subscripting,
2658 options::OPT_objcmt_migrate_property)) {
2659 // None specified, means enable them all.
2660 CmdArgs.push_back("-objcmt-migrate-literals");
2661 CmdArgs.push_back("-objcmt-migrate-subscripting");
2662 CmdArgs.push_back("-objcmt-migrate-property");
2663 } else {
2664 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2665 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2666 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2667 }
2668 } else {
2669 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2670 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2671 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2672 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2673 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2674 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2675 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2676 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2677 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2678 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2679 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2680 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2681 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2682 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2683 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2684 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2685 }
2686}
2687
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002688static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2689 const ArgList &Args, ArgStringList &CmdArgs) {
2690 // -fbuiltin is default unless -mkernel is used.
2691 bool UseBuiltins =
2692 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2693 !Args.hasArg(options::OPT_mkernel));
2694 if (!UseBuiltins)
2695 CmdArgs.push_back("-fno-builtin");
2696
2697 // -ffreestanding implies -fno-builtin.
2698 if (Args.hasArg(options::OPT_ffreestanding))
2699 UseBuiltins = false;
2700
2701 // Process the -fno-builtin-* options.
2702 for (const auto &Arg : Args) {
2703 const Option &O = Arg->getOption();
2704 if (!O.matches(options::OPT_fno_builtin_))
2705 continue;
2706
2707 Arg->claim();
2708
2709 // If -fno-builtin is specified, then there's no need to pass the option to
2710 // the frontend.
2711 if (!UseBuiltins)
2712 continue;
2713
2714 StringRef FuncName = Arg->getValue();
2715 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2716 }
2717
2718 // le32-specific flags:
2719 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2720 // by default.
2721 if (TC.getArch() == llvm::Triple::le32)
2722 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002723}
2724
Adrian Prantl70599032018-02-09 18:43:10 +00002725void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2726 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2727 llvm::sys::path::append(Result, "org.llvm.clang.");
2728 appendUserToPath(Result);
2729 llvm::sys::path::append(Result, "ModuleCache");
2730}
2731
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002732static void RenderModulesOptions(Compilation &C, const Driver &D,
2733 const ArgList &Args, const InputInfo &Input,
2734 const InputInfo &Output,
2735 ArgStringList &CmdArgs, bool &HaveModules) {
2736 // -fmodules enables the use of precompiled modules (off by default).
2737 // Users can pass -fno-cxx-modules to turn off modules support for
2738 // C++/Objective-C++ programs.
2739 bool HaveClangModules = false;
2740 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2741 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2742 options::OPT_fno_cxx_modules, true);
2743 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2744 CmdArgs.push_back("-fmodules");
2745 HaveClangModules = true;
2746 }
2747 }
2748
Richard Smithb1b580e2019-04-14 11:11:37 +00002749 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002750 if (Args.hasArg(options::OPT_fmodules_ts)) {
2751 CmdArgs.push_back("-fmodules-ts");
2752 HaveModules = true;
2753 }
2754
2755 // -fmodule-maps enables implicit reading of module map files. By default,
2756 // this is enabled if we are using Clang's flavor of precompiled modules.
2757 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2758 options::OPT_fno_implicit_module_maps, HaveClangModules))
2759 CmdArgs.push_back("-fimplicit-module-maps");
2760
2761 // -fmodules-decluse checks that modules used are declared so (off by default)
2762 if (Args.hasFlag(options::OPT_fmodules_decluse,
2763 options::OPT_fno_modules_decluse, false))
2764 CmdArgs.push_back("-fmodules-decluse");
2765
2766 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2767 // all #included headers are part of modules.
2768 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2769 options::OPT_fno_modules_strict_decluse, false))
2770 CmdArgs.push_back("-fmodules-strict-decluse");
2771
2772 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002773 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002774 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2775 options::OPT_fno_implicit_modules, HaveClangModules)) {
2776 if (HaveModules)
2777 CmdArgs.push_back("-fno-implicit-modules");
2778 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002779 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002780 // -fmodule-cache-path specifies where our implicitly-built module files
2781 // should be written.
2782 SmallString<128> Path;
2783 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2784 Path = A->getValue();
2785
2786 if (C.isForDiagnostics()) {
2787 // When generating crash reports, we want to emit the modules along with
2788 // the reproduction sources, so we ignore any provided module path.
2789 Path = Output.getFilename();
2790 llvm::sys::path::replace_extension(Path, ".cache");
2791 llvm::sys::path::append(Path, "modules");
2792 } else if (Path.empty()) {
2793 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002794 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002795 }
2796
2797 const char Arg[] = "-fmodules-cache-path=";
2798 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2799 CmdArgs.push_back(Args.MakeArgString(Path));
2800 }
2801
2802 if (HaveModules) {
2803 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2804 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2805 CmdArgs.push_back(Args.MakeArgString(
2806 std::string("-fprebuilt-module-path=") + A->getValue()));
2807 A->claim();
2808 }
2809 }
2810
2811 // -fmodule-name specifies the module that is currently being built (or
2812 // used for header checking by -fmodule-maps).
2813 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2814
2815 // -fmodule-map-file can be used to specify files containing module
2816 // definitions.
2817 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2818
2819 // -fbuiltin-module-map can be used to load the clang
2820 // builtin headers modulemap file.
2821 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2822 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2823 llvm::sys::path::append(BuiltinModuleMap, "include");
2824 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2825 if (llvm::sys::fs::exists(BuiltinModuleMap))
2826 CmdArgs.push_back(
2827 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2828 }
2829
2830 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2831 // names to precompiled module files (the module is loaded only if used).
2832 // The -fmodule-file=<file> form can be used to unconditionally load
2833 // precompiled module files (whether used or not).
2834 if (HaveModules)
2835 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2836 else
2837 Args.ClaimAllArgs(options::OPT_fmodule_file);
2838
2839 // When building modules and generating crashdumps, we need to dump a module
2840 // dependency VFS alongside the output.
2841 if (HaveClangModules && C.isForDiagnostics()) {
2842 SmallString<128> VFSDir(Output.getFilename());
2843 llvm::sys::path::replace_extension(VFSDir, ".cache");
2844 // Add the cache directory as a temp so the crash diagnostics pick it up.
2845 C.addTempFile(Args.MakeArgString(VFSDir));
2846
2847 llvm::sys::path::append(VFSDir, "vfs");
2848 CmdArgs.push_back("-module-dependency-dir");
2849 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2850 }
2851
2852 if (HaveClangModules)
2853 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2854
2855 // Pass through all -fmodules-ignore-macro arguments.
2856 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2857 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2858 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2859
2860 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2861
2862 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2863 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2864 D.Diag(diag::err_drv_argument_not_allowed_with)
2865 << A->getAsString(Args) << "-fbuild-session-timestamp";
2866
2867 llvm::sys::fs::file_status Status;
2868 if (llvm::sys::fs::status(A->getValue(), Status))
2869 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2870 CmdArgs.push_back(
2871 Args.MakeArgString("-fbuild-session-timestamp=" +
2872 Twine((uint64_t)Status.getLastModificationTime()
2873 .time_since_epoch()
2874 .count())));
2875 }
2876
2877 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2878 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2879 options::OPT_fbuild_session_file))
2880 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2881
2882 Args.AddLastArg(CmdArgs,
2883 options::OPT_fmodules_validate_once_per_build_session);
2884 }
2885
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002886 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2887 options::OPT_fno_modules_validate_system_headers,
2888 ImplicitModules))
2889 CmdArgs.push_back("-fmodules-validate-system-headers");
2890
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002891 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2892}
2893
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002894static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2895 ArgStringList &CmdArgs) {
2896 // -fsigned-char is default.
2897 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2898 options::OPT_fno_signed_char,
2899 options::OPT_funsigned_char,
2900 options::OPT_fno_unsigned_char)) {
2901 if (A->getOption().matches(options::OPT_funsigned_char) ||
2902 A->getOption().matches(options::OPT_fno_signed_char)) {
2903 CmdArgs.push_back("-fno-signed-char");
2904 }
2905 } else if (!isSignedCharDefault(T)) {
2906 CmdArgs.push_back("-fno-signed-char");
2907 }
2908
Richard Smith28ddb912018-11-14 21:04:34 +00002909 // The default depends on the language standard.
Nico Weber908b6972019-06-26 17:51:47 +00002910 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
Richard Smith3a8244d2018-05-01 05:02:45 +00002911
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002912 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2913 options::OPT_fno_short_wchar)) {
2914 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2915 CmdArgs.push_back("-fwchar-type=short");
2916 CmdArgs.push_back("-fno-signed-wchar");
2917 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002918 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002919 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002920 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2921 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002922 CmdArgs.push_back("-fno-signed-wchar");
2923 else
2924 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002925 }
2926 }
2927}
2928
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002929static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2930 const llvm::Triple &T, const ArgList &Args,
2931 ObjCRuntime &Runtime, bool InferCovariantReturns,
2932 const InputInfo &Input, ArgStringList &CmdArgs) {
2933 const llvm::Triple::ArchType Arch = TC.getArch();
2934
2935 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2936 // is the default. Except for deployment target of 10.5, next runtime is
2937 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2938 if (Runtime.isNonFragile()) {
2939 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2940 options::OPT_fno_objc_legacy_dispatch,
2941 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2942 if (TC.UseObjCMixedDispatch())
2943 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2944 else
2945 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2946 }
2947 }
2948
2949 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2950 // to do Array/Dictionary subscripting by default.
2951 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002952 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2953 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2954
2955 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2956 // NOTE: This logic is duplicated in ToolChains.cpp.
2957 if (isObjCAutoRefCount(Args)) {
2958 TC.CheckObjCARC();
2959
2960 CmdArgs.push_back("-fobjc-arc");
2961
2962 // FIXME: It seems like this entire block, and several around it should be
2963 // wrapped in isObjC, but for now we just use it here as this is where it
2964 // was being used previously.
2965 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2966 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2967 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2968 else
2969 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2970 }
2971
2972 // Allow the user to enable full exceptions code emission.
2973 // We default off for Objective-C, on for Objective-C++.
2974 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2975 options::OPT_fno_objc_arc_exceptions,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002976 /*Default=*/types::isCXX(Input.getType())))
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002977 CmdArgs.push_back("-fobjc-arc-exceptions");
2978 }
2979
2980 // Silence warning for full exception code emission options when explicitly
2981 // set to use no ARC.
2982 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2983 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2984 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2985 }
2986
Pete Coopere3886802018-12-08 05:13:50 +00002987 // Allow the user to control whether messages can be converted to runtime
2988 // functions.
2989 if (types::isObjC(Input.getType())) {
2990 auto *Arg = Args.getLastArg(
2991 options::OPT_fobjc_convert_messages_to_runtime_calls,
2992 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2993 if (Arg &&
2994 Arg->getOption().matches(
2995 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2996 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2997 }
2998
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002999 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3000 // rewriter.
3001 if (InferCovariantReturns)
3002 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3003
3004 // Pass down -fobjc-weak or -fno-objc-weak if present.
3005 if (types::isObjC(Input.getType())) {
3006 auto WeakArg =
3007 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3008 if (!WeakArg) {
3009 // nothing to do
3010 } else if (!Runtime.allowsWeak()) {
3011 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3012 D.Diag(diag::err_objc_weak_unsupported);
3013 } else {
3014 WeakArg->render(Args, CmdArgs);
3015 }
3016 }
3017}
3018
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003019static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3020 ArgStringList &CmdArgs) {
3021 bool CaretDefault = true;
3022 bool ColumnDefault = true;
3023
3024 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3025 options::OPT__SLASH_diagnostics_column,
3026 options::OPT__SLASH_diagnostics_caret)) {
3027 switch (A->getOption().getID()) {
3028 case options::OPT__SLASH_diagnostics_caret:
3029 CaretDefault = true;
3030 ColumnDefault = true;
3031 break;
3032 case options::OPT__SLASH_diagnostics_column:
3033 CaretDefault = false;
3034 ColumnDefault = true;
3035 break;
3036 case options::OPT__SLASH_diagnostics_classic:
3037 CaretDefault = false;
3038 ColumnDefault = false;
3039 break;
3040 }
3041 }
3042
3043 // -fcaret-diagnostics is default.
3044 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3045 options::OPT_fno_caret_diagnostics, CaretDefault))
3046 CmdArgs.push_back("-fno-caret-diagnostics");
3047
3048 // -fdiagnostics-fixit-info is default, only pass non-default.
3049 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3050 options::OPT_fno_diagnostics_fixit_info))
3051 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3052
3053 // Enable -fdiagnostics-show-option by default.
3054 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3055 options::OPT_fno_diagnostics_show_option))
3056 CmdArgs.push_back("-fdiagnostics-show-option");
3057
3058 if (const Arg *A =
3059 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3060 CmdArgs.push_back("-fdiagnostics-show-category");
3061 CmdArgs.push_back(A->getValue());
3062 }
3063
3064 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3065 options::OPT_fno_diagnostics_show_hotness, false))
3066 CmdArgs.push_back("-fdiagnostics-show-hotness");
3067
3068 if (const Arg *A =
3069 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3070 std::string Opt =
3071 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3072 CmdArgs.push_back(Args.MakeArgString(Opt));
3073 }
3074
3075 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3076 CmdArgs.push_back("-fdiagnostics-format");
3077 CmdArgs.push_back(A->getValue());
3078 }
3079
3080 if (const Arg *A = Args.getLastArg(
3081 options::OPT_fdiagnostics_show_note_include_stack,
3082 options::OPT_fno_diagnostics_show_note_include_stack)) {
3083 const Option &O = A->getOption();
3084 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3085 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3086 else
3087 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3088 }
3089
3090 // Color diagnostics are parsed by the driver directly from argv and later
3091 // re-parsed to construct this job; claim any possible color diagnostic here
3092 // to avoid warn_drv_unused_argument and diagnose bad
3093 // OPT_fdiagnostics_color_EQ values.
3094 for (const Arg *A : Args) {
3095 const Option &O = A->getOption();
3096 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3097 !O.matches(options::OPT_fdiagnostics_color) &&
3098 !O.matches(options::OPT_fno_color_diagnostics) &&
3099 !O.matches(options::OPT_fno_diagnostics_color) &&
3100 !O.matches(options::OPT_fdiagnostics_color_EQ))
3101 continue;
3102
3103 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3104 StringRef Value(A->getValue());
3105 if (Value != "always" && Value != "never" && Value != "auto")
3106 D.Diag(diag::err_drv_clang_unsupported)
3107 << ("-fdiagnostics-color=" + Value).str();
3108 }
3109 A->claim();
3110 }
3111
3112 if (D.getDiags().getDiagnosticOptions().ShowColors)
3113 CmdArgs.push_back("-fcolor-diagnostics");
3114
3115 if (Args.hasArg(options::OPT_fansi_escape_codes))
3116 CmdArgs.push_back("-fansi-escape-codes");
3117
3118 if (!Args.hasFlag(options::OPT_fshow_source_location,
3119 options::OPT_fno_show_source_location))
3120 CmdArgs.push_back("-fno-show-source-location");
3121
3122 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3123 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3124
3125 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3126 ColumnDefault))
3127 CmdArgs.push_back("-fno-show-column");
3128
3129 if (!Args.hasFlag(options::OPT_fspell_checking,
3130 options::OPT_fno_spell_checking))
3131 CmdArgs.push_back("-fno-spell-checking");
3132}
3133
George Rimar91829ee2018-11-14 09:22:16 +00003134enum class DwarfFissionKind { None, Split, Single };
3135
3136static DwarfFissionKind getDebugFissionKind(const Driver &D,
3137 const ArgList &Args, Arg *&Arg) {
3138 Arg =
3139 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3140 if (!Arg)
3141 return DwarfFissionKind::None;
3142
3143 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3144 return DwarfFissionKind::Split;
3145
3146 StringRef Value = Arg->getValue();
3147 if (Value == "split")
3148 return DwarfFissionKind::Split;
3149 if (Value == "single")
3150 return DwarfFissionKind::Single;
3151
3152 D.Diag(diag::err_drv_unsupported_option_argument)
3153 << Arg->getOption().getName() << Arg->getValue();
3154 return DwarfFissionKind::None;
3155}
3156
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003157static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3158 const llvm::Triple &T, const ArgList &Args,
3159 bool EmitCodeView, bool IsWindowsMSVC,
3160 ArgStringList &CmdArgs,
3161 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003162 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003163 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003164 options::OPT_fno_debug_info_for_profiling, false) &&
3165 checkDebugInfoOption(
3166 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003167 CmdArgs.push_back("-fdebug-info-for-profiling");
3168
3169 // The 'g' groups options involve a somewhat intricate sequence of decisions
3170 // about what to pass from the driver to the frontend, but by the time they
3171 // reach cc1 they've been factored into three well-defined orthogonal choices:
3172 // * what level of debug info to generate
3173 // * what dwarf version to write
3174 // * what debugger tuning to use
3175 // This avoids having to monkey around further in cc1 other than to disable
3176 // codeview if not running in a Windows environment. Perhaps even that
3177 // decision should be made in the driver as well though.
3178 unsigned DWARFVersion = 0;
3179 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3180
3181 bool SplitDWARFInlining =
3182 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3183 options::OPT_fno_split_dwarf_inlining, true);
3184
3185 Args.ClaimAllArgs(options::OPT_g_Group);
3186
George Rimar91829ee2018-11-14 09:22:16 +00003187 Arg* SplitDWARFArg;
3188 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003189
George Rimar91829ee2018-11-14 09:22:16 +00003190 if (DwarfFission != DwarfFissionKind::None &&
3191 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3192 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003193 SplitDWARFInlining = false;
3194 }
3195
Fangrui Songe3576b02019-04-17 01:46:27 +00003196 if (const Arg *A =
3197 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3198 options::OPT_gsplit_dwarf_EQ)) {
3199 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3200
3201 // If the last option explicitly specified a debug-info level, use it.
3202 if (checkDebugInfoOption(A, Args, D, TC) &&
3203 A->getOption().matches(options::OPT_gN_Group)) {
3204 DebugInfoKind = DebugLevelToInfoKind(*A);
3205 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3206 // complicated if you've disabled inline info in the skeleton CUs
3207 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3208 // line-tables-only, so let those compose naturally in that case.
3209 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3210 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3211 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3212 SplitDWARFInlining))
3213 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003214 }
3215 }
3216
3217 // If a debugger tuning argument appeared, remember it.
3218 if (const Arg *A =
3219 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003220 if (checkDebugInfoOption(A, Args, D, TC)) {
3221 if (A->getOption().matches(options::OPT_glldb))
3222 DebuggerTuning = llvm::DebuggerKind::LLDB;
3223 else if (A->getOption().matches(options::OPT_gsce))
3224 DebuggerTuning = llvm::DebuggerKind::SCE;
3225 else
3226 DebuggerTuning = llvm::DebuggerKind::GDB;
3227 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003228 }
3229
3230 // If a -gdwarf argument appeared, remember it.
3231 if (const Arg *A =
3232 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3233 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003234 if (checkDebugInfoOption(A, Args, D, TC))
3235 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003236
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003237 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3238 if (checkDebugInfoOption(A, Args, D, TC))
3239 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003240 }
3241
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003242 // If the user asked for debug info but did not explicitly specify -gcodeview
3243 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003244 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003245 DebugInfoKind != codegenoptions::NoDebugInfo) {
3246 switch (TC.getDefaultDebugFormat()) {
3247 case codegenoptions::DIF_CodeView:
3248 EmitCodeView = true;
3249 break;
3250 case codegenoptions::DIF_DWARF:
3251 DWARFVersion = TC.GetDefaultDwarfVersion();
3252 break;
3253 }
3254 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003255
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003256 // -gline-directives-only supported only for the DWARF debug info.
3257 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3258 DebugInfoKind = codegenoptions::NoDebugInfo;
3259
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003260 // We ignore flag -gstrict-dwarf for now.
3261 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3262 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3263
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003264 // Column info is included by default for everything except SCE and
3265 // CodeView. Clang doesn't track end columns, just starting columns, which,
3266 // in theory, is fine for CodeView (and PDB). In practice, however, the
3267 // Microsoft debuggers don't handle missing end columns well, so it's better
3268 // not to include any column info.
3269 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3270 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003271 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003272 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003273 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003274 CmdArgs.push_back("-dwarf-column-info");
3275
3276 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003277 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003278 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3279 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003280 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3281 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003282 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3283 CmdArgs.push_back("-dwarf-ext-refs");
3284 CmdArgs.push_back("-fmodule-format=obj");
3285 }
3286 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003287
Aaron Puchertb207bae2019-06-26 21:36:35 +00003288 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3289 CmdArgs.push_back("-fno-split-dwarf-inlining");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003290
3291 // After we've dealt with all combinations of things that could
3292 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3293 // figure out if we need to "upgrade" it to standalone debug info.
3294 // We parse these two '-f' options whether or not they will be used,
3295 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003296 bool NeedFullDebug = Args.hasFlag(
3297 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3298 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3299 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003300 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3301 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003302 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3303 DebugInfoKind = codegenoptions::FullDebugInfo;
3304
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003305 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3306 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003307 // Source embedding is a vendor extension to DWARF v5. By now we have
3308 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003309 // fallen back to the target default, so if this is still not at least 5
3310 // we emit an error.
3311 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003312 if (DWARFVersion < 5)
3313 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003314 << A->getAsString(Args) << "-gdwarf-5";
3315 else if (checkDebugInfoOption(A, Args, D, TC))
3316 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003317 }
3318
Reid Kleckner75557712018-11-16 18:47:41 +00003319 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003320 CmdArgs.push_back("-gcodeview");
3321
Reid Kleckner75557712018-11-16 18:47:41 +00003322 // Emit codeview type hashes if requested.
3323 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3324 options::OPT_gno_codeview_ghash, false)) {
3325 CmdArgs.push_back("-gcodeview-ghash");
3326 }
3327 }
3328
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003329 // Adjust the debug info kind for the given toolchain.
3330 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3331
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003332 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3333 DebuggerTuning);
3334
3335 // -fdebug-macro turns on macro debug info generation.
3336 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3337 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003338 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3339 D, TC))
3340 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003341
3342 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003343 const auto *PubnamesArg =
3344 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3345 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003346 if (DwarfFission != DwarfFissionKind::None ||
3347 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003348 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3349 if (!PubnamesArg ||
3350 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3351 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3352 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3353 options::OPT_gpubnames)
3354 ? "-gpubnames"
3355 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003356
David Blaikie27692de2018-11-13 20:08:13 +00003357 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3358 options::OPT_fno_debug_ranges_base_address, false)) {
3359 CmdArgs.push_back("-fdebug-ranges-base-address");
3360 }
3361
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003362 // -gdwarf-aranges turns on the emission of the aranges section in the
3363 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003364 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003365 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3366 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3367 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3368 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003369 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003370 CmdArgs.push_back("-generate-arange-section");
3371 }
3372
3373 if (Args.hasFlag(options::OPT_fdebug_types_section,
3374 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003375 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003376 D.Diag(diag::err_drv_unsupported_opt_for_target)
3377 << Args.getLastArg(options::OPT_fdebug_types_section)
3378 ->getAsString(Args)
3379 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003380 } else if (checkDebugInfoOption(
3381 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3382 TC)) {
3383 CmdArgs.push_back("-mllvm");
3384 CmdArgs.push_back("-generate-type-units");
3385 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003386 }
3387
Paul Robinson1787f812017-09-28 18:37:02 +00003388 // Decide how to render forward declarations of template instantiations.
3389 // SCE wants full descriptions, others just get them in the name.
3390 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3391 CmdArgs.push_back("-debug-forward-template-params");
3392
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003393 // Do we need to explicitly import anonymous namespaces into the parent
3394 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003395 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3396 CmdArgs.push_back("-dwarf-explicit-import");
3397
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003398 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003399}
3400
David L. Jonesf561aba2017-03-08 01:02:16 +00003401void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3402 const InputInfo &Output, const InputInfoList &Inputs,
3403 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003404 const auto &TC = getToolChain();
3405 const llvm::Triple &RawTriple = TC.getTriple();
3406 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003407 const std::string &TripleStr = Triple.getTriple();
3408
3409 bool KernelOrKext =
3410 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003411 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003412 ArgStringList CmdArgs;
3413
3414 // Check number of inputs for sanity. We need at least one input.
3415 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003416 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003417 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003418 // second input. Module precompilation accepts a list of header files to
3419 // include as part of the module. All other jobs are expected to have exactly
3420 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003421 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003422 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003423 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003424 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3425
3426 // A header module compilation doesn't have a main input file, so invent a
3427 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003428 const char *ModuleName = [&]{
3429 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3430 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3431 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003432 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003433
3434 const InputInfo &Input =
3435 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3436
3437 InputInfoList ModuleHeaderInputs;
3438 const InputInfo *CudaDeviceInput = nullptr;
3439 const InputInfo *OpenMPDeviceInput = nullptr;
3440 for (const InputInfo &I : Inputs) {
3441 if (&I == &Input) {
3442 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003443 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003444 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003445 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003446 if (I.getType() != Expected) {
3447 D.Diag(diag::err_drv_module_header_wrong_kind)
3448 << I.getFilename() << types::getTypeName(I.getType())
3449 << types::getTypeName(Expected);
3450 }
3451 ModuleHeaderInputs.push_back(I);
3452 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3453 CudaDeviceInput = &I;
3454 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3455 OpenMPDeviceInput = &I;
3456 } else {
3457 llvm_unreachable("unexpectedly given multiple inputs");
3458 }
3459 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003460
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003461 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003462 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003463 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003464
Yaxun Liu398612b2018-05-08 21:02:12 +00003465 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3466 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3467 // Windows), we need to pass Windows-specific flags to cc1.
Fangrui Songe6e09562019-07-12 13:21:58 +00003468 if (IsCuda || IsHIP)
David L. Jonesf561aba2017-03-08 01:02:16 +00003469 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003470
3471 // C++ is not supported for IAMCU.
3472 if (IsIAMCU && types::isCXX(Input.getType()))
3473 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3474
3475 // Invoke ourselves in -cc1 mode.
3476 //
3477 // FIXME: Implement custom jobs for internal actions.
3478 CmdArgs.push_back("-cc1");
3479
3480 // Add the "effective" target triple.
3481 CmdArgs.push_back("-triple");
3482 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3483
3484 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3485 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3486 Args.ClaimAllArgs(options::OPT_MJ);
3487 }
3488
Yaxun Liu398612b2018-05-08 21:02:12 +00003489 if (IsCuda || IsHIP) {
3490 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3491 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003492 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003493 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3494 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003495 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3496 ->getTriple()
3497 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003498 else {
3499 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003500 NormalizedTriple =
3501 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3502 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3503 ->getTriple()
3504 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003505 if (IsCuda) {
3506 // We need to figure out which CUDA version we're compiling for, as that
3507 // determines how we load and launch GPU kernels.
3508 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3509 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3510 assert(CTC && "Expected valid CUDA Toolchain.");
3511 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3512 CmdArgs.push_back(Args.MakeArgString(
3513 Twine("-target-sdk-version=") +
3514 CudaVersionToString(CTC->CudaInstallation.version())));
3515 }
3516 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003517 CmdArgs.push_back("-aux-triple");
3518 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3519 }
3520
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003521 if (IsOpenMPDevice) {
3522 // We have to pass the triple of the host if compiling for an OpenMP device.
3523 std::string NormalizedTriple =
3524 C.getSingleOffloadToolChain<Action::OFK_Host>()
3525 ->getTriple()
3526 .normalize();
3527 CmdArgs.push_back("-aux-triple");
3528 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3529 }
3530
David L. Jonesf561aba2017-03-08 01:02:16 +00003531 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3532 Triple.getArch() == llvm::Triple::thumb)) {
3533 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3534 unsigned Version;
3535 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3536 if (Version < 7)
3537 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3538 << TripleStr;
3539 }
3540
3541 // Push all default warning arguments that are specific to
3542 // the given target. These come before user provided warning options
3543 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003544 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003545
3546 // Select the appropriate action.
3547 RewriteKind rewriteKind = RK_None;
3548
Nico Weberb28ffd82019-07-27 01:13:00 +00003549 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
3550 // it claims when not running an assembler. Otherwise, clang would emit
3551 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
3552 // flags while debugging something. That'd be somewhat inconvenient, and it's
3553 // also inconsistent with most other flags -- we don't warn on
3554 // -ffunction-sections not being used in -E mode either for example, even
3555 // though it's not really used either.
3556 if (!isa<AssembleJobAction>(JA)) {
3557 // The args claimed here should match the args used in
3558 // CollectArgsForIntegratedAssembler().
3559 if (TC.useIntegratedAs()) {
3560 Args.ClaimAllArgs(options::OPT_mrelax_all);
3561 Args.ClaimAllArgs(options::OPT_mno_relax_all);
3562 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
3563 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
3564 switch (C.getDefaultToolChain().getArch()) {
3565 case llvm::Triple::arm:
3566 case llvm::Triple::armeb:
3567 case llvm::Triple::thumb:
3568 case llvm::Triple::thumbeb:
3569 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
Bjorn Pettersson60c1ee22019-07-27 17:09:08 +00003570 break;
Nico Weberb28ffd82019-07-27 01:13:00 +00003571 default:
3572 break;
3573 }
3574 }
3575 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
3576 Args.ClaimAllArgs(options::OPT_Xassembler);
3577 }
3578
David L. Jonesf561aba2017-03-08 01:02:16 +00003579 if (isa<AnalyzeJobAction>(JA)) {
3580 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3581 CmdArgs.push_back("-analyze");
3582 } else if (isa<MigrateJobAction>(JA)) {
3583 CmdArgs.push_back("-migrate");
3584 } else if (isa<PreprocessJobAction>(JA)) {
3585 if (Output.getType() == types::TY_Dependencies)
3586 CmdArgs.push_back("-Eonly");
3587 else {
3588 CmdArgs.push_back("-E");
3589 if (Args.hasArg(options::OPT_rewrite_objc) &&
3590 !Args.hasArg(options::OPT_g_Group))
3591 CmdArgs.push_back("-P");
3592 }
3593 } else if (isa<AssembleJobAction>(JA)) {
3594 CmdArgs.push_back("-emit-obj");
3595
3596 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3597
3598 // Also ignore explicit -force_cpusubtype_ALL option.
3599 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3600 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003601 if (JA.getType() == types::TY_Nothing)
3602 CmdArgs.push_back("-fsyntax-only");
3603 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003604 CmdArgs.push_back(IsHeaderModulePrecompile
3605 ? "-emit-header-module"
3606 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003607 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003608 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003609 } else if (isa<VerifyPCHJobAction>(JA)) {
3610 CmdArgs.push_back("-verify-pch");
3611 } else {
3612 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3613 "Invalid action for clang tool.");
3614 if (JA.getType() == types::TY_Nothing) {
3615 CmdArgs.push_back("-fsyntax-only");
3616 } else if (JA.getType() == types::TY_LLVM_IR ||
3617 JA.getType() == types::TY_LTO_IR) {
3618 CmdArgs.push_back("-emit-llvm");
3619 } else if (JA.getType() == types::TY_LLVM_BC ||
3620 JA.getType() == types::TY_LTO_BC) {
3621 CmdArgs.push_back("-emit-llvm-bc");
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003622 } else if (JA.getType() == types::TY_IFS) {
3623 StringRef StubFormat =
3624 llvm::StringSwitch<StringRef>(
3625 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3626 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
3627 : "")
3628 .Case("experimental-yaml-elf-v1", "experimental-yaml-elf-v1")
3629 .Case("experimental-tapi-elf-v1", "experimental-tapi-elf-v1")
3630 .Default("");
3631
3632 if (StubFormat.empty())
3633 D.Diag(diag::err_drv_invalid_value)
3634 << "Must specify a valid interface stub format type using "
3635 << "-interface-stub-version=<experimental-tapi-elf-v1 | "
3636 "experimental-yaml-elf-v1>";
3637
3638 CmdArgs.push_back("-emit-interface-stubs");
3639 CmdArgs.push_back(
3640 Args.MakeArgString(Twine("-interface-stub-version=") + StubFormat));
David L. Jonesf561aba2017-03-08 01:02:16 +00003641 } else if (JA.getType() == types::TY_PP_Asm) {
3642 CmdArgs.push_back("-S");
3643 } else if (JA.getType() == types::TY_AST) {
3644 CmdArgs.push_back("-emit-pch");
3645 } else if (JA.getType() == types::TY_ModuleFile) {
3646 CmdArgs.push_back("-module-file-info");
3647 } else if (JA.getType() == types::TY_RewrittenObjC) {
3648 CmdArgs.push_back("-rewrite-objc");
3649 rewriteKind = RK_NonFragile;
3650 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3651 CmdArgs.push_back("-rewrite-objc");
3652 rewriteKind = RK_Fragile;
3653 } else {
3654 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3655 }
3656
3657 // Preserve use-list order by default when emitting bitcode, so that
3658 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3659 // same result as running passes here. For LTO, we don't need to preserve
3660 // the use-list order, since serialization to bitcode is part of the flow.
3661 if (JA.getType() == types::TY_LLVM_BC)
3662 CmdArgs.push_back("-emit-llvm-uselists");
3663
Artem Belevichecb178b2018-03-21 22:22:59 +00003664 // Device-side jobs do not support LTO.
3665 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3666 JA.isDeviceOffloading(Action::OFK_Host));
3667
3668 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003669 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3670
Paul Robinsond23f2a82017-07-13 21:25:47 +00003671 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3672 // does not support LTO unit features (CFI, whole program vtable opt)
3673 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003674 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003675 D.getLTOMode() == LTOK_Full)
3676 CmdArgs.push_back("-flto-unit");
3677 }
3678 }
3679
3680 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3681 if (!types::isLLVMIR(Input.getType()))
Bob Haarman79434642019-07-15 20:51:44 +00003682 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003683 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3684 }
3685
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003686 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003687 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3688
David L. Jonesf561aba2017-03-08 01:02:16 +00003689 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003690 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003691 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3692 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3693 // Add flags implied by -fembed-bitcode.
3694 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3695 // Disable all llvm IR level optimizations.
3696 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003697
Fangrui Song2632ebb2019-05-30 02:30:04 +00003698 // Render target options such as -fuse-init-array on modern ELF platforms.
3699 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3700
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003701 // reject options that shouldn't be supported in bitcode
3702 // also reject kernel/kext
3703 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3704 options::OPT_mkernel,
3705 options::OPT_fapple_kext,
3706 options::OPT_ffunction_sections,
3707 options::OPT_fno_function_sections,
3708 options::OPT_fdata_sections,
3709 options::OPT_fno_data_sections,
3710 options::OPT_funique_section_names,
3711 options::OPT_fno_unique_section_names,
3712 options::OPT_mrestrict_it,
3713 options::OPT_mno_restrict_it,
3714 options::OPT_mstackrealign,
3715 options::OPT_mno_stackrealign,
3716 options::OPT_mstack_alignment,
3717 options::OPT_mcmodel_EQ,
3718 options::OPT_mlong_calls,
3719 options::OPT_mno_long_calls,
3720 options::OPT_ggnu_pubnames,
3721 options::OPT_gdwarf_aranges,
3722 options::OPT_fdebug_types_section,
3723 options::OPT_fno_debug_types_section,
3724 options::OPT_fdwarf_directory_asm,
3725 options::OPT_fno_dwarf_directory_asm,
3726 options::OPT_mrelax_all,
3727 options::OPT_mno_relax_all,
3728 options::OPT_ftrap_function_EQ,
3729 options::OPT_ffixed_r9,
3730 options::OPT_mfix_cortex_a53_835769,
3731 options::OPT_mno_fix_cortex_a53_835769,
3732 options::OPT_ffixed_x18,
3733 options::OPT_mglobal_merge,
3734 options::OPT_mno_global_merge,
3735 options::OPT_mred_zone,
3736 options::OPT_mno_red_zone,
3737 options::OPT_Wa_COMMA,
3738 options::OPT_Xassembler,
3739 options::OPT_mllvm,
3740 };
3741 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003742 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003743 std::end(kBitcodeOptionBlacklist))
3744 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3745
3746 // Render the CodeGen options that need to be passed.
3747 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3748 options::OPT_fno_optimize_sibling_calls))
3749 CmdArgs.push_back("-mdisable-tail-calls");
3750
3751 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3752 CmdArgs);
3753
3754 // Render ABI arguments
3755 switch (TC.getArch()) {
3756 default: break;
3757 case llvm::Triple::arm:
3758 case llvm::Triple::armeb:
3759 case llvm::Triple::thumbeb:
3760 RenderARMABI(Triple, Args, CmdArgs);
3761 break;
3762 case llvm::Triple::aarch64:
3763 case llvm::Triple::aarch64_be:
3764 RenderAArch64ABI(Triple, Args, CmdArgs);
3765 break;
3766 }
3767
3768 // Optimization level for CodeGen.
3769 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3770 if (A->getOption().matches(options::OPT_O4)) {
3771 CmdArgs.push_back("-O3");
3772 D.Diag(diag::warn_O4_is_O3);
3773 } else {
3774 A->render(Args, CmdArgs);
3775 }
3776 }
3777
3778 // Input/Output file.
3779 if (Output.getType() == types::TY_Dependencies) {
3780 // Handled with other dependency code.
3781 } else if (Output.isFilename()) {
3782 CmdArgs.push_back("-o");
3783 CmdArgs.push_back(Output.getFilename());
3784 } else {
3785 assert(Output.isNothing() && "Input output.");
3786 }
3787
3788 for (const auto &II : Inputs) {
3789 addDashXForInput(Args, II, CmdArgs);
3790 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003791 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003792 else
3793 II.getInputArg().renderAsInput(Args, CmdArgs);
3794 }
3795
3796 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3797 CmdArgs, Inputs));
3798 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003799 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003800
David L. Jonesf561aba2017-03-08 01:02:16 +00003801 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3802 CmdArgs.push_back("-fembed-bitcode=marker");
3803
3804 // We normally speed up the clang process a bit by skipping destructors at
3805 // exit, but when we're generating diagnostics we can rely on some of the
3806 // cleanup.
3807 if (!C.isForDiagnostics())
3808 CmdArgs.push_back("-disable-free");
3809
David L. Jonesf561aba2017-03-08 01:02:16 +00003810#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003811 const bool IsAssertBuild = false;
3812#else
3813 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003814#endif
3815
Eric Fiselier123c7492018-02-07 18:36:51 +00003816 // Disable the verification pass in -asserts builds.
3817 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003818 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003819
3820 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003821 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3822 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003823 CmdArgs.push_back("-discard-value-names");
3824
David L. Jonesf561aba2017-03-08 01:02:16 +00003825 // Set the main file name, so that debug info works even with
3826 // -save-temps.
3827 CmdArgs.push_back("-main-file-name");
3828 CmdArgs.push_back(getBaseInputName(Args, Input));
3829
3830 // Some flags which affect the language (via preprocessor
3831 // defines).
3832 if (Args.hasArg(options::OPT_static))
3833 CmdArgs.push_back("-static-define");
3834
Martin Storsjo434ef832018-08-06 19:48:44 +00003835 if (Args.hasArg(options::OPT_municode))
3836 CmdArgs.push_back("-DUNICODE");
3837
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003838 if (isa<AnalyzeJobAction>(JA))
3839 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003840
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003841 // Enable compatilibily mode to avoid analyzer-config related errors.
3842 // Since we can't access frontend flags through hasArg, let's manually iterate
3843 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003844 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003845 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003846 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3847 FoundAnalyzerConfig = true;
3848 break;
3849 }
3850 if (!FoundAnalyzerConfig)
3851 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3852 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3853 FoundAnalyzerConfig = true;
3854 break;
3855 }
3856 if (FoundAnalyzerConfig)
3857 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003858
David L. Jonesf561aba2017-03-08 01:02:16 +00003859 CheckCodeGenerationOptions(D, Args);
3860
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003861 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003862 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3863 if (FunctionAlignment) {
3864 CmdArgs.push_back("-function-alignment");
3865 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3866 }
3867
David L. Jonesf561aba2017-03-08 01:02:16 +00003868 llvm::Reloc::Model RelocationModel;
3869 unsigned PICLevel;
3870 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003871 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003872
3873 const char *RMName = RelocationModelName(RelocationModel);
3874
3875 if ((RelocationModel == llvm::Reloc::ROPI ||
3876 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3877 types::isCXX(Input.getType()) &&
3878 !Args.hasArg(options::OPT_fallow_unsupported))
3879 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3880
3881 if (RMName) {
3882 CmdArgs.push_back("-mrelocation-model");
3883 CmdArgs.push_back(RMName);
3884 }
3885 if (PICLevel > 0) {
3886 CmdArgs.push_back("-pic-level");
3887 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3888 if (IsPIE)
3889 CmdArgs.push_back("-pic-is-pie");
3890 }
3891
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003892 if (RelocationModel == llvm::Reloc::ROPI ||
3893 RelocationModel == llvm::Reloc::ROPI_RWPI)
3894 CmdArgs.push_back("-fropi");
3895 if (RelocationModel == llvm::Reloc::RWPI ||
3896 RelocationModel == llvm::Reloc::ROPI_RWPI)
3897 CmdArgs.push_back("-frwpi");
3898
David L. Jonesf561aba2017-03-08 01:02:16 +00003899 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3900 CmdArgs.push_back("-meabi");
3901 CmdArgs.push_back(A->getValue());
3902 }
3903
3904 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003905 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003906 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003907 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3908 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003909 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003910 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003911 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003912 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003913
3914 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3915
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003916 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3917 options::OPT_fno_merge_all_constants, false))
3918 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003919
Manoj Guptada08f6a2018-07-19 00:44:52 +00003920 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3921 options::OPT_fdelete_null_pointer_checks, false))
3922 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3923
David L. Jonesf561aba2017-03-08 01:02:16 +00003924 // LLVM Code Generator Options.
3925
3926 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3927 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3928 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3929 options::OPT_frewrite_map_file_EQ)) {
3930 StringRef Map = A->getValue();
3931 if (!llvm::sys::fs::exists(Map)) {
3932 D.Diag(diag::err_drv_no_such_file) << Map;
3933 } else {
3934 CmdArgs.push_back("-frewrite-map-file");
3935 CmdArgs.push_back(A->getValue());
3936 A->claim();
3937 }
3938 }
3939 }
3940
3941 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3942 StringRef v = A->getValue();
3943 CmdArgs.push_back("-mllvm");
3944 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3945 A->claim();
3946 }
3947
3948 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3949 true))
3950 CmdArgs.push_back("-fno-jump-tables");
3951
Dehao Chen5e97f232017-08-24 21:37:33 +00003952 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3953 options::OPT_fno_profile_sample_accurate, false))
3954 CmdArgs.push_back("-fprofile-sample-accurate");
3955
David L. Jonesf561aba2017-03-08 01:02:16 +00003956 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3957 options::OPT_fno_preserve_as_comments, true))
3958 CmdArgs.push_back("-fno-preserve-as-comments");
3959
3960 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3961 CmdArgs.push_back("-mregparm");
3962 CmdArgs.push_back(A->getValue());
3963 }
3964
3965 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3966 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003967 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003968 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003969 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003970 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3971 CmdArgs.push_back("-fpcc-struct-return");
3972 } else {
3973 assert(A->getOption().matches(options::OPT_freg_struct_return));
3974 CmdArgs.push_back("-freg-struct-return");
3975 }
3976 }
3977
3978 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3979 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3980
Yuanfang Chenff22ec32019-07-20 22:50:50 +00003981 CodeGenOptions::FramePointerKind FPKeepKind =
3982 getFramePointerKind(Args, RawTriple);
3983 const char *FPKeepKindStr = nullptr;
3984 switch (FPKeepKind) {
3985 case CodeGenOptions::FramePointerKind::None:
3986 FPKeepKindStr = "-mframe-pointer=none";
3987 break;
3988 case CodeGenOptions::FramePointerKind::NonLeaf:
3989 FPKeepKindStr = "-mframe-pointer=non-leaf";
3990 break;
3991 case CodeGenOptions::FramePointerKind::All:
3992 FPKeepKindStr = "-mframe-pointer=all";
3993 break;
Fangrui Songdc039662019-07-12 02:01:51 +00003994 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +00003995 assert(FPKeepKindStr && "unknown FramePointerKind");
3996 CmdArgs.push_back(FPKeepKindStr);
3997
David L. Jonesf561aba2017-03-08 01:02:16 +00003998 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3999 options::OPT_fno_zero_initialized_in_bss))
4000 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4001
4002 bool OFastEnabled = isOptimizationLevelFast(Args);
4003 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4004 // enabled. This alias option is being used to simplify the hasFlag logic.
4005 OptSpecifier StrictAliasingAliasOption =
4006 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4007 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4008 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004009 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004010 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4011 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4012 CmdArgs.push_back("-relaxed-aliasing");
4013 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4014 options::OPT_fno_struct_path_tbaa))
4015 CmdArgs.push_back("-no-struct-path-tbaa");
4016 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4017 false))
4018 CmdArgs.push_back("-fstrict-enums");
4019 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4020 true))
4021 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00004022 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4023 options::OPT_fno_allow_editor_placeholders, false))
4024 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00004025 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4026 options::OPT_fno_strict_vtable_pointers,
4027 false))
4028 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00004029 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4030 options::OPT_fno_force_emit_vtables,
4031 false))
4032 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00004033 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4034 options::OPT_fno_optimize_sibling_calls))
4035 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00004036 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00004037 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00004038 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00004039
Wei Mi9b3d6272017-10-16 16:50:27 +00004040 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4041 options::OPT_fno_fine_grained_bitfield_accesses);
4042
David L. Jonesf561aba2017-03-08 01:02:16 +00004043 // Handle segmented stacks.
4044 if (Args.hasArg(options::OPT_fsplit_stack))
4045 CmdArgs.push_back("-split-stacks");
4046
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004047 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004048
Fangrui Songc46d78d2019-07-12 02:32:15 +00004049 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_64,
4050 options::OPT_mlong_double_128)) {
Fangrui Song11cb39c2019-07-09 00:27:43 +00004051 if (TC.getArch() == llvm::Triple::x86 ||
4052 TC.getArch() == llvm::Triple::x86_64 ||
Fangrui Songc46d78d2019-07-12 02:32:15 +00004053 TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64())
4054 A->render(Args, CmdArgs);
4055 else
Fangrui Song11cb39c2019-07-09 00:27:43 +00004056 D.Diag(diag::err_drv_unsupported_opt_for_target)
4057 << A->getAsString(Args) << TripleStr;
Fangrui Song11cb39c2019-07-09 00:27:43 +00004058 }
4059
David L. Jonesf561aba2017-03-08 01:02:16 +00004060 // Decide whether to use verbose asm. Verbose assembly is the default on
4061 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004062 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004063 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4064 IsIntegratedAssemblerDefault) ||
4065 Args.hasArg(options::OPT_dA))
4066 CmdArgs.push_back("-masm-verbose");
4067
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004068 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004069 CmdArgs.push_back("-no-integrated-as");
4070
4071 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4072 CmdArgs.push_back("-mdebug-pass");
4073 CmdArgs.push_back("Structure");
4074 }
4075 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4076 CmdArgs.push_back("-mdebug-pass");
4077 CmdArgs.push_back("Arguments");
4078 }
4079
4080 // Enable -mconstructor-aliases except on darwin, where we have to work around
4081 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4082 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004083 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004084 CmdArgs.push_back("-mconstructor-aliases");
4085
4086 // Darwin's kernel doesn't support guard variables; just die if we
4087 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004088 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004089 CmdArgs.push_back("-fforbid-guard-variables");
4090
4091 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4092 false)) {
4093 CmdArgs.push_back("-mms-bitfields");
4094 }
4095
4096 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4097 options::OPT_mno_pie_copy_relocations,
4098 false)) {
4099 CmdArgs.push_back("-mpie-copy-relocations");
4100 }
4101
Sriraman Tallam5c651482017-11-07 19:37:51 +00004102 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4103 CmdArgs.push_back("-fno-plt");
4104 }
4105
Vedant Kumardf502592017-09-12 22:51:53 +00004106 // -fhosted is default.
4107 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4108 // use Freestanding.
4109 bool Freestanding =
4110 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4111 KernelOrKext;
4112 if (Freestanding)
4113 CmdArgs.push_back("-ffreestanding");
4114
David L. Jonesf561aba2017-03-08 01:02:16 +00004115 // This is a coarse approximation of what llvm-gcc actually does, both
4116 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4117 // complicated ways.
4118 bool AsynchronousUnwindTables =
4119 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4120 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004121 (TC.IsUnwindTablesDefault(Args) ||
4122 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004123 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004124 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4125 AsynchronousUnwindTables))
4126 CmdArgs.push_back("-munwind-tables");
4127
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004128 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004129
David L. Jonesf561aba2017-03-08 01:02:16 +00004130 // FIXME: Handle -mtune=.
4131 (void)Args.hasArg(options::OPT_mtune_EQ);
4132
4133 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4134 CmdArgs.push_back("-mcode-model");
4135 CmdArgs.push_back(A->getValue());
4136 }
4137
4138 // Add the target cpu
4139 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4140 if (!CPU.empty()) {
4141 CmdArgs.push_back("-target-cpu");
4142 CmdArgs.push_back(Args.MakeArgString(CPU));
4143 }
4144
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004145 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004146
David L. Jonesf561aba2017-03-08 01:02:16 +00004147 // These two are potentially updated by AddClangCLArgs.
4148 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4149 bool EmitCodeView = false;
4150
4151 // Add clang-cl arguments.
4152 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004153 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004154 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4155
George Rimar91829ee2018-11-14 09:22:16 +00004156 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004157 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004158 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004159
4160 // Add the split debug info name to the command lines here so we
4161 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004162 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004163 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004164 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4165 isa<BackendJobAction>(JA));
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004166 if (SplitDWARF) {
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004167 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4168 CmdArgs.push_back("-split-dwarf-file");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004169 CmdArgs.push_back(SplitDWARFOut);
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004170 if (DwarfFission == DwarfFissionKind::Split) {
4171 CmdArgs.push_back("-split-dwarf-output");
4172 CmdArgs.push_back(SplitDWARFOut);
4173 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004174 }
4175
David L. Jonesf561aba2017-03-08 01:02:16 +00004176 // Pass the linker version in use.
4177 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4178 CmdArgs.push_back("-target-linker-version");
4179 CmdArgs.push_back(A->getValue());
4180 }
4181
David L. Jonesf561aba2017-03-08 01:02:16 +00004182 // Explicitly error on some things we know we don't support and can't just
4183 // ignore.
4184 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4185 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004186 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004187 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004188 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4189 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4190 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4191 << Unsupported->getOption().getName();
4192 }
Eric Christopher758aad72017-03-21 22:06:18 +00004193 // The faltivec option has been superseded by the maltivec option.
4194 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4195 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4196 << Unsupported->getOption().getName()
4197 << "please use -maltivec and include altivec.h explicitly";
4198 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4199 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4200 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004201 }
4202
4203 Args.AddAllArgs(CmdArgs, options::OPT_v);
4204 Args.AddLastArg(CmdArgs, options::OPT_H);
4205 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4206 CmdArgs.push_back("-header-include-file");
4207 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4208 : "-");
4209 }
4210 Args.AddLastArg(CmdArgs, options::OPT_P);
4211 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4212
4213 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4214 CmdArgs.push_back("-diagnostic-log-file");
4215 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4216 : "-");
4217 }
4218
David L. Jonesf561aba2017-03-08 01:02:16 +00004219 bool UseSeparateSections = isUseSeparateSections(Triple);
4220
4221 if (Args.hasFlag(options::OPT_ffunction_sections,
4222 options::OPT_fno_function_sections, UseSeparateSections)) {
4223 CmdArgs.push_back("-ffunction-sections");
4224 }
4225
4226 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4227 UseSeparateSections)) {
4228 CmdArgs.push_back("-fdata-sections");
4229 }
4230
4231 if (!Args.hasFlag(options::OPT_funique_section_names,
4232 options::OPT_fno_unique_section_names, true))
4233 CmdArgs.push_back("-fno-unique-section-names");
4234
Nico Weber908b6972019-06-26 17:51:47 +00004235 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4236 options::OPT_finstrument_functions_after_inlining,
4237 options::OPT_finstrument_function_entry_bare);
David L. Jonesf561aba2017-03-08 01:02:16 +00004238
Artem Belevichc30bcad2018-01-24 17:41:02 +00004239 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4240 // sampling, overhead of call arc collection is way too high and there's no
4241 // way to collect the output.
4242 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004243 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004244
Nico Weber908b6972019-06-26 17:51:47 +00004245 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
Richard Smithf667ad52017-08-26 01:04:35 +00004246
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004247 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004248 if (RawTriple.isPS4CPU() &&
4249 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004250 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4251 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004252 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004253
4254 // Pass options for controlling the default header search paths.
4255 if (Args.hasArg(options::OPT_nostdinc)) {
4256 CmdArgs.push_back("-nostdsysteminc");
4257 CmdArgs.push_back("-nobuiltininc");
4258 } else {
4259 if (Args.hasArg(options::OPT_nostdlibinc))
4260 CmdArgs.push_back("-nostdsysteminc");
4261 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4262 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4263 }
4264
4265 // Pass the path to compiler resource files.
4266 CmdArgs.push_back("-resource-dir");
4267 CmdArgs.push_back(D.ResourceDir.c_str());
4268
4269 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4270
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004271 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004272
4273 // Add preprocessing options like -I, -D, etc. if we are using the
4274 // preprocessor.
4275 //
4276 // FIXME: Support -fpreprocessed
4277 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4278 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4279
4280 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4281 // that "The compiler can only warn and ignore the option if not recognized".
4282 // When building with ccache, it will pass -D options to clang even on
4283 // preprocessed inputs and configure concludes that -fPIC is not supported.
4284 Args.ClaimAllArgs(options::OPT_D);
4285
4286 // Manually translate -O4 to -O3; let clang reject others.
4287 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4288 if (A->getOption().matches(options::OPT_O4)) {
4289 CmdArgs.push_back("-O3");
4290 D.Diag(diag::warn_O4_is_O3);
4291 } else {
4292 A->render(Args, CmdArgs);
4293 }
4294 }
4295
4296 // Warn about ignored options to clang.
4297 for (const Arg *A :
4298 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4299 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4300 A->claim();
4301 }
4302
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004303 for (const Arg *A :
4304 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4305 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4306 A->claim();
4307 }
4308
David L. Jonesf561aba2017-03-08 01:02:16 +00004309 claimNoWarnArgs(Args);
4310
4311 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4312
4313 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4314 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4315 CmdArgs.push_back("-pedantic");
4316 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4317 Args.AddLastArg(CmdArgs, options::OPT_w);
4318
Leonard Chanf921d852018-06-04 16:07:52 +00004319 // Fixed point flags
4320 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4321 /*Default=*/false))
4322 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4323
David L. Jonesf561aba2017-03-08 01:02:16 +00004324 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4325 // (-ansi is equivalent to -std=c89 or -std=c++98).
4326 //
4327 // If a std is supplied, only add -trigraphs if it follows the
4328 // option.
4329 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004330 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4331 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004332 if (Std->getOption().matches(options::OPT_ansi))
4333 if (types::isCXX(InputType))
4334 CmdArgs.push_back("-std=c++98");
4335 else
4336 CmdArgs.push_back("-std=c89");
4337 else
4338 Std->render(Args, CmdArgs);
4339
4340 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4341 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4342 options::OPT_ftrigraphs,
4343 options::OPT_fno_trigraphs))
4344 if (A != Std)
4345 A->render(Args, CmdArgs);
4346 } else {
4347 // Honor -std-default.
4348 //
4349 // FIXME: Clang doesn't correctly handle -std= when the input language
4350 // doesn't match. For the time being just ignore this for C++ inputs;
4351 // eventually we want to do all the standard defaulting here instead of
4352 // splitting it between the driver and clang -cc1.
4353 if (!types::isCXX(InputType))
4354 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4355 /*Joined=*/true);
4356 else if (IsWindowsMSVC)
4357 ImplyVCPPCXXVer = true;
4358
4359 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4360 options::OPT_fno_trigraphs);
4361 }
4362
4363 // GCC's behavior for -Wwrite-strings is a bit strange:
4364 // * In C, this "warning flag" changes the types of string literals from
4365 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4366 // for the discarded qualifier.
4367 // * In C++, this is just a normal warning flag.
4368 //
4369 // Implementing this warning correctly in C is hard, so we follow GCC's
4370 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4371 // a non-const char* in C, rather than using this crude hack.
4372 if (!types::isCXX(InputType)) {
4373 // FIXME: This should behave just like a warning flag, and thus should also
4374 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4375 Arg *WriteStrings =
4376 Args.getLastArg(options::OPT_Wwrite_strings,
4377 options::OPT_Wno_write_strings, options::OPT_w);
4378 if (WriteStrings &&
4379 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4380 CmdArgs.push_back("-fconst-strings");
4381 }
4382
4383 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4384 // during C++ compilation, which it is by default. GCC keeps this define even
4385 // in the presence of '-w', match this behavior bug-for-bug.
4386 if (types::isCXX(InputType) &&
4387 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4388 true)) {
4389 CmdArgs.push_back("-fdeprecated-macro");
4390 }
4391
4392 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4393 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4394 if (Asm->getOption().matches(options::OPT_fasm))
4395 CmdArgs.push_back("-fgnu-keywords");
4396 else
4397 CmdArgs.push_back("-fno-gnu-keywords");
4398 }
4399
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004400 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004401 CmdArgs.push_back("-fno-dwarf-directory-asm");
4402
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004403 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004404 CmdArgs.push_back("-fno-autolink");
4405
4406 // Add in -fdebug-compilation-dir if necessary.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00004407 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00004408
Paul Robinson9b292b42018-07-10 15:15:24 +00004409 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004410
4411 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4412 options::OPT_ftemplate_depth_EQ)) {
4413 CmdArgs.push_back("-ftemplate-depth");
4414 CmdArgs.push_back(A->getValue());
4415 }
4416
4417 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4418 CmdArgs.push_back("-foperator-arrow-depth");
4419 CmdArgs.push_back(A->getValue());
4420 }
4421
4422 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4423 CmdArgs.push_back("-fconstexpr-depth");
4424 CmdArgs.push_back(A->getValue());
4425 }
4426
4427 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4428 CmdArgs.push_back("-fconstexpr-steps");
4429 CmdArgs.push_back(A->getValue());
4430 }
4431
4432 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4433 CmdArgs.push_back("-fbracket-depth");
4434 CmdArgs.push_back(A->getValue());
4435 }
4436
4437 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4438 options::OPT_Wlarge_by_value_copy_def)) {
4439 if (A->getNumValues()) {
4440 StringRef bytes = A->getValue();
4441 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4442 } else
4443 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4444 }
4445
4446 if (Args.hasArg(options::OPT_relocatable_pch))
4447 CmdArgs.push_back("-relocatable-pch");
4448
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004449 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4450 static const char *kCFABIs[] = {
4451 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4452 };
4453
4454 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4455 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4456 else
4457 A->render(Args, CmdArgs);
4458 }
4459
David L. Jonesf561aba2017-03-08 01:02:16 +00004460 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4461 CmdArgs.push_back("-fconstant-string-class");
4462 CmdArgs.push_back(A->getValue());
4463 }
4464
4465 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4466 CmdArgs.push_back("-ftabstop");
4467 CmdArgs.push_back(A->getValue());
4468 }
4469
Sean Eveson5110d4f2018-01-08 13:42:26 +00004470 if (Args.hasFlag(options::OPT_fstack_size_section,
4471 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4472 CmdArgs.push_back("-fstack-size-section");
4473
David L. Jonesf561aba2017-03-08 01:02:16 +00004474 CmdArgs.push_back("-ferror-limit");
4475 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4476 CmdArgs.push_back(A->getValue());
4477 else
4478 CmdArgs.push_back("19");
4479
4480 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4481 CmdArgs.push_back("-fmacro-backtrace-limit");
4482 CmdArgs.push_back(A->getValue());
4483 }
4484
4485 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4486 CmdArgs.push_back("-ftemplate-backtrace-limit");
4487 CmdArgs.push_back(A->getValue());
4488 }
4489
4490 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4491 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4492 CmdArgs.push_back(A->getValue());
4493 }
4494
4495 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4496 CmdArgs.push_back("-fspell-checking-limit");
4497 CmdArgs.push_back(A->getValue());
4498 }
4499
4500 // Pass -fmessage-length=.
4501 CmdArgs.push_back("-fmessage-length");
4502 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4503 CmdArgs.push_back(A->getValue());
4504 } else {
4505 // If -fmessage-length=N was not specified, determine whether this is a
4506 // terminal and, if so, implicitly define -fmessage-length appropriately.
4507 unsigned N = llvm::sys::Process::StandardErrColumns();
4508 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4509 }
4510
4511 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4512 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4513 options::OPT_fvisibility_ms_compat)) {
4514 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4515 CmdArgs.push_back("-fvisibility");
4516 CmdArgs.push_back(A->getValue());
4517 } else {
4518 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4519 CmdArgs.push_back("-fvisibility");
4520 CmdArgs.push_back("hidden");
4521 CmdArgs.push_back("-ftype-visibility");
4522 CmdArgs.push_back("default");
4523 }
4524 }
4525
4526 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004527 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004528
4529 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4530
David L. Jonesf561aba2017-03-08 01:02:16 +00004531 // Forward -f (flag) options which we can pass directly.
4532 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4533 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004534 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004535 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004536 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4537 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004538 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004539
David L. Jonesf561aba2017-03-08 01:02:16 +00004540 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004541 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004542 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004543
David L. Jonesf561aba2017-03-08 01:02:16 +00004544 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4545 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4546
4547 // Forward flags for OpenMP. We don't do this if the current action is an
4548 // device offloading action other than OpenMP.
4549 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4550 options::OPT_fno_openmp, false) &&
4551 (JA.isDeviceOffloading(Action::OFK_None) ||
4552 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004553 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004554 case Driver::OMPRT_OMP:
4555 case Driver::OMPRT_IOMP5:
4556 // Clang can generate useful OpenMP code for these two runtime libraries.
4557 CmdArgs.push_back("-fopenmp");
4558
4559 // If no option regarding the use of TLS in OpenMP codegeneration is
4560 // given, decide a default based on the target. Otherwise rely on the
4561 // options and pass the right information to the frontend.
4562 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4563 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4564 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004565 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4566 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004567 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004568 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4569 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004570 Args.AddAllArgs(CmdArgs,
4571 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004572 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4573 options::OPT_fno_openmp_optimistic_collapse,
4574 /*Default=*/false))
4575 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004576
4577 // When in OpenMP offloading mode with NVPTX target, forward
4578 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004579 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4580 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4581 CmdArgs.push_back("-fopenmp-cuda-mode");
4582
4583 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4584 // is required.
4585 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4586 options::OPT_fno_openmp_cuda_force_full_runtime,
4587 /*Default=*/false))
4588 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004589 break;
4590 default:
4591 // By default, if Clang doesn't know how to generate useful OpenMP code
4592 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4593 // down to the actual compilation.
4594 // FIXME: It would be better to have a mode which *only* omits IR
4595 // generation based on the OpenMP support so that we get consistent
4596 // semantic analysis, etc.
4597 break;
4598 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004599 } else {
4600 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4601 options::OPT_fno_openmp_simd);
4602 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004603 }
4604
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004605 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4606 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004607
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004608 const XRayArgs &XRay = TC.getXRayArgs();
4609 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004610
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004611 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004612 Args.AddLastArg(CmdArgs, options::OPT_pg);
4613
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004614 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004615 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4616
4617 // -flax-vector-conversions is default.
4618 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4619 options::OPT_fno_lax_vector_conversions))
4620 CmdArgs.push_back("-fno-lax-vector-conversions");
4621
4622 if (Args.getLastArg(options::OPT_fapple_kext) ||
4623 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4624 CmdArgs.push_back("-fapple-kext");
4625
4626 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4627 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4628 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4629 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004630 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00004631 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004632 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004633 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004634
4635 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4636 CmdArgs.push_back("-ftrapv-handler");
4637 CmdArgs.push_back(A->getValue());
4638 }
4639
4640 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4641
4642 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4643 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4644 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4645 if (A->getOption().matches(options::OPT_fwrapv))
4646 CmdArgs.push_back("-fwrapv");
4647 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4648 options::OPT_fno_strict_overflow)) {
4649 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4650 CmdArgs.push_back("-fwrapv");
4651 }
4652
4653 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4654 options::OPT_fno_reroll_loops))
4655 if (A->getOption().matches(options::OPT_freroll_loops))
4656 CmdArgs.push_back("-freroll-loops");
4657
4658 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4659 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4660 options::OPT_fno_unroll_loops);
4661
4662 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4663
Zola Bridgesc8666792018-11-26 18:13:31 +00004664 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4665 false))
4666 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004667
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004668 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004669 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004670
4671 // Translate -mstackrealign
4672 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4673 false))
4674 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4675
4676 if (Args.hasArg(options::OPT_mstack_alignment)) {
4677 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4678 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4679 }
4680
4681 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4682 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4683
4684 if (!Size.empty())
4685 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4686 else
4687 CmdArgs.push_back("-mstack-probe-size=0");
4688 }
4689
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004690 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4691 options::OPT_mno_stack_arg_probe, true))
4692 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4693
David L. Jonesf561aba2017-03-08 01:02:16 +00004694 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4695 options::OPT_mno_restrict_it)) {
4696 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004697 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004698 CmdArgs.push_back("-arm-restrict-it");
4699 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004700 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004701 CmdArgs.push_back("-arm-no-restrict-it");
4702 }
4703 } else if (Triple.isOSWindows() &&
4704 (Triple.getArch() == llvm::Triple::arm ||
4705 Triple.getArch() == llvm::Triple::thumb)) {
4706 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004707 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004708 CmdArgs.push_back("-arm-restrict-it");
4709 }
4710
4711 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004712 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004713
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004714 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4715 CmdArgs.push_back(
4716 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4717 }
4718
David L. Jonesf561aba2017-03-08 01:02:16 +00004719 // Forward -f options with positive and negative forms; we translate
4720 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004721 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004722 auto *PGOArg = Args.getLastArg(
4723 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4724 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4725 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4726 if (PGOArg)
4727 D.Diag(diag::err_drv_argument_not_allowed_with)
4728 << "SampleUse with PGO options";
4729
David L. Jonesf561aba2017-03-08 01:02:16 +00004730 StringRef fname = A->getValue();
4731 if (!llvm::sys::fs::exists(fname))
4732 D.Diag(diag::err_drv_no_such_file) << fname;
4733 else
4734 A->render(Args, CmdArgs);
4735 }
Richard Smith8654ae52018-10-10 23:13:35 +00004736 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004737
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004738 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004739
4740 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4741 options::OPT_fno_assume_sane_operator_new))
4742 CmdArgs.push_back("-fno-assume-sane-operator-new");
4743
4744 // -fblocks=0 is default.
4745 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004746 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004747 (Args.hasArg(options::OPT_fgnu_runtime) &&
4748 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4749 !Args.hasArg(options::OPT_fno_blocks))) {
4750 CmdArgs.push_back("-fblocks");
4751
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004752 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004753 CmdArgs.push_back("-fblocks-runtime-optional");
4754 }
4755
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004756 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004757 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004758 CmdArgs.push_back("-fencode-extended-block-signature");
4759
David L. Jonesf561aba2017-03-08 01:02:16 +00004760 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4761 false) &&
4762 types::isCXX(InputType)) {
4763 CmdArgs.push_back("-fcoroutines-ts");
4764 }
4765
Aaron Ballman61736552017-10-21 20:28:58 +00004766 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4767 options::OPT_fno_double_square_bracket_attributes);
4768
David L. Jonesf561aba2017-03-08 01:02:16 +00004769 // -faccess-control is default.
4770 if (Args.hasFlag(options::OPT_fno_access_control,
4771 options::OPT_faccess_control, false))
4772 CmdArgs.push_back("-fno-access-control");
4773
4774 // -felide-constructors is the default.
4775 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4776 options::OPT_felide_constructors, false))
4777 CmdArgs.push_back("-fno-elide-constructors");
4778
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004779 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004780
4781 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004782 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004783 CmdArgs.push_back("-fno-rtti");
4784
4785 // -fshort-enums=0 is default for all architectures except Hexagon.
4786 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004787 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004788 CmdArgs.push_back("-fshort-enums");
4789
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004790 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004791
4792 // -fuse-cxa-atexit is default.
4793 if (!Args.hasFlag(
4794 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004795 !RawTriple.isOSWindows() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004796 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004797 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4798 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004799 KernelOrKext)
4800 CmdArgs.push_back("-fno-use-cxa-atexit");
4801
Akira Hatanaka617e2612018-04-17 18:41:52 +00004802 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4803 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004804 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004805 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4806
David L. Jonesf561aba2017-03-08 01:02:16 +00004807 // -fms-extensions=0 is default.
4808 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4809 IsWindowsMSVC))
4810 CmdArgs.push_back("-fms-extensions");
4811
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004812 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004813 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004814 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004815 CmdArgs.push_back("-fuse-line-directives");
4816
4817 // -fms-compatibility=0 is default.
4818 if (Args.hasFlag(options::OPT_fms_compatibility,
4819 options::OPT_fno_ms_compatibility,
4820 (IsWindowsMSVC &&
4821 Args.hasFlag(options::OPT_fms_extensions,
4822 options::OPT_fno_ms_extensions, true))))
4823 CmdArgs.push_back("-fms-compatibility");
4824
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004825 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004826 if (!MSVT.empty())
4827 CmdArgs.push_back(
4828 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4829
4830 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4831 if (ImplyVCPPCXXVer) {
4832 StringRef LanguageStandard;
4833 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004834 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004835 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4836 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004837 .Case("c++17", "-std=c++17")
4838 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004839 .Default("");
4840 if (LanguageStandard.empty())
4841 D.Diag(clang::diag::warn_drv_unused_argument)
4842 << StdArg->getAsString(Args);
4843 }
4844
4845 if (LanguageStandard.empty()) {
4846 if (IsMSVC2015Compatible)
4847 LanguageStandard = "-std=c++14";
4848 else
4849 LanguageStandard = "-std=c++11";
4850 }
4851
4852 CmdArgs.push_back(LanguageStandard.data());
4853 }
4854
4855 // -fno-borland-extensions is default.
4856 if (Args.hasFlag(options::OPT_fborland_extensions,
4857 options::OPT_fno_borland_extensions, false))
4858 CmdArgs.push_back("-fborland-extensions");
4859
4860 // -fno-declspec is default, except for PS4.
4861 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004862 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004863 CmdArgs.push_back("-fdeclspec");
4864 else if (Args.hasArg(options::OPT_fno_declspec))
4865 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4866
4867 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4868 // than 19.
4869 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4870 options::OPT_fno_threadsafe_statics,
4871 !IsWindowsMSVC || IsMSVC2015Compatible))
4872 CmdArgs.push_back("-fno-threadsafe-statics");
4873
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004874 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004875 // Many old Windows SDK versions require this to parse.
4876 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4877 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004878 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4879 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4880 CmdArgs.push_back("-fdelayed-template-parsing");
4881
4882 // -fgnu-keywords default varies depending on language; only pass if
4883 // specified.
Nico Weber908b6972019-06-26 17:51:47 +00004884 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4885 options::OPT_fno_gnu_keywords);
David L. Jonesf561aba2017-03-08 01:02:16 +00004886
4887 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4888 false))
4889 CmdArgs.push_back("-fgnu89-inline");
4890
4891 if (Args.hasArg(options::OPT_fno_inline))
4892 CmdArgs.push_back("-fno-inline");
4893
Nico Weber908b6972019-06-26 17:51:47 +00004894 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4895 options::OPT_finline_hint_functions,
4896 options::OPT_fno_inline_functions);
David L. Jonesf561aba2017-03-08 01:02:16 +00004897
Richard Smithb1b580e2019-04-14 11:11:37 +00004898 // FIXME: Find a better way to determine whether the language has modules
4899 // support by default, or just assume that all languages do.
4900 bool HaveModules =
4901 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4902 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4903
David L. Jonesf561aba2017-03-08 01:02:16 +00004904 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4905 options::OPT_fno_experimental_new_pass_manager);
4906
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004907 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004908 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4909 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004910
4911 if (Args.hasFlag(options::OPT_fapplication_extension,
4912 options::OPT_fno_application_extension, false))
4913 CmdArgs.push_back("-fapplication-extension");
4914
4915 // Handle GCC-style exception args.
4916 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004917 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004918
Martell Malonec950c652017-11-29 07:25:12 +00004919 // Handle exception personalities
4920 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4921 options::OPT_fseh_exceptions,
4922 options::OPT_fdwarf_exceptions);
4923 if (A) {
4924 const Option &Opt = A->getOption();
4925 if (Opt.matches(options::OPT_fsjlj_exceptions))
4926 CmdArgs.push_back("-fsjlj-exceptions");
4927 if (Opt.matches(options::OPT_fseh_exceptions))
4928 CmdArgs.push_back("-fseh-exceptions");
4929 if (Opt.matches(options::OPT_fdwarf_exceptions))
4930 CmdArgs.push_back("-fdwarf-exceptions");
4931 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004932 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004933 default:
4934 break;
4935 case llvm::ExceptionHandling::DwarfCFI:
4936 CmdArgs.push_back("-fdwarf-exceptions");
4937 break;
4938 case llvm::ExceptionHandling::SjLj:
4939 CmdArgs.push_back("-fsjlj-exceptions");
4940 break;
4941 case llvm::ExceptionHandling::WinEH:
4942 CmdArgs.push_back("-fseh-exceptions");
4943 break;
Martell Malonec950c652017-11-29 07:25:12 +00004944 }
4945 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004946
4947 // C++ "sane" operator new.
4948 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4949 options::OPT_fno_assume_sane_operator_new))
4950 CmdArgs.push_back("-fno-assume-sane-operator-new");
4951
4952 // -frelaxed-template-template-args is off by default, as it is a severe
4953 // breaking change until a corresponding change to template partial ordering
4954 // is provided.
4955 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4956 options::OPT_fno_relaxed_template_template_args, false))
4957 CmdArgs.push_back("-frelaxed-template-template-args");
4958
4959 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4960 // most platforms.
4961 if (Args.hasFlag(options::OPT_fsized_deallocation,
4962 options::OPT_fno_sized_deallocation, false))
4963 CmdArgs.push_back("-fsized-deallocation");
4964
4965 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4966 // by default.
4967 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4968 options::OPT_fno_aligned_allocation,
4969 options::OPT_faligned_new_EQ)) {
4970 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4971 CmdArgs.push_back("-fno-aligned-allocation");
4972 else
4973 CmdArgs.push_back("-faligned-allocation");
4974 }
4975
4976 // The default new alignment can be specified using a dedicated option or via
4977 // a GCC-compatible option that also turns on aligned allocation.
4978 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4979 options::OPT_faligned_new_EQ))
4980 CmdArgs.push_back(
4981 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4982
4983 // -fconstant-cfstrings is default, and may be subject to argument translation
4984 // on Darwin.
4985 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4986 options::OPT_fno_constant_cfstrings) ||
4987 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4988 options::OPT_mno_constant_cfstrings))
4989 CmdArgs.push_back("-fno-constant-cfstrings");
4990
David L. Jonesf561aba2017-03-08 01:02:16 +00004991 // -fno-pascal-strings is default, only pass non-default.
4992 if (Args.hasFlag(options::OPT_fpascal_strings,
4993 options::OPT_fno_pascal_strings, false))
4994 CmdArgs.push_back("-fpascal-strings");
4995
4996 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4997 // -fno-pack-struct doesn't apply to -fpack-struct=.
4998 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4999 std::string PackStructStr = "-fpack-struct=";
5000 PackStructStr += A->getValue();
5001 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5002 } else if (Args.hasFlag(options::OPT_fpack_struct,
5003 options::OPT_fno_pack_struct, false)) {
5004 CmdArgs.push_back("-fpack-struct=1");
5005 }
5006
5007 // Handle -fmax-type-align=N and -fno-type-align
5008 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5009 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5010 if (!SkipMaxTypeAlign) {
5011 std::string MaxTypeAlignStr = "-fmax-type-align=";
5012 MaxTypeAlignStr += A->getValue();
5013 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5014 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005015 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005016 if (!SkipMaxTypeAlign) {
5017 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5018 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5019 }
5020 }
5021
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00005022 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
5023 CmdArgs.push_back("-Qn");
5024
David L. Jonesf561aba2017-03-08 01:02:16 +00005025 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005026 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00005027 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5028 !NoCommonDefault))
5029 CmdArgs.push_back("-fno-common");
5030
5031 // -fsigned-bitfields is default, and clang doesn't yet support
5032 // -funsigned-bitfields.
5033 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5034 options::OPT_funsigned_bitfields))
5035 D.Diag(diag::warn_drv_clang_unsupported)
5036 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5037
5038 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5039 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5040 D.Diag(diag::err_drv_clang_unsupported)
5041 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5042
5043 // -finput_charset=UTF-8 is default. Reject others
5044 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5045 StringRef value = inputCharset->getValue();
5046 if (!value.equals_lower("utf-8"))
5047 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5048 << value;
5049 }
5050
5051 // -fexec_charset=UTF-8 is default. Reject others
5052 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5053 StringRef value = execCharset->getValue();
5054 if (!value.equals_lower("utf-8"))
5055 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5056 << value;
5057 }
5058
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005059 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005060
5061 // -fno-asm-blocks is default.
5062 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5063 false))
5064 CmdArgs.push_back("-fasm-blocks");
5065
5066 // -fgnu-inline-asm is default.
5067 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5068 options::OPT_fno_gnu_inline_asm, true))
5069 CmdArgs.push_back("-fno-gnu-inline-asm");
5070
5071 // Enable vectorization per default according to the optimization level
5072 // selected. For optimization levels that want vectorization we use the alias
5073 // option to simplify the hasFlag logic.
5074 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5075 OptSpecifier VectorizeAliasOption =
5076 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5077 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5078 options::OPT_fno_vectorize, EnableVec))
5079 CmdArgs.push_back("-vectorize-loops");
5080
5081 // -fslp-vectorize is enabled based on the optimization level selected.
5082 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5083 OptSpecifier SLPVectAliasOption =
5084 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5085 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5086 options::OPT_fno_slp_vectorize, EnableSLPVec))
5087 CmdArgs.push_back("-vectorize-slp");
5088
Craig Topper9a724aa2017-12-11 21:09:19 +00005089 ParseMPreferVectorWidth(D, Args, CmdArgs);
5090
Nico Weber908b6972019-06-26 17:51:47 +00005091 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5092 Args.AddLastArg(CmdArgs,
5093 options::OPT_fsanitize_undefined_strip_path_components_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005094
5095 // -fdollars-in-identifiers default varies depending on platform and
5096 // language; only pass if specified.
5097 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5098 options::OPT_fno_dollars_in_identifiers)) {
5099 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5100 CmdArgs.push_back("-fdollars-in-identifiers");
5101 else
5102 CmdArgs.push_back("-fno-dollars-in-identifiers");
5103 }
5104
5105 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5106 // practical purposes.
5107 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5108 options::OPT_fno_unit_at_a_time)) {
5109 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5110 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5111 }
5112
5113 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5114 options::OPT_fno_apple_pragma_pack, false))
5115 CmdArgs.push_back("-fapple-pragma-pack");
5116
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005117 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005118 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005119 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005120 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005121 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5122 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005123 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005124 options::OPT_fno_save_optimization_record, false)) {
5125 CmdArgs.push_back("-opt-record-file");
5126
5127 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5128 if (A) {
5129 CmdArgs.push_back(A->getValue());
5130 } else {
5131 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005132
5133 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5134 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5135 F = FinalOutput->getValue();
5136 }
5137
5138 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005139 // Use the input filename.
5140 F = llvm::sys::path::stem(Input.getBaseInput());
5141
5142 // If we're compiling for an offload architecture (i.e. a CUDA device),
5143 // we need to make the file name for the device compilation different
5144 // from the host compilation.
5145 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5146 !JA.isDeviceOffloading(Action::OFK_Host)) {
5147 llvm::sys::path::replace_extension(F, "");
5148 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5149 Triple.normalize());
5150 F += "-";
5151 F += JA.getOffloadingArch();
5152 }
5153 }
5154
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005155 std::string Extension = "opt.";
5156 if (const Arg *A =
5157 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5158 Extension += A->getValue();
5159 else
5160 Extension += "yaml";
5161
5162 llvm::sys::path::replace_extension(F, Extension);
David L. Jonesf561aba2017-03-08 01:02:16 +00005163 CmdArgs.push_back(Args.MakeArgString(F));
5164 }
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005165
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005166 if (const Arg *A =
5167 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5168 CmdArgs.push_back("-opt-record-passes");
5169 CmdArgs.push_back(A->getValue());
5170 }
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005171
5172 if (const Arg *A =
5173 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5174 CmdArgs.push_back("-opt-record-format");
5175 CmdArgs.push_back(A->getValue());
5176 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005177 }
5178
Richard Smith86a3ef52017-06-09 21:24:02 +00005179 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5180 options::OPT_fno_rewrite_imports, false);
5181 if (RewriteImports)
5182 CmdArgs.push_back("-frewrite-imports");
5183
David L. Jonesf561aba2017-03-08 01:02:16 +00005184 // Enable rewrite includes if the user's asked for it or if we're generating
5185 // diagnostics.
5186 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5187 // nice to enable this when doing a crashdump for modules as well.
5188 if (Args.hasFlag(options::OPT_frewrite_includes,
5189 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005190 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005191 CmdArgs.push_back("-frewrite-includes");
5192
5193 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5194 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5195 options::OPT_traditional_cpp)) {
5196 if (isa<PreprocessJobAction>(JA))
5197 CmdArgs.push_back("-traditional-cpp");
5198 else
5199 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5200 }
5201
5202 Args.AddLastArg(CmdArgs, options::OPT_dM);
5203 Args.AddLastArg(CmdArgs, options::OPT_dD);
5204
5205 // Handle serialized diagnostics.
5206 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5207 CmdArgs.push_back("-serialize-diagnostic-file");
5208 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5209 }
5210
5211 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5212 CmdArgs.push_back("-fretain-comments-from-system-headers");
5213
5214 // Forward -fcomment-block-commands to -cc1.
5215 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5216 // Forward -fparse-all-comments to -cc1.
5217 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5218
5219 // Turn -fplugin=name.so into -load name.so
5220 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5221 CmdArgs.push_back("-load");
5222 CmdArgs.push_back(A->getValue());
5223 A->claim();
5224 }
5225
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005226 // Forward -fpass-plugin=name.so to -cc1.
5227 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5228 CmdArgs.push_back(
5229 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5230 A->claim();
5231 }
5232
David L. Jonesf561aba2017-03-08 01:02:16 +00005233 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005234 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5235 if (!StatsFile.empty())
5236 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005237
5238 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5239 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005240 // -finclude-default-header flag is for preprocessor,
5241 // do not pass it to other cc1 commands when save-temps is enabled
5242 if (C.getDriver().isSaveTempsEnabled() &&
5243 !isa<PreprocessJobAction>(JA)) {
5244 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5245 Arg->claim();
5246 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5247 CmdArgs.push_back(Arg->getValue());
5248 }
5249 }
5250 else {
5251 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5252 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005253 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5254 A->claim();
5255
5256 // We translate this by hand to the -cc1 argument, since nightly test uses
5257 // it and developers have been trained to spell it with -mllvm. Both
5258 // spellings are now deprecated and should be removed.
5259 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5260 CmdArgs.push_back("-disable-llvm-optzns");
5261 } else {
5262 A->render(Args, CmdArgs);
5263 }
5264 }
5265
5266 // With -save-temps, we want to save the unoptimized bitcode output from the
5267 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5268 // by the frontend.
5269 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5270 // has slightly different breakdown between stages.
5271 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5272 // pristine IR generated by the frontend. Ideally, a new compile action should
5273 // be added so both IR can be captured.
5274 if (C.getDriver().isSaveTempsEnabled() &&
5275 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5276 isa<CompileJobAction>(JA))
5277 CmdArgs.push_back("-disable-llvm-passes");
5278
David L. Jonesf561aba2017-03-08 01:02:16 +00005279 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5280
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005281 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005282
Scott Linderde6beb02018-12-14 15:38:15 +00005283 // Optionally embed the -cc1 level arguments into the debug info or a
5284 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005285 // Also record command line arguments into the debug info if
5286 // -grecord-gcc-switches options is set on.
5287 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005288 auto GRecordSwitches =
5289 Args.hasFlag(options::OPT_grecord_command_line,
5290 options::OPT_gno_record_command_line, false);
5291 auto FRecordSwitches =
5292 Args.hasFlag(options::OPT_frecord_command_line,
5293 options::OPT_fno_record_command_line, false);
5294 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5295 D.Diag(diag::err_drv_unsupported_opt_for_target)
5296 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5297 << TripleStr;
5298 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005299 ArgStringList OriginalArgs;
5300 for (const auto &Arg : Args)
5301 Arg->render(Args, OriginalArgs);
5302
5303 SmallString<256> Flags;
5304 Flags += Exec;
5305 for (const char *OriginalArg : OriginalArgs) {
5306 SmallString<128> EscapedArg;
5307 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5308 Flags += " ";
5309 Flags += EscapedArg;
5310 }
Scott Linderde6beb02018-12-14 15:38:15 +00005311 auto FlagsArgString = Args.MakeArgString(Flags);
5312 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5313 CmdArgs.push_back("-dwarf-debug-flags");
5314 CmdArgs.push_back(FlagsArgString);
5315 }
5316 if (FRecordSwitches) {
5317 CmdArgs.push_back("-record-command-line");
5318 CmdArgs.push_back(FlagsArgString);
5319 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005320 }
5321
Yaxun Liu97670892018-10-02 17:48:54 +00005322 // Host-side cuda compilation receives all device-side outputs in a single
5323 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5324 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005325 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005326 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005327 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5328 CmdArgs.push_back("-fgpu-rdc");
5329 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005330
Yaxun Liu97670892018-10-02 17:48:54 +00005331 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005332 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5333 options::OPT_fno_cuda_short_ptr, false))
5334 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005335 }
5336
David L. Jonesf561aba2017-03-08 01:02:16 +00005337 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5338 // to specify the result of the compile phase on the host, so the meaningful
5339 // device declarations can be identified. Also, -fopenmp-is-device is passed
5340 // along to tell the frontend that it is generating code for a device, so that
5341 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005342 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005343 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005344 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005345 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005346 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005347 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005348 }
5349
5350 // For all the host OpenMP offloading compile jobs we need to pass the targets
5351 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005352 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005353 SmallString<128> TargetInfo("-fopenmp-targets=");
5354
5355 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5356 assert(Tgts && Tgts->getNumValues() &&
5357 "OpenMP offloading has to have targets specified.");
5358 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5359 if (i)
5360 TargetInfo += ',';
5361 // We need to get the string from the triple because it may be not exactly
5362 // the same as the one we get directly from the arguments.
5363 llvm::Triple T(Tgts->getValue(i));
5364 TargetInfo += T.getTriple();
5365 }
5366 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5367 }
5368
5369 bool WholeProgramVTables =
5370 Args.hasFlag(options::OPT_fwhole_program_vtables,
5371 options::OPT_fno_whole_program_vtables, false);
5372 if (WholeProgramVTables) {
5373 if (!D.isUsingLTO())
5374 D.Diag(diag::err_drv_argument_only_allowed_with)
5375 << "-fwhole-program-vtables"
5376 << "-flto";
5377 CmdArgs.push_back("-fwhole-program-vtables");
5378 }
5379
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005380 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5381 bool SplitLTOUnit =
5382 Args.hasFlag(options::OPT_fsplit_lto_unit,
5383 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5384 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5385 D.Diag(diag::err_drv_argument_not_allowed_with)
5386 << "-fno-split-lto-unit"
5387 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5388 if (SplitLTOUnit)
5389 CmdArgs.push_back("-fsplit-lto-unit");
5390
Amara Emerson4ee9f822018-01-26 00:27:22 +00005391 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5392 options::OPT_fno_experimental_isel)) {
5393 CmdArgs.push_back("-mllvm");
5394 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5395 CmdArgs.push_back("-global-isel=1");
5396
5397 // GISel is on by default on AArch64 -O0, so don't bother adding
5398 // the fallback remarks for it. Other combinations will add a warning of
5399 // some kind.
5400 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5401 bool IsOptLevelSupported = false;
5402
5403 Arg *A = Args.getLastArg(options::OPT_O_Group);
5404 if (Triple.getArch() == llvm::Triple::aarch64) {
5405 if (!A || A->getOption().matches(options::OPT_O0))
5406 IsOptLevelSupported = true;
5407 }
5408 if (!IsArchSupported || !IsOptLevelSupported) {
5409 CmdArgs.push_back("-mllvm");
5410 CmdArgs.push_back("-global-isel-abort=2");
5411
5412 if (!IsArchSupported)
5413 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5414 else
5415 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5416 }
5417 } else {
5418 CmdArgs.push_back("-global-isel=0");
5419 }
5420 }
5421
Manman Ren394d4cc2019-03-04 20:30:30 +00005422 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5423 CmdArgs.push_back("-forder-file-instrumentation");
5424 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5425 // on, we need to pass these flags as linker flags and that will be handled
5426 // outside of the compiler.
5427 if (!D.isUsingLTO()) {
5428 CmdArgs.push_back("-mllvm");
5429 CmdArgs.push_back("-enable-order-file-instrumentation");
5430 }
5431 }
5432
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005433 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5434 options::OPT_fno_force_enable_int128)) {
5435 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5436 CmdArgs.push_back("-fforce-enable-int128");
5437 }
5438
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005439 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5440 options::OPT_fno_complete_member_pointers, false))
5441 CmdArgs.push_back("-fcomplete-member-pointers");
5442
Erik Pilkington5a559e62018-08-21 17:24:06 +00005443 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5444 options::OPT_fno_cxx_static_destructors, true))
5445 CmdArgs.push_back("-fno-c++-static-destructors");
5446
Jessica Paquette36a25672018-06-29 18:06:10 +00005447 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5448 options::OPT_mno_outline)) {
5449 if (A->getOption().matches(options::OPT_moutline)) {
5450 // We only support -moutline in AArch64 right now. If we're not compiling
5451 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5452 // proper mllvm flags.
5453 if (Triple.getArch() != llvm::Triple::aarch64) {
5454 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5455 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005456 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005457 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005458 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005459 } else {
5460 // Disable all outlining behaviour.
5461 CmdArgs.push_back("-mllvm");
5462 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005463 }
5464 }
5465
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005466 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005467 (TC.getTriple().isOSBinFormatELF() ||
5468 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005469 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005470 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005471 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005472 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005473 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005474 CmdArgs.push_back("-faddrsig");
5475
Peter Collingbournee08e68d2019-06-07 19:10:08 +00005476 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5477 std::string Str = A->getAsString(Args);
5478 if (!TC.getTriple().isOSBinFormatELF())
5479 D.Diag(diag::err_drv_unsupported_opt_for_target)
5480 << Str << TC.getTripleString();
5481 CmdArgs.push_back(Args.MakeArgString(Str));
5482 }
5483
Reid Kleckner549ed542019-05-23 18:35:43 +00005484 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5485 // the -cc1 command easier to edit when reproducing compiler crashes.
5486 if (Output.getType() == types::TY_Dependencies) {
5487 // Handled with other dependency code.
5488 } else if (Output.isFilename()) {
5489 CmdArgs.push_back("-o");
5490 CmdArgs.push_back(Output.getFilename());
5491 } else {
5492 assert(Output.isNothing() && "Invalid output.");
5493 }
5494
5495 addDashXForInput(Args, Input, CmdArgs);
5496
5497 ArrayRef<InputInfo> FrontendInputs = Input;
5498 if (IsHeaderModulePrecompile)
5499 FrontendInputs = ModuleHeaderInputs;
5500 else if (Input.isNothing())
5501 FrontendInputs = {};
5502
5503 for (const InputInfo &Input : FrontendInputs) {
5504 if (Input.isFilename())
5505 CmdArgs.push_back(Input.getFilename());
5506 else
5507 Input.getInputArg().renderAsInput(Args, CmdArgs);
5508 }
5509
David L. Jonesf561aba2017-03-08 01:02:16 +00005510 // Finally add the compile command to the compilation.
5511 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5512 Output.getType() == types::TY_Object &&
5513 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5514 auto CLCommand =
5515 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5516 C.addCommand(llvm::make_unique<FallbackCommand>(
5517 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5518 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5519 isa<PrecompileJobAction>(JA)) {
5520 // In /fallback builds, run the main compilation even if the pch generation
5521 // fails, so that the main compilation's fallback to cl.exe runs.
5522 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5523 CmdArgs, Inputs));
5524 } else {
5525 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5526 }
5527
Hans Wennborg2fe01042018-10-13 19:13:14 +00005528 // Make the compile command echo its inputs for /showFilenames.
5529 if (Output.getType() == types::TY_Object &&
5530 Args.hasFlag(options::OPT__SLASH_showFilenames,
5531 options::OPT__SLASH_showFilenames_, false)) {
5532 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5533 }
5534
David L. Jonesf561aba2017-03-08 01:02:16 +00005535 if (Arg *A = Args.getLastArg(options::OPT_pg))
Yuanfang Chenff22ec32019-07-20 22:50:50 +00005536 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
David L. Jonesf561aba2017-03-08 01:02:16 +00005537 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5538 << A->getAsString(Args);
5539
5540 // Claim some arguments which clang supports automatically.
5541
5542 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005543 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005544 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5545
5546 // Claim some arguments which clang doesn't support, but we don't
5547 // care to warn the user about.
5548 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5549 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5550
5551 // Disable warnings for clang -E -emit-llvm foo.c
5552 Args.ClaimAllArgs(options::OPT_emit_llvm);
5553}
5554
5555Clang::Clang(const ToolChain &TC)
5556 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5557 // as it is for other tools. Some operations on a Tool actually test
5558 // whether that tool is Clang based on the Tool's Name as a string.
5559 : Tool("clang", "clang frontend", TC, RF_Full) {}
5560
5561Clang::~Clang() {}
5562
5563/// Add options related to the Objective-C runtime/ABI.
5564///
5565/// Returns true if the runtime is non-fragile.
5566ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5567 ArgStringList &cmdArgs,
5568 RewriteKind rewriteKind) const {
5569 // Look for the controlling runtime option.
5570 Arg *runtimeArg =
5571 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5572 options::OPT_fobjc_runtime_EQ);
5573
5574 // Just forward -fobjc-runtime= to the frontend. This supercedes
5575 // options about fragility.
5576 if (runtimeArg &&
5577 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5578 ObjCRuntime runtime;
5579 StringRef value = runtimeArg->getValue();
5580 if (runtime.tryParse(value)) {
5581 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5582 << value;
5583 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005584 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5585 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005586 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5587 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005588 getToolChain().getDriver().Diag(
5589 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5590 << runtime.getVersion().getMajor();
5591 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005592
5593 runtimeArg->render(args, cmdArgs);
5594 return runtime;
5595 }
5596
5597 // Otherwise, we'll need the ABI "version". Version numbers are
5598 // slightly confusing for historical reasons:
5599 // 1 - Traditional "fragile" ABI
5600 // 2 - Non-fragile ABI, version 1
5601 // 3 - Non-fragile ABI, version 2
5602 unsigned objcABIVersion = 1;
5603 // If -fobjc-abi-version= is present, use that to set the version.
5604 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5605 StringRef value = abiArg->getValue();
5606 if (value == "1")
5607 objcABIVersion = 1;
5608 else if (value == "2")
5609 objcABIVersion = 2;
5610 else if (value == "3")
5611 objcABIVersion = 3;
5612 else
5613 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5614 } else {
5615 // Otherwise, determine if we are using the non-fragile ABI.
5616 bool nonFragileABIIsDefault =
5617 (rewriteKind == RK_NonFragile ||
5618 (rewriteKind == RK_None &&
5619 getToolChain().IsObjCNonFragileABIDefault()));
5620 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5621 options::OPT_fno_objc_nonfragile_abi,
5622 nonFragileABIIsDefault)) {
5623// Determine the non-fragile ABI version to use.
5624#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5625 unsigned nonFragileABIVersion = 1;
5626#else
5627 unsigned nonFragileABIVersion = 2;
5628#endif
5629
5630 if (Arg *abiArg =
5631 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5632 StringRef value = abiArg->getValue();
5633 if (value == "1")
5634 nonFragileABIVersion = 1;
5635 else if (value == "2")
5636 nonFragileABIVersion = 2;
5637 else
5638 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5639 << value;
5640 }
5641
5642 objcABIVersion = 1 + nonFragileABIVersion;
5643 } else {
5644 objcABIVersion = 1;
5645 }
5646 }
5647
5648 // We don't actually care about the ABI version other than whether
5649 // it's non-fragile.
5650 bool isNonFragile = objcABIVersion != 1;
5651
5652 // If we have no runtime argument, ask the toolchain for its default runtime.
5653 // However, the rewriter only really supports the Mac runtime, so assume that.
5654 ObjCRuntime runtime;
5655 if (!runtimeArg) {
5656 switch (rewriteKind) {
5657 case RK_None:
5658 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5659 break;
5660 case RK_Fragile:
5661 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5662 break;
5663 case RK_NonFragile:
5664 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5665 break;
5666 }
5667
5668 // -fnext-runtime
5669 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5670 // On Darwin, make this use the default behavior for the toolchain.
5671 if (getToolChain().getTriple().isOSDarwin()) {
5672 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5673
5674 // Otherwise, build for a generic macosx port.
5675 } else {
5676 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5677 }
5678
5679 // -fgnu-runtime
5680 } else {
5681 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5682 // Legacy behaviour is to target the gnustep runtime if we are in
5683 // non-fragile mode or the GCC runtime in fragile mode.
5684 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005685 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005686 else
5687 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5688 }
5689
5690 cmdArgs.push_back(
5691 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5692 return runtime;
5693}
5694
5695static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5696 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5697 I += HaveDash;
5698 return !HaveDash;
5699}
5700
5701namespace {
5702struct EHFlags {
5703 bool Synch = false;
5704 bool Asynch = false;
5705 bool NoUnwindC = false;
5706};
5707} // end anonymous namespace
5708
5709/// /EH controls whether to run destructor cleanups when exceptions are
5710/// thrown. There are three modifiers:
5711/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5712/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5713/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5714/// - c: Assume that extern "C" functions are implicitly nounwind.
5715/// The default is /EHs-c-, meaning cleanups are disabled.
5716static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5717 EHFlags EH;
5718
5719 std::vector<std::string> EHArgs =
5720 Args.getAllArgValues(options::OPT__SLASH_EH);
5721 for (auto EHVal : EHArgs) {
5722 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5723 switch (EHVal[I]) {
5724 case 'a':
5725 EH.Asynch = maybeConsumeDash(EHVal, I);
5726 if (EH.Asynch)
5727 EH.Synch = false;
5728 continue;
5729 case 'c':
5730 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5731 continue;
5732 case 's':
5733 EH.Synch = maybeConsumeDash(EHVal, I);
5734 if (EH.Synch)
5735 EH.Asynch = false;
5736 continue;
5737 default:
5738 break;
5739 }
5740 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5741 break;
5742 }
5743 }
5744 // The /GX, /GX- flags are only processed if there are not /EH flags.
5745 // The default is that /GX is not specified.
5746 if (EHArgs.empty() &&
5747 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005748 /*Default=*/false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005749 EH.Synch = true;
5750 EH.NoUnwindC = true;
5751 }
5752
5753 return EH;
5754}
5755
5756void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5757 ArgStringList &CmdArgs,
5758 codegenoptions::DebugInfoKind *DebugInfoKind,
5759 bool *EmitCodeView) const {
5760 unsigned RTOptionID = options::OPT__SLASH_MT;
5761
5762 if (Args.hasArg(options::OPT__SLASH_LDd))
5763 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5764 // but defining _DEBUG is sticky.
5765 RTOptionID = options::OPT__SLASH_MTd;
5766
5767 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5768 RTOptionID = A->getOption().getID();
5769
5770 StringRef FlagForCRT;
5771 switch (RTOptionID) {
5772 case options::OPT__SLASH_MD:
5773 if (Args.hasArg(options::OPT__SLASH_LDd))
5774 CmdArgs.push_back("-D_DEBUG");
5775 CmdArgs.push_back("-D_MT");
5776 CmdArgs.push_back("-D_DLL");
5777 FlagForCRT = "--dependent-lib=msvcrt";
5778 break;
5779 case options::OPT__SLASH_MDd:
5780 CmdArgs.push_back("-D_DEBUG");
5781 CmdArgs.push_back("-D_MT");
5782 CmdArgs.push_back("-D_DLL");
5783 FlagForCRT = "--dependent-lib=msvcrtd";
5784 break;
5785 case options::OPT__SLASH_MT:
5786 if (Args.hasArg(options::OPT__SLASH_LDd))
5787 CmdArgs.push_back("-D_DEBUG");
5788 CmdArgs.push_back("-D_MT");
5789 CmdArgs.push_back("-flto-visibility-public-std");
5790 FlagForCRT = "--dependent-lib=libcmt";
5791 break;
5792 case options::OPT__SLASH_MTd:
5793 CmdArgs.push_back("-D_DEBUG");
5794 CmdArgs.push_back("-D_MT");
5795 CmdArgs.push_back("-flto-visibility-public-std");
5796 FlagForCRT = "--dependent-lib=libcmtd";
5797 break;
5798 default:
5799 llvm_unreachable("Unexpected option ID.");
5800 }
5801
5802 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5803 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5804 } else {
5805 CmdArgs.push_back(FlagForCRT.data());
5806
5807 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5808 // users want. The /Za flag to cl.exe turns this off, but it's not
5809 // implemented in clang.
5810 CmdArgs.push_back("--dependent-lib=oldnames");
5811 }
5812
Nico Weber908b6972019-06-26 17:51:47 +00005813 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
David L. Jonesf561aba2017-03-08 01:02:16 +00005814
5815 // This controls whether or not we emit RTTI data for polymorphic types.
5816 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005817 /*Default=*/false))
David L. Jonesf561aba2017-03-08 01:02:16 +00005818 CmdArgs.push_back("-fno-rtti-data");
5819
5820 // This controls whether or not we emit stack-protector instrumentation.
5821 // In MSVC, Buffer Security Check (/GS) is on by default.
5822 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005823 /*Default=*/true)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005824 CmdArgs.push_back("-stack-protector");
5825 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5826 }
5827
5828 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5829 if (Arg *DebugInfoArg =
5830 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5831 options::OPT_gline_tables_only)) {
5832 *EmitCodeView = true;
5833 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5834 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5835 else
5836 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005837 } else {
5838 *EmitCodeView = false;
5839 }
5840
5841 const Driver &D = getToolChain().getDriver();
5842 EHFlags EH = parseClangCLEHFlags(D, Args);
5843 if (EH.Synch || EH.Asynch) {
5844 if (types::isCXX(InputType))
5845 CmdArgs.push_back("-fcxx-exceptions");
5846 CmdArgs.push_back("-fexceptions");
5847 }
5848 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5849 CmdArgs.push_back("-fexternc-nounwind");
5850
5851 // /EP should expand to -E -P.
5852 if (Args.hasArg(options::OPT__SLASH_EP)) {
5853 CmdArgs.push_back("-E");
5854 CmdArgs.push_back("-P");
5855 }
5856
5857 unsigned VolatileOptionID;
5858 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5859 getToolChain().getArch() == llvm::Triple::x86)
5860 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5861 else
5862 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5863
5864 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5865 VolatileOptionID = A->getOption().getID();
5866
5867 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5868 CmdArgs.push_back("-fms-volatile");
5869
Takuto Ikuta302c6432018-11-03 06:45:00 +00005870 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5871 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005872 false)) {
5873 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5874 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5875 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005876 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005877 }
5878 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005879
David L. Jonesf561aba2017-03-08 01:02:16 +00005880 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5881 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5882 if (MostGeneralArg && BestCaseArg)
5883 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5884 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5885
5886 if (MostGeneralArg) {
5887 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5888 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5889 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5890
5891 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5892 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5893 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5894 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5895 << FirstConflict->getAsString(Args)
5896 << SecondConflict->getAsString(Args);
5897
5898 if (SingleArg)
5899 CmdArgs.push_back("-fms-memptr-rep=single");
5900 else if (MultipleArg)
5901 CmdArgs.push_back("-fms-memptr-rep=multiple");
5902 else
5903 CmdArgs.push_back("-fms-memptr-rep=virtual");
5904 }
5905
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005906 // Parse the default calling convention options.
5907 if (Arg *CCArg =
5908 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005909 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5910 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005911 unsigned DCCOptId = CCArg->getOption().getID();
5912 const char *DCCFlag = nullptr;
5913 bool ArchSupported = true;
5914 llvm::Triple::ArchType Arch = getToolChain().getArch();
5915 switch (DCCOptId) {
5916 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005917 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005918 break;
5919 case options::OPT__SLASH_Gr:
5920 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005921 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005922 break;
5923 case options::OPT__SLASH_Gz:
5924 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005925 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005926 break;
5927 case options::OPT__SLASH_Gv:
5928 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005929 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005930 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005931 case options::OPT__SLASH_Gregcall:
5932 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5933 DCCFlag = "-fdefault-calling-conv=regcall";
5934 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005935 }
5936
5937 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5938 if (ArchSupported && DCCFlag)
5939 CmdArgs.push_back(DCCFlag);
5940 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005941
Nico Weber908b6972019-06-26 17:51:47 +00005942 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005943
5944 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5945 CmdArgs.push_back("-fdiagnostics-format");
5946 if (Args.hasArg(options::OPT__SLASH_fallback))
5947 CmdArgs.push_back("msvc-fallback");
5948 else
5949 CmdArgs.push_back("msvc");
5950 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005951
Hans Wennborga912e3e2018-08-10 09:49:21 +00005952 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5953 SmallVector<StringRef, 1> SplitArgs;
5954 StringRef(A->getValue()).split(SplitArgs, ",");
5955 bool Instrument = false;
5956 bool NoChecks = false;
5957 for (StringRef Arg : SplitArgs) {
5958 if (Arg.equals_lower("cf"))
5959 Instrument = true;
5960 else if (Arg.equals_lower("cf-"))
5961 Instrument = false;
5962 else if (Arg.equals_lower("nochecks"))
5963 NoChecks = true;
5964 else if (Arg.equals_lower("nochecks-"))
5965 NoChecks = false;
5966 else
5967 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5968 }
5969 // Currently there's no support emitting CFG instrumentation; the flag only
5970 // emits the table of address-taken functions.
5971 if (Instrument || NoChecks)
5972 CmdArgs.push_back("-cfguard");
5973 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005974}
5975
5976visualstudio::Compiler *Clang::getCLFallback() const {
5977 if (!CLFallback)
5978 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5979 return CLFallback.get();
5980}
5981
5982
5983const char *Clang::getBaseInputName(const ArgList &Args,
5984 const InputInfo &Input) {
5985 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5986}
5987
5988const char *Clang::getBaseInputStem(const ArgList &Args,
5989 const InputInfoList &Inputs) {
5990 const char *Str = getBaseInputName(Args, Inputs[0]);
5991
5992 if (const char *End = strrchr(Str, '.'))
5993 return Args.MakeArgString(std::string(Str, End));
5994
5995 return Str;
5996}
5997
5998const char *Clang::getDependencyFileName(const ArgList &Args,
5999 const InputInfoList &Inputs) {
6000 // FIXME: Think about this more.
6001 std::string Res;
6002
6003 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6004 std::string Str(OutputOpt->getValue());
6005 Res = Str.substr(0, Str.rfind('.'));
6006 } else {
6007 Res = getBaseInputStem(Args, Inputs);
6008 }
6009 return Args.MakeArgString(Res + ".d");
6010}
6011
6012// Begin ClangAs
6013
6014void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6015 ArgStringList &CmdArgs) const {
6016 StringRef CPUName;
6017 StringRef ABIName;
6018 const llvm::Triple &Triple = getToolChain().getTriple();
6019 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6020
6021 CmdArgs.push_back("-target-abi");
6022 CmdArgs.push_back(ABIName.data());
6023}
6024
6025void ClangAs::AddX86TargetArgs(const ArgList &Args,
6026 ArgStringList &CmdArgs) const {
6027 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6028 StringRef Value = A->getValue();
6029 if (Value == "intel" || Value == "att") {
6030 CmdArgs.push_back("-mllvm");
6031 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6032 } else {
6033 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6034 << A->getOption().getName() << Value;
6035 }
6036 }
6037}
6038
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006039void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6040 ArgStringList &CmdArgs) const {
6041 const llvm::Triple &Triple = getToolChain().getTriple();
6042 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6043
6044 CmdArgs.push_back("-target-abi");
6045 CmdArgs.push_back(ABIName.data());
6046}
6047
David L. Jonesf561aba2017-03-08 01:02:16 +00006048void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6049 const InputInfo &Output, const InputInfoList &Inputs,
6050 const ArgList &Args,
6051 const char *LinkingOutput) const {
6052 ArgStringList CmdArgs;
6053
6054 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6055 const InputInfo &Input = Inputs[0];
6056
Martin Storsjob547ef22018-10-26 08:33:29 +00006057 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00006058 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00006059 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00006060
6061 // Don't warn about "clang -w -c foo.s"
6062 Args.ClaimAllArgs(options::OPT_w);
6063 // and "clang -emit-llvm -c foo.s"
6064 Args.ClaimAllArgs(options::OPT_emit_llvm);
6065
6066 claimNoWarnArgs(Args);
6067
6068 // Invoke ourselves in -cc1as mode.
6069 //
6070 // FIXME: Implement custom jobs for internal actions.
6071 CmdArgs.push_back("-cc1as");
6072
6073 // Add the "effective" target triple.
6074 CmdArgs.push_back("-triple");
6075 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6076
6077 // Set the output mode, we currently only expect to be used as a real
6078 // assembler.
6079 CmdArgs.push_back("-filetype");
6080 CmdArgs.push_back("obj");
6081
6082 // Set the main file name, so that debug info works even with
6083 // -save-temps or preprocessed assembly.
6084 CmdArgs.push_back("-main-file-name");
6085 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6086
6087 // Add the target cpu
6088 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6089 if (!CPU.empty()) {
6090 CmdArgs.push_back("-target-cpu");
6091 CmdArgs.push_back(Args.MakeArgString(CPU));
6092 }
6093
6094 // Add the target features
6095 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6096
6097 // Ignore explicit -force_cpusubtype_ALL option.
6098 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6099
6100 // Pass along any -I options so we get proper .include search paths.
6101 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6102
6103 // Determine the original source input.
6104 const Action *SourceAction = &JA;
6105 while (SourceAction->getKind() != Action::InputClass) {
6106 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6107 SourceAction = SourceAction->getInputs()[0];
6108 }
6109
6110 // Forward -g and handle debug info related flags, assuming we are dealing
6111 // with an actual assembly file.
6112 bool WantDebug = false;
6113 unsigned DwarfVersion = 0;
6114 Args.ClaimAllArgs(options::OPT_g_Group);
6115 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6116 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6117 !A->getOption().matches(options::OPT_ggdb0);
6118 if (WantDebug)
6119 DwarfVersion = DwarfVersionNum(A->getSpelling());
6120 }
6121 if (DwarfVersion == 0)
6122 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6123
6124 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6125
6126 if (SourceAction->getType() == types::TY_Asm ||
6127 SourceAction->getType() == types::TY_PP_Asm) {
6128 // You might think that it would be ok to set DebugInfoKind outside of
6129 // the guard for source type, however there is a test which asserts
6130 // that some assembler invocation receives no -debug-info-kind,
6131 // and it's not clear whether that test is just overly restrictive.
6132 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6133 : codegenoptions::NoDebugInfo);
6134 // Add the -fdebug-compilation-dir flag if needed.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00006135 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00006136
Paul Robinson9b292b42018-07-10 15:15:24 +00006137 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6138
David L. Jonesf561aba2017-03-08 01:02:16 +00006139 // Set the AT_producer to the clang version when using the integrated
6140 // assembler on assembly source files.
6141 CmdArgs.push_back("-dwarf-debug-producer");
6142 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6143
6144 // And pass along -I options
6145 Args.AddAllArgs(CmdArgs, options::OPT_I);
6146 }
6147 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6148 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006149 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006150
David L. Jonesf561aba2017-03-08 01:02:16 +00006151
6152 // Handle -fPIC et al -- the relocation-model affects the assembler
6153 // for some targets.
6154 llvm::Reloc::Model RelocationModel;
6155 unsigned PICLevel;
6156 bool IsPIE;
6157 std::tie(RelocationModel, PICLevel, IsPIE) =
6158 ParsePICArgs(getToolChain(), Args);
6159
6160 const char *RMName = RelocationModelName(RelocationModel);
6161 if (RMName) {
6162 CmdArgs.push_back("-mrelocation-model");
6163 CmdArgs.push_back(RMName);
6164 }
6165
6166 // Optionally embed the -cc1as level arguments into the debug info, for build
6167 // analysis.
6168 if (getToolChain().UseDwarfDebugFlags()) {
6169 ArgStringList OriginalArgs;
6170 for (const auto &Arg : Args)
6171 Arg->render(Args, OriginalArgs);
6172
6173 SmallString<256> Flags;
6174 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6175 Flags += Exec;
6176 for (const char *OriginalArg : OriginalArgs) {
6177 SmallString<128> EscapedArg;
6178 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6179 Flags += " ";
6180 Flags += EscapedArg;
6181 }
6182 CmdArgs.push_back("-dwarf-debug-flags");
6183 CmdArgs.push_back(Args.MakeArgString(Flags));
6184 }
6185
6186 // FIXME: Add -static support, once we have it.
6187
6188 // Add target specific flags.
6189 switch (getToolChain().getArch()) {
6190 default:
6191 break;
6192
6193 case llvm::Triple::mips:
6194 case llvm::Triple::mipsel:
6195 case llvm::Triple::mips64:
6196 case llvm::Triple::mips64el:
6197 AddMIPSTargetArgs(Args, CmdArgs);
6198 break;
6199
6200 case llvm::Triple::x86:
6201 case llvm::Triple::x86_64:
6202 AddX86TargetArgs(Args, CmdArgs);
6203 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006204
6205 case llvm::Triple::arm:
6206 case llvm::Triple::armeb:
6207 case llvm::Triple::thumb:
6208 case llvm::Triple::thumbeb:
6209 // This isn't in AddARMTargetArgs because we want to do this for assembly
6210 // only, not C/C++.
6211 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6212 options::OPT_mno_default_build_attributes, true)) {
6213 CmdArgs.push_back("-mllvm");
6214 CmdArgs.push_back("-arm-add-build-attributes");
6215 }
6216 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006217
6218 case llvm::Triple::riscv32:
6219 case llvm::Triple::riscv64:
6220 AddRISCVTargetArgs(Args, CmdArgs);
6221 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006222 }
6223
6224 // Consume all the warning flags. Usually this would be handled more
6225 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6226 // doesn't handle that so rather than warning about unused flags that are
6227 // actually used, we'll lie by omission instead.
6228 // FIXME: Stop lying and consume only the appropriate driver flags
6229 Args.ClaimAllArgs(options::OPT_W_Group);
6230
6231 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6232 getToolChain().getDriver());
6233
6234 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6235
6236 assert(Output.isFilename() && "Unexpected lipo output.");
6237 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006238 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006239
Petr Hosekd3265352018-10-15 21:30:32 +00006240 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006241 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006242 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6243 T.isOSBinFormatELF()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00006244 CmdArgs.push_back("-split-dwarf-output");
George Rimar36d71da2019-03-27 11:00:03 +00006245 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006246 }
6247
David L. Jonesf561aba2017-03-08 01:02:16 +00006248 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006249 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006250
6251 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6252 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006253}
6254
6255// Begin OffloadBundler
6256
6257void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6258 const InputInfo &Output,
6259 const InputInfoList &Inputs,
6260 const llvm::opt::ArgList &TCArgs,
6261 const char *LinkingOutput) const {
6262 // The version with only one output is expected to refer to a bundling job.
6263 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6264
6265 // The bundling command looks like this:
6266 // clang-offload-bundler -type=bc
6267 // -targets=host-triple,openmp-triple1,openmp-triple2
6268 // -outputs=input_file
6269 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6270
6271 ArgStringList CmdArgs;
6272
6273 // Get the type.
6274 CmdArgs.push_back(TCArgs.MakeArgString(
6275 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6276
6277 assert(JA.getInputs().size() == Inputs.size() &&
6278 "Not have inputs for all dependence actions??");
6279
6280 // Get the targets.
6281 SmallString<128> Triples;
6282 Triples += "-targets=";
6283 for (unsigned I = 0; I < Inputs.size(); ++I) {
6284 if (I)
6285 Triples += ',';
6286
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006287 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006288 Action::OffloadKind CurKind = Action::OFK_Host;
6289 const ToolChain *CurTC = &getToolChain();
6290 const Action *CurDep = JA.getInputs()[I];
6291
6292 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006293 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006294 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006295 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006296 CurKind = A->getOffloadingDeviceKind();
6297 CurTC = TC;
6298 });
6299 }
6300 Triples += Action::GetOffloadKindName(CurKind);
6301 Triples += '-';
6302 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006303 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6304 Triples += '-';
6305 Triples += CurDep->getOffloadingArch();
6306 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006307 }
6308 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6309
6310 // Get bundled file command.
6311 CmdArgs.push_back(
6312 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6313
6314 // Get unbundled files command.
6315 SmallString<128> UB;
6316 UB += "-inputs=";
6317 for (unsigned I = 0; I < Inputs.size(); ++I) {
6318 if (I)
6319 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006320
6321 // Find ToolChain for this input.
6322 const ToolChain *CurTC = &getToolChain();
6323 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6324 CurTC = nullptr;
6325 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6326 assert(CurTC == nullptr && "Expected one dependence!");
6327 CurTC = TC;
6328 });
6329 }
6330 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006331 }
6332 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6333
6334 // All the inputs are encoded as commands.
6335 C.addCommand(llvm::make_unique<Command>(
6336 JA, *this,
6337 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6338 CmdArgs, None));
6339}
6340
6341void OffloadBundler::ConstructJobMultipleOutputs(
6342 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6343 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6344 const char *LinkingOutput) const {
6345 // The version with multiple outputs is expected to refer to a unbundling job.
6346 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6347
6348 // The unbundling command looks like this:
6349 // clang-offload-bundler -type=bc
6350 // -targets=host-triple,openmp-triple1,openmp-triple2
6351 // -inputs=input_file
6352 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6353 // -unbundle
6354
6355 ArgStringList CmdArgs;
6356
6357 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6358 InputInfo Input = Inputs.front();
6359
6360 // Get the type.
6361 CmdArgs.push_back(TCArgs.MakeArgString(
6362 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6363
6364 // Get the targets.
6365 SmallString<128> Triples;
6366 Triples += "-targets=";
6367 auto DepInfo = UA.getDependentActionsInfo();
6368 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6369 if (I)
6370 Triples += ',';
6371
6372 auto &Dep = DepInfo[I];
6373 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6374 Triples += '-';
6375 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006376 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6377 !Dep.DependentBoundArch.empty()) {
6378 Triples += '-';
6379 Triples += Dep.DependentBoundArch;
6380 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006381 }
6382
6383 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6384
6385 // Get bundled file command.
6386 CmdArgs.push_back(
6387 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6388
6389 // Get unbundled files command.
6390 SmallString<128> UB;
6391 UB += "-outputs=";
6392 for (unsigned I = 0; I < Outputs.size(); ++I) {
6393 if (I)
6394 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006395 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006396 }
6397 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6398 CmdArgs.push_back("-unbundle");
6399
6400 // All the inputs are encoded as commands.
6401 C.addCommand(llvm::make_unique<Command>(
6402 JA, *this,
6403 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6404 CmdArgs, None));
6405}