blob: aa17efbee32bb591ea4d367cdd65c40d05803c39 [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:
Roger Ferrer Ibanez93c4d532019-09-10 08:16:24 +0000339 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
Alex Bradbury71f45452018-01-11 13:36:56 +0000340 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) {
Nico Weber2346b922019-08-13 17:37:09 +0000583 // We have 4 states:
584 //
585 // 00) leaf retained, non-leaf retained
586 // 01) leaf retained, non-leaf omitted (this is invalid)
587 // 10) leaf omitted, non-leaf retained
588 // (what -momit-leaf-frame-pointer was designed for)
589 // 11) leaf omitted, non-leaf omitted
590 //
591 // "omit" options taking precedence over "no-omit" options is the only way
592 // to make 3 valid states representable
Fangrui Songdc039662019-07-12 02:01:51 +0000593 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
594 options::OPT_fno_omit_frame_pointer);
595 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
596 bool NoOmitFP =
597 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
Nico Weber2346b922019-08-13 17:37:09 +0000598 bool KeepLeaf =
599 Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
600 options::OPT_mno_omit_leaf_frame_pointer, Triple.isPS4CPU());
Fangrui Songdc039662019-07-12 02:01:51 +0000601 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
602 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
Nico Weber2346b922019-08-13 17:37:09 +0000603 if (KeepLeaf)
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000604 return CodeGenOptions::FramePointerKind::NonLeaf;
605 return CodeGenOptions::FramePointerKind::All;
Fangrui Songdc039662019-07-12 02:01:51 +0000606 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000607 return CodeGenOptions::FramePointerKind::None;
David L. Jonesf561aba2017-03-08 01:02:16 +0000608}
609
610/// Add a CC1 option to specify the debug compilation directory.
Hans Wennborg999f8a72019-09-05 08:43:00 +0000611static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
Nico Weber37b75332019-06-17 12:10:40 +0000612 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
613 CmdArgs.push_back("-fdebug-compilation-dir");
614 CmdArgs.push_back(A->getValue());
Hans Wennborg999f8a72019-09-05 08:43:00 +0000615 } else {
616 SmallString<128> cwd;
617 if (!llvm::sys::fs::current_path(cwd)) {
618 CmdArgs.push_back("-fdebug-compilation-dir");
619 CmdArgs.push_back(Args.MakeArgString(cwd));
620 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000621 }
622}
623
Paul Robinson9b292b42018-07-10 15:15:24 +0000624/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
625static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
626 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
627 StringRef Map = A->getValue();
628 if (Map.find('=') == StringRef::npos)
629 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
630 else
631 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
632 A->claim();
633 }
634}
635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000636/// Vectorize at all optimization levels greater than 1 except for -Oz.
Nico Weber37b75332019-06-17 12:10:40 +0000637/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
638/// enabled.
David L. Jonesf561aba2017-03-08 01:02:16 +0000639static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
640 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
641 if (A->getOption().matches(options::OPT_O4) ||
642 A->getOption().matches(options::OPT_Ofast))
643 return true;
644
645 if (A->getOption().matches(options::OPT_O0))
646 return false;
647
648 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
649
650 // Vectorize -Os.
651 StringRef S(A->getValue());
652 if (S == "s")
653 return true;
654
655 // Don't vectorize -Oz, unless it's the slp vectorizer.
656 if (S == "z")
657 return isSlpVec;
658
659 unsigned OptLevel = 0;
660 if (S.getAsInteger(10, OptLevel))
661 return false;
662
663 return OptLevel > 1;
664 }
665
666 return false;
667}
668
669/// Add -x lang to \p CmdArgs for \p Input.
670static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
671 ArgStringList &CmdArgs) {
672 // When using -verify-pch, we don't want to provide the type
673 // 'precompiled-header' if it was inferred from the file extension
674 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
675 return;
676
677 CmdArgs.push_back("-x");
678 if (Args.hasArg(options::OPT_rewrite_objc))
679 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000680 else {
681 // Map the driver type to the frontend type. This is mostly an identity
682 // mapping, except that the distinction between module interface units
683 // and other source files does not exist at the frontend layer.
684 const char *ClangType;
685 switch (Input.getType()) {
686 case types::TY_CXXModule:
687 ClangType = "c++";
688 break;
689 case types::TY_PP_CXXModule:
690 ClangType = "c++-cpp-output";
691 break;
692 default:
693 ClangType = types::getTypeName(Input.getType());
694 break;
695 }
696 CmdArgs.push_back(ClangType);
697 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000698}
699
700static void appendUserToPath(SmallVectorImpl<char> &Result) {
701#ifdef LLVM_ON_UNIX
702 const char *Username = getenv("LOGNAME");
703#else
704 const char *Username = getenv("USERNAME");
705#endif
706 if (Username) {
707 // Validate that LoginName can be used in a path, and get its length.
708 size_t Len = 0;
709 for (const char *P = Username; *P; ++P, ++Len) {
710 if (!clang::isAlphanumeric(*P) && *P != '_') {
711 Username = nullptr;
712 break;
713 }
714 }
715
716 if (Username && Len > 0) {
717 Result.append(Username, Username + Len);
718 return;
719 }
720 }
721
722// Fallback to user id.
723#ifdef LLVM_ON_UNIX
724 std::string UID = llvm::utostr(getuid());
725#else
726 // FIXME: Windows seems to have an 'SID' that might work.
727 std::string UID = "9999";
728#endif
729 Result.append(UID.begin(), UID.end());
730}
731
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000732static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
733 const Driver &D, const InputInfo &Output,
734 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000735 ArgStringList &CmdArgs) {
736
737 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
738 options::OPT_fprofile_generate_EQ,
739 options::OPT_fno_profile_generate);
740 if (PGOGenerateArg &&
741 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
742 PGOGenerateArg = nullptr;
743
Rong Xua4a09b22019-03-04 20:21:31 +0000744 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
745 options::OPT_fcs_profile_generate_EQ,
746 options::OPT_fno_profile_generate);
747 if (CSPGOGenerateArg &&
748 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
749 CSPGOGenerateArg = nullptr;
750
David L. Jonesf561aba2017-03-08 01:02:16 +0000751 auto *ProfileGenerateArg = Args.getLastArg(
752 options::OPT_fprofile_instr_generate,
753 options::OPT_fprofile_instr_generate_EQ,
754 options::OPT_fno_profile_instr_generate);
755 if (ProfileGenerateArg &&
756 ProfileGenerateArg->getOption().matches(
757 options::OPT_fno_profile_instr_generate))
758 ProfileGenerateArg = nullptr;
759
760 if (PGOGenerateArg && ProfileGenerateArg)
761 D.Diag(diag::err_drv_argument_not_allowed_with)
762 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
763
764 auto *ProfileUseArg = getLastProfileUseArg(Args);
765
766 if (PGOGenerateArg && ProfileUseArg)
767 D.Diag(diag::err_drv_argument_not_allowed_with)
768 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
769
770 if (ProfileGenerateArg && ProfileUseArg)
771 D.Diag(diag::err_drv_argument_not_allowed_with)
772 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
773
Rong Xua4a09b22019-03-04 20:21:31 +0000774 if (CSPGOGenerateArg && PGOGenerateArg)
775 D.Diag(diag::err_drv_argument_not_allowed_with)
776 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
777
David L. Jonesf561aba2017-03-08 01:02:16 +0000778 if (ProfileGenerateArg) {
779 if (ProfileGenerateArg->getOption().matches(
780 options::OPT_fprofile_instr_generate_EQ))
781 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
782 ProfileGenerateArg->getValue()));
783 // The default is to use Clang Instrumentation.
784 CmdArgs.push_back("-fprofile-instrument=clang");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000785 if (TC.getTriple().isWindowsMSVCEnvironment()) {
786 // Add dependent lib for clang_rt.profile
787 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
788 TC.getCompilerRT(Args, "profile")));
789 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000790 }
791
Rong Xua4a09b22019-03-04 20:21:31 +0000792 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000793 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000794 assert(!CSPGOGenerateArg);
795 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000796 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000797 }
798 if (CSPGOGenerateArg) {
799 assert(!PGOGenerateArg);
800 PGOGenArg = CSPGOGenerateArg;
801 CmdArgs.push_back("-fprofile-instrument=csllvm");
802 }
803 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000804 if (TC.getTriple().isWindowsMSVCEnvironment()) {
805 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
806 TC.getCompilerRT(Args, "profile")));
807 }
Rong Xua4a09b22019-03-04 20:21:31 +0000808 if (PGOGenArg->getOption().matches(
809 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
810 : options::OPT_fcs_profile_generate_EQ)) {
811 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000812 llvm::sys::path::append(Path, "default_%m.profraw");
813 CmdArgs.push_back(
814 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
815 }
816 }
817
818 if (ProfileUseArg) {
819 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
820 CmdArgs.push_back(Args.MakeArgString(
821 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
822 else if ((ProfileUseArg->getOption().matches(
823 options::OPT_fprofile_use_EQ) ||
824 ProfileUseArg->getOption().matches(
825 options::OPT_fprofile_instr_use))) {
826 SmallString<128> Path(
827 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
828 if (Path.empty() || llvm::sys::fs::is_directory(Path))
829 llvm::sys::path::append(Path, "default.profdata");
830 CmdArgs.push_back(
831 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
832 }
833 }
834
835 if (Args.hasArg(options::OPT_ftest_coverage) ||
836 Args.hasArg(options::OPT_coverage))
837 CmdArgs.push_back("-femit-coverage-notes");
838 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
839 false) ||
840 Args.hasArg(options::OPT_coverage))
841 CmdArgs.push_back("-femit-coverage-data");
842
843 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000844 options::OPT_fno_coverage_mapping, false)) {
845 if (!ProfileGenerateArg)
846 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
847 << "-fcoverage-mapping"
848 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000849
David L. Jonesf561aba2017-03-08 01:02:16 +0000850 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000851 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000852
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000853 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
854 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
855 if (!Args.hasArg(options::OPT_coverage))
856 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
857 << "-fprofile-exclude-files="
858 << "--coverage";
859
860 StringRef v = Arg->getValue();
861 CmdArgs.push_back(
862 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
863 }
864
865 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
866 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
867 if (!Args.hasArg(options::OPT_coverage))
868 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
869 << "-fprofile-filter-files="
870 << "--coverage";
871
872 StringRef v = Arg->getValue();
873 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
874 }
875
David L. Jonesf561aba2017-03-08 01:02:16 +0000876 if (C.getArgs().hasArg(options::OPT_c) ||
877 C.getArgs().hasArg(options::OPT_S)) {
878 if (Output.isFilename()) {
879 CmdArgs.push_back("-coverage-notes-file");
880 SmallString<128> OutputFilename;
881 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
882 OutputFilename = FinalOutput->getValue();
883 else
884 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
885 SmallString<128> CoverageFilename = OutputFilename;
Hans Wennborg999f8a72019-09-05 08:43:00 +0000886 if (llvm::sys::path::is_relative(CoverageFilename)) {
887 SmallString<128> Pwd;
888 if (!llvm::sys::fs::current_path(Pwd)) {
889 llvm::sys::path::append(Pwd, CoverageFilename);
890 CoverageFilename.swap(Pwd);
891 }
892 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000893 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
894 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
895
896 // Leave -fprofile-dir= an unused argument unless .gcda emission is
897 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
898 // the flag used. There is no -fno-profile-dir, so the user has no
899 // targeted way to suppress the warning.
900 if (Args.hasArg(options::OPT_fprofile_arcs) ||
901 Args.hasArg(options::OPT_coverage)) {
902 CmdArgs.push_back("-coverage-data-file");
903 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
904 CoverageFilename = FProfileDir->getValue();
905 llvm::sys::path::append(CoverageFilename, OutputFilename);
906 }
907 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
908 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
909 }
910 }
911 }
912}
913
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000914/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000915static bool ContainsCompileAction(const Action *A) {
916 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
917 return true;
918
919 for (const auto &AI : A->inputs())
920 if (ContainsCompileAction(AI))
921 return true;
922
923 return false;
924}
925
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000926/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000927/// This is done by default when compiling non-assembler source with -O0.
928static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
929 bool RelaxDefault = true;
930
931 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
932 RelaxDefault = A->getOption().matches(options::OPT_O0);
933
934 if (RelaxDefault) {
935 RelaxDefault = false;
936 for (const auto &Act : C.getActions()) {
937 if (ContainsCompileAction(Act)) {
938 RelaxDefault = true;
939 break;
940 }
941 }
942 }
943
944 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
945 RelaxDefault);
946}
947
948// Extract the integer N from a string spelled "-dwarf-N", returning 0
949// on mismatch. The StringRef input (rather than an Arg) allows
950// for use by the "-Xassembler" option parser.
951static unsigned DwarfVersionNum(StringRef ArgValue) {
952 return llvm::StringSwitch<unsigned>(ArgValue)
953 .Case("-gdwarf-2", 2)
954 .Case("-gdwarf-3", 3)
955 .Case("-gdwarf-4", 4)
956 .Case("-gdwarf-5", 5)
957 .Default(0);
958}
959
960static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
961 codegenoptions::DebugInfoKind DebugInfoKind,
962 unsigned DwarfVersion,
963 llvm::DebuggerKind DebuggerTuning) {
964 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000965 case codegenoptions::DebugDirectivesOnly:
966 CmdArgs.push_back("-debug-info-kind=line-directives-only");
967 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000968 case codegenoptions::DebugLineTablesOnly:
969 CmdArgs.push_back("-debug-info-kind=line-tables-only");
970 break;
971 case codegenoptions::LimitedDebugInfo:
972 CmdArgs.push_back("-debug-info-kind=limited");
973 break;
974 case codegenoptions::FullDebugInfo:
975 CmdArgs.push_back("-debug-info-kind=standalone");
976 break;
977 default:
978 break;
979 }
980 if (DwarfVersion > 0)
981 CmdArgs.push_back(
982 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
983 switch (DebuggerTuning) {
984 case llvm::DebuggerKind::GDB:
985 CmdArgs.push_back("-debugger-tuning=gdb");
986 break;
987 case llvm::DebuggerKind::LLDB:
988 CmdArgs.push_back("-debugger-tuning=lldb");
989 break;
990 case llvm::DebuggerKind::SCE:
991 CmdArgs.push_back("-debugger-tuning=sce");
992 break;
993 default:
994 break;
995 }
996}
997
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000998static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
999 const Driver &D, const ToolChain &TC) {
1000 assert(A && "Expected non-nullptr argument.");
1001 if (TC.supportsDebugInfoOption(A))
1002 return true;
1003 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1004 << A->getAsString(Args) << TC.getTripleString();
1005 return false;
1006}
1007
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001008static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1009 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001010 const Driver &D,
1011 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001012 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
1013 if (!A)
1014 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001015 if (checkDebugInfoOption(A, Args, D, TC)) {
1016 if (A->getOption().getID() == options::OPT_gz) {
1017 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001018 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001019 else
1020 D.Diag(diag::warn_debug_compression_unavailable);
1021 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001022 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001023
1024 StringRef Value = A->getValue();
1025 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001026 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001027 } else if (Value == "zlib" || Value == "zlib-gnu") {
1028 if (llvm::zlib::isAvailable()) {
1029 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001030 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001031 } else {
1032 D.Diag(diag::warn_debug_compression_unavailable);
1033 }
1034 } else {
1035 D.Diag(diag::err_drv_unsupported_option_argument)
1036 << A->getOption().getName() << Value;
1037 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001038 }
1039}
1040
David L. Jonesf561aba2017-03-08 01:02:16 +00001041static const char *RelocationModelName(llvm::Reloc::Model Model) {
1042 switch (Model) {
1043 case llvm::Reloc::Static:
1044 return "static";
1045 case llvm::Reloc::PIC_:
1046 return "pic";
1047 case llvm::Reloc::DynamicNoPIC:
1048 return "dynamic-no-pic";
1049 case llvm::Reloc::ROPI:
1050 return "ropi";
1051 case llvm::Reloc::RWPI:
1052 return "rwpi";
1053 case llvm::Reloc::ROPI_RWPI:
1054 return "ropi-rwpi";
1055 }
1056 llvm_unreachable("Unknown Reloc::Model kind");
1057}
1058
1059void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1060 const Driver &D, const ArgList &Args,
1061 ArgStringList &CmdArgs,
1062 const InputInfo &Output,
1063 const InputInfoList &Inputs) const {
David L. Jonesf561aba2017-03-08 01:02:16 +00001064 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1065
1066 CheckPreprocessingOptions(D, Args);
1067
1068 Args.AddLastArg(CmdArgs, options::OPT_C);
1069 Args.AddLastArg(CmdArgs, options::OPT_CC);
1070
1071 // Handle dependency file generation.
Fangrui Song55abd2b2019-09-14 06:01:22 +00001072 Arg *ArgM = Args.getLastArg(options::OPT_MM);
1073 if (!ArgM)
1074 ArgM = Args.getLastArg(options::OPT_M);
1075 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1076 if (!ArgMD)
1077 ArgMD = Args.getLastArg(options::OPT_MD);
1078
1079 // -M and -MM imply -w.
1080 if (ArgM)
1081 CmdArgs.push_back("-w");
1082 else
1083 ArgM = ArgMD;
1084
1085 if (ArgM) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001086 // Determine the output location.
1087 const char *DepFile;
1088 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1089 DepFile = MF->getValue();
1090 C.addFailureResultFile(DepFile, &JA);
1091 } else if (Output.getType() == types::TY_Dependencies) {
1092 DepFile = Output.getFilename();
Fangrui Song55abd2b2019-09-14 06:01:22 +00001093 } else if (!ArgMD) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001094 DepFile = "-";
1095 } else {
1096 DepFile = getDependencyFileName(Args, Inputs);
1097 C.addFailureResultFile(DepFile, &JA);
1098 }
1099 CmdArgs.push_back("-dependency-file");
1100 CmdArgs.push_back(DepFile);
1101
Fangrui Song55abd2b2019-09-14 06:01:22 +00001102 bool HasTarget = false;
1103 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1104 HasTarget = true;
1105 A->claim();
1106 if (A->getOption().matches(options::OPT_MT)) {
1107 A->render(Args, CmdArgs);
1108 } else {
1109 CmdArgs.push_back("-MT");
1110 SmallString<128> Quoted;
1111 QuoteTarget(A->getValue(), Quoted);
1112 CmdArgs.push_back(Args.MakeArgString(Quoted));
1113 }
1114 }
1115
David L. Jonesf561aba2017-03-08 01:02:16 +00001116 // Add a default target if one wasn't specified.
Fangrui Song55abd2b2019-09-14 06:01:22 +00001117 if (!HasTarget) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001118 const char *DepTarget;
1119
1120 // If user provided -o, that is the dependency target, except
1121 // when we are only generating a dependency file.
1122 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1123 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1124 DepTarget = OutputOpt->getValue();
1125 } else {
1126 // Otherwise derive from the base input.
1127 //
1128 // FIXME: This should use the computed output file location.
1129 SmallString<128> P(Inputs[0].getBaseInput());
1130 llvm::sys::path::replace_extension(P, "o");
1131 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1132 }
1133
1134 CmdArgs.push_back("-MT");
1135 SmallString<128> Quoted;
1136 QuoteTarget(DepTarget, Quoted);
1137 CmdArgs.push_back(Args.MakeArgString(Quoted));
1138 }
1139
Fangrui Song55abd2b2019-09-14 06:01:22 +00001140 if (ArgM->getOption().matches(options::OPT_M) ||
1141 ArgM->getOption().matches(options::OPT_MD))
David L. Jonesf561aba2017-03-08 01:02:16 +00001142 CmdArgs.push_back("-sys-header-deps");
1143 if ((isa<PrecompileJobAction>(JA) &&
1144 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1145 Args.hasArg(options::OPT_fmodule_file_deps))
1146 CmdArgs.push_back("-module-file-deps");
1147 }
1148
1149 if (Args.hasArg(options::OPT_MG)) {
Fangrui Song55abd2b2019-09-14 06:01:22 +00001150 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1151 ArgM->getOption().matches(options::OPT_MMD))
David L. Jonesf561aba2017-03-08 01:02:16 +00001152 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1153 CmdArgs.push_back("-MG");
1154 }
1155
1156 Args.AddLastArg(CmdArgs, options::OPT_MP);
1157 Args.AddLastArg(CmdArgs, options::OPT_MV);
1158
David L. Jonesf561aba2017-03-08 01:02:16 +00001159 // Add offload include arguments specific for CUDA. This must happen before
1160 // we -I or -include anything else, because we must pick up the CUDA headers
1161 // from the particular CUDA installation, rather than from e.g.
1162 // /usr/local/include.
1163 if (JA.isOffloading(Action::OFK_Cuda))
1164 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1165
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001166 // If we are offloading to a target via OpenMP we need to include the
1167 // openmp_wrappers folder which contains alternative system headers.
1168 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1169 getToolChain().getTriple().isNVPTX()){
1170 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1171 // Add openmp_wrappers/* to our system include path. This lets us wrap
1172 // standard library headers.
1173 SmallString<128> P(D.ResourceDir);
1174 llvm::sys::path::append(P, "include");
1175 llvm::sys::path::append(P, "openmp_wrappers");
1176 CmdArgs.push_back("-internal-isystem");
1177 CmdArgs.push_back(Args.MakeArgString(P));
1178 }
1179
1180 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001181 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001182 }
1183
David L. Jonesf561aba2017-03-08 01:02:16 +00001184 // Add -i* options, and automatically translate to
1185 // -include-pch/-include-pth for transparent PCH support. It's
1186 // wonky, but we include looking for .gch so we can support seamless
1187 // replacement into a build system already set up to be generating
1188 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001189
1190 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001191 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1192 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001193 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1194 JA.getKind() <= Action::AssembleJobClass) {
1195 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001196 }
Erich Keane76675de2018-07-05 17:22:13 +00001197 if (YcArg || YuArg) {
1198 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1199 if (!isa<PrecompileJobAction>(JA)) {
1200 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001201 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1202 C, !ThroughHeader.empty()
1203 ? ThroughHeader
1204 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001205 }
Mike Rice58df1af2018-09-11 17:10:44 +00001206
1207 if (ThroughHeader.empty()) {
1208 CmdArgs.push_back(Args.MakeArgString(
1209 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1210 } else {
1211 CmdArgs.push_back(
1212 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1213 }
Erich Keane76675de2018-07-05 17:22:13 +00001214 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001215 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001216
1217 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001218 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001219 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001220 // Handling of gcc-style gch precompiled headers.
1221 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1222 RenderedImplicitInclude = true;
1223
David L. Jonesf561aba2017-03-08 01:02:16 +00001224 bool FoundPCH = false;
1225 SmallString<128> P(A->getValue());
1226 // We want the files to have a name like foo.h.pch. Add a dummy extension
1227 // so that replace_extension does the right thing.
1228 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001229 llvm::sys::path::replace_extension(P, "pch");
1230 if (llvm::sys::fs::exists(P))
1231 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001232
1233 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001234 llvm::sys::path::replace_extension(P, "gch");
1235 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001236 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001237 }
1238 }
1239
Erich Keane0a6b5b62018-12-04 14:34:09 +00001240 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001241 if (IsFirstImplicitInclude) {
1242 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001243 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001244 CmdArgs.push_back(Args.MakeArgString(P));
1245 continue;
1246 } else {
1247 // Ignore the PCH if not first on command line and emit warning.
1248 D.Diag(diag::warn_drv_pch_not_first_include) << P
1249 << A->getAsString(Args);
1250 }
1251 }
1252 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1253 // Handling of paths which must come late. These entries are handled by
1254 // the toolchain itself after the resource dir is inserted in the right
1255 // search order.
1256 // Do not claim the argument so that the use of the argument does not
1257 // silently go unnoticed on toolchains which do not honour the option.
1258 continue;
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001259 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1260 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1261 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00001262 }
1263
1264 // Not translated, render as usual.
1265 A->claim();
1266 A->render(Args, CmdArgs);
1267 }
1268
1269 Args.AddAllArgs(CmdArgs,
1270 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1271 options::OPT_F, options::OPT_index_header_map});
1272
1273 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1274
1275 // FIXME: There is a very unfortunate problem here, some troubled
1276 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1277 // really support that we would have to parse and then translate
1278 // those options. :(
1279 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1280 options::OPT_Xpreprocessor);
1281
1282 // -I- is a deprecated GCC feature, reject it.
1283 if (Arg *A = Args.getLastArg(options::OPT_I_))
1284 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1285
1286 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1287 // -isysroot to the CC1 invocation.
1288 StringRef sysroot = C.getSysRoot();
1289 if (sysroot != "") {
1290 if (!Args.hasArg(options::OPT_isysroot)) {
1291 CmdArgs.push_back("-isysroot");
1292 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1293 }
1294 }
1295
1296 // Parse additional include paths from environment variables.
1297 // FIXME: We should probably sink the logic for handling these from the
1298 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1299 // CPATH - included following the user specified includes (but prior to
1300 // builtin and standard includes).
1301 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1302 // C_INCLUDE_PATH - system includes enabled when compiling C.
1303 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1304 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1305 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1306 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1307 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1308 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1309 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1310
1311 // While adding the include arguments, we also attempt to retrieve the
1312 // arguments of related offloading toolchains or arguments that are specific
1313 // of an offloading programming model.
1314
1315 // Add C++ include arguments, if needed.
Shoaib Meenaib50e8c52019-08-06 06:48:43 +00001316 if (types::isCXX(Inputs[0].getType())) {
1317 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1318 forAllAssociatedToolChains(
1319 C, JA, getToolChain(),
1320 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1321 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1322 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1323 });
1324 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001325
1326 // Add system include arguments for all targets but IAMCU.
1327 if (!IsIAMCU)
1328 forAllAssociatedToolChains(C, JA, getToolChain(),
1329 [&Args, &CmdArgs](const ToolChain &TC) {
1330 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1331 });
1332 else {
1333 // For IAMCU add special include arguments.
1334 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1335 }
1336}
1337
1338// FIXME: Move to target hook.
1339static bool isSignedCharDefault(const llvm::Triple &Triple) {
1340 switch (Triple.getArch()) {
1341 default:
1342 return true;
1343
1344 case llvm::Triple::aarch64:
1345 case llvm::Triple::aarch64_be:
1346 case llvm::Triple::arm:
1347 case llvm::Triple::armeb:
1348 case llvm::Triple::thumb:
1349 case llvm::Triple::thumbeb:
1350 if (Triple.isOSDarwin() || Triple.isOSWindows())
1351 return true;
1352 return false;
1353
1354 case llvm::Triple::ppc:
1355 case llvm::Triple::ppc64:
1356 if (Triple.isOSDarwin())
1357 return true;
1358 return false;
1359
1360 case llvm::Triple::hexagon:
1361 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001362 case llvm::Triple::riscv32:
1363 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001364 case llvm::Triple::systemz:
1365 case llvm::Triple::xcore:
1366 return false;
1367 }
1368}
1369
1370static bool isNoCommonDefault(const llvm::Triple &Triple) {
1371 switch (Triple.getArch()) {
1372 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001373 if (Triple.isOSFuchsia())
1374 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001375 return false;
1376
1377 case llvm::Triple::xcore:
1378 case llvm::Triple::wasm32:
1379 case llvm::Triple::wasm64:
1380 return true;
1381 }
1382}
1383
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001384namespace {
1385void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1386 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001387 // Select the ABI to use.
1388 // FIXME: Support -meabi.
1389 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1390 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001391 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001392 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001393 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001394 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001395 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001396 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001397
David L. Jonesf561aba2017-03-08 01:02:16 +00001398 CmdArgs.push_back("-target-abi");
1399 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001400}
1401}
1402
1403void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1404 ArgStringList &CmdArgs, bool KernelOrKext) const {
1405 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001406
1407 // Determine floating point ABI from the options & target defaults.
1408 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1409 if (ABI == arm::FloatABI::Soft) {
1410 // Floating point operations and argument passing are soft.
1411 // FIXME: This changes CPP defines, we need -target-soft-float.
1412 CmdArgs.push_back("-msoft-float");
1413 CmdArgs.push_back("-mfloat-abi");
1414 CmdArgs.push_back("soft");
1415 } else if (ABI == arm::FloatABI::SoftFP) {
1416 // Floating point operations are hard, but argument passing is soft.
1417 CmdArgs.push_back("-mfloat-abi");
1418 CmdArgs.push_back("soft");
1419 } else {
1420 // Floating point operations and argument passing are hard.
1421 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1422 CmdArgs.push_back("-mfloat-abi");
1423 CmdArgs.push_back("hard");
1424 }
1425
1426 // Forward the -mglobal-merge option for explicit control over the pass.
1427 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1428 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001429 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001430 if (A->getOption().matches(options::OPT_mno_global_merge))
1431 CmdArgs.push_back("-arm-global-merge=false");
1432 else
1433 CmdArgs.push_back("-arm-global-merge=true");
1434 }
1435
1436 if (!Args.hasFlag(options::OPT_mimplicit_float,
1437 options::OPT_mno_implicit_float, true))
1438 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001439
1440 if (Args.getLastArg(options::OPT_mcmse))
1441 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001442}
1443
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001444void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1445 const ArgList &Args, bool KernelOrKext,
1446 ArgStringList &CmdArgs) const {
1447 const ToolChain &TC = getToolChain();
1448
1449 // Add the target features
1450 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1451
1452 // Add target specific flags.
1453 switch (TC.getArch()) {
1454 default:
1455 break;
1456
1457 case llvm::Triple::arm:
1458 case llvm::Triple::armeb:
1459 case llvm::Triple::thumb:
1460 case llvm::Triple::thumbeb:
1461 // Use the effective triple, which takes into account the deployment target.
1462 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1463 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1464 break;
1465
1466 case llvm::Triple::aarch64:
1467 case llvm::Triple::aarch64_be:
1468 AddAArch64TargetArgs(Args, CmdArgs);
1469 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1470 break;
1471
1472 case llvm::Triple::mips:
1473 case llvm::Triple::mipsel:
1474 case llvm::Triple::mips64:
1475 case llvm::Triple::mips64el:
1476 AddMIPSTargetArgs(Args, CmdArgs);
1477 break;
1478
1479 case llvm::Triple::ppc:
1480 case llvm::Triple::ppc64:
1481 case llvm::Triple::ppc64le:
1482 AddPPCTargetArgs(Args, CmdArgs);
1483 break;
1484
Alex Bradbury71f45452018-01-11 13:36:56 +00001485 case llvm::Triple::riscv32:
1486 case llvm::Triple::riscv64:
1487 AddRISCVTargetArgs(Args, CmdArgs);
1488 break;
1489
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001490 case llvm::Triple::sparc:
1491 case llvm::Triple::sparcel:
1492 case llvm::Triple::sparcv9:
1493 AddSparcTargetArgs(Args, CmdArgs);
1494 break;
1495
1496 case llvm::Triple::systemz:
1497 AddSystemZTargetArgs(Args, CmdArgs);
1498 break;
1499
1500 case llvm::Triple::x86:
1501 case llvm::Triple::x86_64:
1502 AddX86TargetArgs(Args, CmdArgs);
1503 break;
1504
1505 case llvm::Triple::lanai:
1506 AddLanaiTargetArgs(Args, CmdArgs);
1507 break;
1508
1509 case llvm::Triple::hexagon:
1510 AddHexagonTargetArgs(Args, CmdArgs);
1511 break;
1512
1513 case llvm::Triple::wasm32:
1514 case llvm::Triple::wasm64:
1515 AddWebAssemblyTargetArgs(Args, CmdArgs);
1516 break;
1517 }
1518}
1519
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001520// Parse -mbranch-protection=<protection>[+<protection>]* where
1521// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1522// Returns a triple of (return address signing Scope, signing key, require
1523// landing pads)
1524static std::tuple<StringRef, StringRef, bool>
1525ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1526 const Arg *A) {
1527 StringRef Scope = "none";
1528 StringRef Key = "a_key";
1529 bool IndirectBranches = false;
1530
1531 StringRef Value = A->getValue();
1532 // This maps onto -mbranch-protection=<scope>+<key>
1533
1534 if (Value.equals("standard")) {
1535 Scope = "non-leaf";
1536 Key = "a_key";
1537 IndirectBranches = true;
1538
1539 } else if (!Value.equals("none")) {
1540 SmallVector<StringRef, 4> BranchProtection;
1541 StringRef(A->getValue()).split(BranchProtection, '+');
1542
1543 auto Protection = BranchProtection.begin();
1544 while (Protection != BranchProtection.end()) {
1545 if (Protection->equals("bti"))
1546 IndirectBranches = true;
1547 else if (Protection->equals("pac-ret")) {
1548 Scope = "non-leaf";
1549 while (++Protection != BranchProtection.end()) {
1550 // Inner loop as "leaf" and "b-key" options must only appear attached
1551 // to pac-ret.
1552 if (Protection->equals("leaf"))
1553 Scope = "all";
1554 else if (Protection->equals("b-key"))
1555 Key = "b_key";
1556 else
1557 break;
1558 }
1559 Protection--;
1560 } else
1561 D.Diag(diag::err_invalid_branch_protection)
1562 << *Protection << A->getAsString(Args);
1563 Protection++;
1564 }
1565 }
1566
1567 return std::make_tuple(Scope, Key, IndirectBranches);
1568}
1569
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001570namespace {
1571void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1572 ArgStringList &CmdArgs) {
1573 const char *ABIName = nullptr;
1574 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1575 ABIName = A->getValue();
1576 else if (Triple.isOSDarwin())
1577 ABIName = "darwinpcs";
1578 else
1579 ABIName = "aapcs";
1580
1581 CmdArgs.push_back("-target-abi");
1582 CmdArgs.push_back(ABIName);
1583}
1584}
1585
David L. Jonesf561aba2017-03-08 01:02:16 +00001586void Clang::AddAArch64TargetArgs(const ArgList &Args,
1587 ArgStringList &CmdArgs) const {
1588 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1589
1590 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1591 Args.hasArg(options::OPT_mkernel) ||
1592 Args.hasArg(options::OPT_fapple_kext))
1593 CmdArgs.push_back("-disable-red-zone");
1594
1595 if (!Args.hasFlag(options::OPT_mimplicit_float,
1596 options::OPT_mno_implicit_float, true))
1597 CmdArgs.push_back("-no-implicit-float");
1598
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001599 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001600
1601 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1602 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001603 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001604 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1605 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1606 else
1607 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1608 } else if (Triple.isAndroid()) {
1609 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001610 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001611 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1612 }
1613
1614 // Forward the -mglobal-merge option for explicit control over the pass.
1615 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1616 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001617 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001618 if (A->getOption().matches(options::OPT_mno_global_merge))
1619 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1620 else
1621 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1622 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001623
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001624 // Enable/disable return address signing and indirect branch targets.
1625 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1626 options::OPT_mbranch_protection_EQ)) {
1627
1628 const Driver &D = getToolChain().getDriver();
1629
1630 StringRef Scope, Key;
1631 bool IndirectBranches;
1632
1633 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1634 Scope = A->getValue();
1635 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1636 !Scope.equals("all"))
1637 D.Diag(diag::err_invalid_branch_protection)
1638 << Scope << A->getAsString(Args);
1639 Key = "a_key";
1640 IndirectBranches = false;
1641 } else
1642 std::tie(Scope, Key, IndirectBranches) =
1643 ParseAArch64BranchProtection(D, Args, A);
1644
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001645 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001646 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1647 CmdArgs.push_back(
1648 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1649 if (IndirectBranches)
1650 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001651 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001652}
1653
1654void Clang::AddMIPSTargetArgs(const ArgList &Args,
1655 ArgStringList &CmdArgs) const {
1656 const Driver &D = getToolChain().getDriver();
1657 StringRef CPUName;
1658 StringRef ABIName;
1659 const llvm::Triple &Triple = getToolChain().getTriple();
1660 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1661
1662 CmdArgs.push_back("-target-abi");
1663 CmdArgs.push_back(ABIName.data());
1664
1665 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1666 if (ABI == mips::FloatABI::Soft) {
1667 // Floating point operations and argument passing are soft.
1668 CmdArgs.push_back("-msoft-float");
1669 CmdArgs.push_back("-mfloat-abi");
1670 CmdArgs.push_back("soft");
1671 } else {
1672 // Floating point operations and argument passing are hard.
1673 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1674 CmdArgs.push_back("-mfloat-abi");
1675 CmdArgs.push_back("hard");
1676 }
1677
David L. Jonesf561aba2017-03-08 01:02:16 +00001678 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1679 options::OPT_mno_ldc1_sdc1)) {
1680 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1681 CmdArgs.push_back("-mllvm");
1682 CmdArgs.push_back("-mno-ldc1-sdc1");
1683 }
1684 }
1685
1686 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1687 options::OPT_mno_check_zero_division)) {
1688 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1689 CmdArgs.push_back("-mllvm");
1690 CmdArgs.push_back("-mno-check-zero-division");
1691 }
1692 }
1693
1694 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1695 StringRef v = A->getValue();
1696 CmdArgs.push_back("-mllvm");
1697 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1698 A->claim();
1699 }
1700
Simon Dardis31636a12017-07-20 14:04:12 +00001701 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1702 Arg *ABICalls =
1703 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1704
1705 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1706 // -mgpopt is the default for static, -fno-pic environments but these two
1707 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1708 // the only case where -mllvm -mgpopt is passed.
1709 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1710 // passed explicitly when compiling something with -mabicalls
1711 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001712 //
1713 // When the ABI in use is N64, we also need to determine the PIC mode that
1714 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001715 bool NoABICalls =
1716 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001717
1718 llvm::Reloc::Model RelocationModel;
1719 unsigned PICLevel;
1720 bool IsPIE;
1721 std::tie(RelocationModel, PICLevel, IsPIE) =
1722 ParsePICArgs(getToolChain(), Args);
1723
1724 NoABICalls = NoABICalls ||
1725 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1726
Simon Dardis31636a12017-07-20 14:04:12 +00001727 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1728 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1729 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1730 CmdArgs.push_back("-mllvm");
1731 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001732
1733 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1734 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001735 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001736 options::OPT_mno_extern_sdata);
1737 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1738 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001739 if (LocalSData) {
1740 CmdArgs.push_back("-mllvm");
1741 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1742 CmdArgs.push_back("-mlocal-sdata=1");
1743 } else {
1744 CmdArgs.push_back("-mlocal-sdata=0");
1745 }
1746 LocalSData->claim();
1747 }
1748
Simon Dardis7d318782017-07-24 14:02:09 +00001749 if (ExternSData) {
1750 CmdArgs.push_back("-mllvm");
1751 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1752 CmdArgs.push_back("-mextern-sdata=1");
1753 } else {
1754 CmdArgs.push_back("-mextern-sdata=0");
1755 }
1756 ExternSData->claim();
1757 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001758
1759 if (EmbeddedData) {
1760 CmdArgs.push_back("-mllvm");
1761 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1762 CmdArgs.push_back("-membedded-data=1");
1763 } else {
1764 CmdArgs.push_back("-membedded-data=0");
1765 }
1766 EmbeddedData->claim();
1767 }
1768
Simon Dardis31636a12017-07-20 14:04:12 +00001769 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1770 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1771
1772 if (GPOpt)
1773 GPOpt->claim();
1774
David L. Jonesf561aba2017-03-08 01:02:16 +00001775 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1776 StringRef Val = StringRef(A->getValue());
1777 if (mips::hasCompactBranches(CPUName)) {
1778 if (Val == "never" || Val == "always" || Val == "optimal") {
1779 CmdArgs.push_back("-mllvm");
1780 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1781 } else
1782 D.Diag(diag::err_drv_unsupported_option_argument)
1783 << A->getOption().getName() << Val;
1784 } else
1785 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1786 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001787
1788 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1789 options::OPT_mno_relax_pic_calls)) {
1790 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1791 CmdArgs.push_back("-mllvm");
1792 CmdArgs.push_back("-mips-jalr-reloc=0");
1793 }
1794 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001795}
1796
1797void Clang::AddPPCTargetArgs(const ArgList &Args,
1798 ArgStringList &CmdArgs) const {
1799 // Select the ABI to use.
1800 const char *ABIName = nullptr;
1801 if (getToolChain().getTriple().isOSLinux())
1802 switch (getToolChain().getArch()) {
1803 case llvm::Triple::ppc64: {
1804 // When targeting a processor that supports QPX, or if QPX is
1805 // specifically enabled, default to using the ABI that supports QPX (so
1806 // long as it is not specifically disabled).
1807 bool HasQPX = false;
1808 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1809 HasQPX = A->getValue() == StringRef("a2q");
1810 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1811 if (HasQPX) {
1812 ABIName = "elfv1-qpx";
1813 break;
1814 }
1815
1816 ABIName = "elfv1";
1817 break;
1818 }
1819 case llvm::Triple::ppc64le:
1820 ABIName = "elfv2";
1821 break;
1822 default:
1823 break;
1824 }
1825
Fangrui Song6bd02a42019-07-15 07:25:11 +00001826 bool IEEELongDouble = false;
1827 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1828 StringRef V = A->getValue();
1829 if (V == "ieeelongdouble")
1830 IEEELongDouble = true;
1831 else if (V == "ibmlongdouble")
1832 IEEELongDouble = false;
1833 else if (V != "altivec")
1834 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1835 // the option if given as we don't have backend support for any targets
1836 // that don't use the altivec abi.
David L. Jonesf561aba2017-03-08 01:02:16 +00001837 ABIName = A->getValue();
Fangrui Song6bd02a42019-07-15 07:25:11 +00001838 }
1839 if (IEEELongDouble)
1840 CmdArgs.push_back("-mabi=ieeelongdouble");
David L. Jonesf561aba2017-03-08 01:02:16 +00001841
1842 ppc::FloatABI FloatABI =
1843 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1844
1845 if (FloatABI == ppc::FloatABI::Soft) {
1846 // Floating point operations and argument passing are soft.
1847 CmdArgs.push_back("-msoft-float");
1848 CmdArgs.push_back("-mfloat-abi");
1849 CmdArgs.push_back("soft");
1850 } else {
1851 // Floating point operations and argument passing are hard.
1852 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1853 CmdArgs.push_back("-mfloat-abi");
1854 CmdArgs.push_back("hard");
1855 }
1856
1857 if (ABIName) {
1858 CmdArgs.push_back("-target-abi");
1859 CmdArgs.push_back(ABIName);
1860 }
1861}
1862
Alex Bradbury71f45452018-01-11 13:36:56 +00001863void Clang::AddRISCVTargetArgs(const ArgList &Args,
1864 ArgStringList &CmdArgs) const {
Alex Bradbury71f45452018-01-11 13:36:56 +00001865 const llvm::Triple &Triple = getToolChain().getTriple();
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001866 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
Alex Bradbury71f45452018-01-11 13:36:56 +00001867
1868 CmdArgs.push_back("-target-abi");
Roger Ferrer Ibanez371bdc92019-08-07 07:08:00 +00001869 CmdArgs.push_back(ABIName.data());
Alex Bradbury71f45452018-01-11 13:36:56 +00001870}
1871
David L. Jonesf561aba2017-03-08 01:02:16 +00001872void Clang::AddSparcTargetArgs(const ArgList &Args,
1873 ArgStringList &CmdArgs) const {
1874 sparc::FloatABI FloatABI =
1875 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1876
1877 if (FloatABI == sparc::FloatABI::Soft) {
1878 // Floating point operations and argument passing are soft.
1879 CmdArgs.push_back("-msoft-float");
1880 CmdArgs.push_back("-mfloat-abi");
1881 CmdArgs.push_back("soft");
1882 } else {
1883 // Floating point operations and argument passing are hard.
1884 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1885 CmdArgs.push_back("-mfloat-abi");
1886 CmdArgs.push_back("hard");
1887 }
1888}
1889
1890void Clang::AddSystemZTargetArgs(const ArgList &Args,
1891 ArgStringList &CmdArgs) const {
1892 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1893 CmdArgs.push_back("-mbackchain");
1894}
1895
1896void Clang::AddX86TargetArgs(const ArgList &Args,
1897 ArgStringList &CmdArgs) const {
1898 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1899 Args.hasArg(options::OPT_mkernel) ||
1900 Args.hasArg(options::OPT_fapple_kext))
1901 CmdArgs.push_back("-disable-red-zone");
1902
Kristina Brooks7f569b72018-10-18 14:07:02 +00001903 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1904 options::OPT_mno_tls_direct_seg_refs, true))
1905 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1906
David L. Jonesf561aba2017-03-08 01:02:16 +00001907 // Default to avoid implicit floating-point for kernel/kext code, but allow
1908 // that to be overridden with -mno-soft-float.
1909 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1910 Args.hasArg(options::OPT_fapple_kext));
1911 if (Arg *A = Args.getLastArg(
1912 options::OPT_msoft_float, options::OPT_mno_soft_float,
1913 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1914 const Option &O = A->getOption();
1915 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1916 O.matches(options::OPT_msoft_float));
1917 }
1918 if (NoImplicitFloat)
1919 CmdArgs.push_back("-no-implicit-float");
1920
1921 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1922 StringRef Value = A->getValue();
1923 if (Value == "intel" || Value == "att") {
1924 CmdArgs.push_back("-mllvm");
1925 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1926 } else {
1927 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1928 << A->getOption().getName() << Value;
1929 }
Nico Webere3712cf2018-01-17 13:34:20 +00001930 } else if (getToolChain().getDriver().IsCLMode()) {
1931 CmdArgs.push_back("-mllvm");
1932 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001933 }
1934
1935 // Set flags to support MCU ABI.
1936 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1937 CmdArgs.push_back("-mfloat-abi");
1938 CmdArgs.push_back("soft");
1939 CmdArgs.push_back("-mstack-alignment=4");
1940 }
1941}
1942
1943void Clang::AddHexagonTargetArgs(const ArgList &Args,
1944 ArgStringList &CmdArgs) const {
1945 CmdArgs.push_back("-mqdsp6-compat");
1946 CmdArgs.push_back("-Wreturn-type");
1947
1948 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001949 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001950 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1951 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001952 }
1953
1954 if (!Args.hasArg(options::OPT_fno_short_enums))
1955 CmdArgs.push_back("-fshort-enums");
1956 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1957 CmdArgs.push_back("-mllvm");
1958 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1959 }
1960 CmdArgs.push_back("-mllvm");
1961 CmdArgs.push_back("-machine-sink-split=0");
1962}
1963
1964void Clang::AddLanaiTargetArgs(const ArgList &Args,
1965 ArgStringList &CmdArgs) const {
1966 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1967 StringRef CPUName = A->getValue();
1968
1969 CmdArgs.push_back("-target-cpu");
1970 CmdArgs.push_back(Args.MakeArgString(CPUName));
1971 }
1972 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1973 StringRef Value = A->getValue();
1974 // Only support mregparm=4 to support old usage. Report error for all other
1975 // cases.
1976 int Mregparm;
1977 if (Value.getAsInteger(10, Mregparm)) {
1978 if (Mregparm != 4) {
1979 getToolChain().getDriver().Diag(
1980 diag::err_drv_unsupported_option_argument)
1981 << A->getOption().getName() << Value;
1982 }
1983 }
1984 }
1985}
1986
1987void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1988 ArgStringList &CmdArgs) const {
1989 // Default to "hidden" visibility.
1990 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1991 options::OPT_fvisibility_ms_compat)) {
1992 CmdArgs.push_back("-fvisibility");
1993 CmdArgs.push_back("hidden");
1994 }
1995}
1996
1997void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1998 StringRef Target, const InputInfo &Output,
1999 const InputInfo &Input, const ArgList &Args) const {
2000 // If this is a dry run, do not create the compilation database file.
2001 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2002 return;
2003
2004 using llvm::yaml::escape;
2005 const Driver &D = getToolChain().getDriver();
2006
2007 if (!CompilationDatabase) {
2008 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002009 auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +00002010 llvm::sys::fs::OF_Text);
David L. Jonesf561aba2017-03-08 01:02:16 +00002011 if (EC) {
2012 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2013 << EC.message();
2014 return;
2015 }
2016 CompilationDatabase = std::move(File);
2017 }
2018 auto &CDB = *CompilationDatabase;
Hans Wennborg999f8a72019-09-05 08:43:00 +00002019 SmallString<128> Buf;
2020 if (!llvm::sys::fs::current_path(Buf))
2021 Buf = ".";
2022 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
David L. Jonesf561aba2017-03-08 01:02:16 +00002023 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2024 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2025 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2026 Buf = "-x";
2027 Buf += types::getTypeName(Input.getType());
2028 CDB << ", \"" << escape(Buf) << "\"";
2029 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2030 Buf = "--sysroot=";
2031 Buf += D.SysRoot;
2032 CDB << ", \"" << escape(Buf) << "\"";
2033 }
2034 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2035 for (auto &A: Args) {
2036 auto &O = A->getOption();
2037 // Skip language selection, which is positional.
2038 if (O.getID() == options::OPT_x)
2039 continue;
2040 // Skip writing dependency output and the compilation database itself.
2041 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2042 continue;
Alex Lorenz8679ef42019-08-26 17:59:41 +00002043 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2044 continue;
David L. Jonesf561aba2017-03-08 01:02:16 +00002045 // Skip inputs.
2046 if (O.getKind() == Option::InputClass)
2047 continue;
2048 // All other arguments are quoted and appended.
2049 ArgStringList ASL;
2050 A->render(Args, ASL);
2051 for (auto &it: ASL)
2052 CDB << ", \"" << escape(it) << "\"";
2053 }
2054 Buf = "--target=";
2055 Buf += Target;
2056 CDB << ", \"" << escape(Buf) << "\"]},\n";
2057}
2058
Alex Lorenz8679ef42019-08-26 17:59:41 +00002059void Clang::DumpCompilationDatabaseFragmentToDir(
2060 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2061 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2062 // If this is a dry run, do not create the compilation database file.
2063 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2064 return;
2065
2066 if (CompilationDatabase)
2067 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2068
2069 SmallString<256> Path = Dir;
2070 const auto &Driver = C.getDriver();
2071 Driver.getVFS().makeAbsolute(Path);
2072 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2073 if (Err) {
2074 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2075 return;
2076 }
2077
2078 llvm::sys::path::append(
2079 Path,
2080 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2081 int FD;
2082 SmallString<256> TempPath;
2083 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
2084 if (Err) {
2085 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2086 return;
2087 }
2088 CompilationDatabase =
2089 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2090 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2091}
2092
David L. Jonesf561aba2017-03-08 01:02:16 +00002093static void CollectArgsForIntegratedAssembler(Compilation &C,
2094 const ArgList &Args,
2095 ArgStringList &CmdArgs,
2096 const Driver &D) {
2097 if (UseRelaxAll(C, Args))
2098 CmdArgs.push_back("-mrelax-all");
2099
2100 // Only default to -mincremental-linker-compatible if we think we are
2101 // targeting the MSVC linker.
2102 bool DefaultIncrementalLinkerCompatible =
2103 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2104 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2105 options::OPT_mno_incremental_linker_compatible,
2106 DefaultIncrementalLinkerCompatible))
2107 CmdArgs.push_back("-mincremental-linker-compatible");
2108
2109 switch (C.getDefaultToolChain().getArch()) {
2110 case llvm::Triple::arm:
2111 case llvm::Triple::armeb:
2112 case llvm::Triple::thumb:
2113 case llvm::Triple::thumbeb:
2114 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2115 StringRef Value = A->getValue();
2116 if (Value == "always" || Value == "never" || Value == "arm" ||
2117 Value == "thumb") {
2118 CmdArgs.push_back("-mllvm");
2119 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2120 } else {
2121 D.Diag(diag::err_drv_unsupported_option_argument)
2122 << A->getOption().getName() << Value;
2123 }
2124 }
2125 break;
2126 default:
2127 break;
2128 }
2129
Nico Weberb28ffd82019-07-27 01:13:00 +00002130 // If you add more args here, also add them to the block below that
2131 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2132
David L. Jonesf561aba2017-03-08 01:02:16 +00002133 // When passing -I arguments to the assembler we sometimes need to
2134 // unconditionally take the next argument. For example, when parsing
2135 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2136 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2137 // arg after parsing the '-I' arg.
2138 bool TakeNextArg = false;
2139
Petr Hosek5668d832017-11-22 01:38:31 +00002140 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002141 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002142 const char *MipsTargetFeature = nullptr;
2143 for (const Arg *A :
2144 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2145 A->claim();
2146
2147 for (StringRef Value : A->getValues()) {
2148 if (TakeNextArg) {
2149 CmdArgs.push_back(Value.data());
2150 TakeNextArg = false;
2151 continue;
2152 }
2153
2154 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2155 Value == "-mbig-obj")
2156 continue; // LLVM handles bigobj automatically
2157
2158 switch (C.getDefaultToolChain().getArch()) {
2159 default:
2160 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002161 case llvm::Triple::thumb:
2162 case llvm::Triple::thumbeb:
2163 case llvm::Triple::arm:
2164 case llvm::Triple::armeb:
2165 if (Value == "-mthumb")
2166 // -mthumb has already been processed in ComputeLLVMTriple()
2167 // recognize but skip over here.
2168 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002169 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002170 case llvm::Triple::mips:
2171 case llvm::Triple::mipsel:
2172 case llvm::Triple::mips64:
2173 case llvm::Triple::mips64el:
2174 if (Value == "--trap") {
2175 CmdArgs.push_back("-target-feature");
2176 CmdArgs.push_back("+use-tcc-in-div");
2177 continue;
2178 }
2179 if (Value == "--break") {
2180 CmdArgs.push_back("-target-feature");
2181 CmdArgs.push_back("-use-tcc-in-div");
2182 continue;
2183 }
2184 if (Value.startswith("-msoft-float")) {
2185 CmdArgs.push_back("-target-feature");
2186 CmdArgs.push_back("+soft-float");
2187 continue;
2188 }
2189 if (Value.startswith("-mhard-float")) {
2190 CmdArgs.push_back("-target-feature");
2191 CmdArgs.push_back("-soft-float");
2192 continue;
2193 }
2194
2195 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2196 .Case("-mips1", "+mips1")
2197 .Case("-mips2", "+mips2")
2198 .Case("-mips3", "+mips3")
2199 .Case("-mips4", "+mips4")
2200 .Case("-mips5", "+mips5")
2201 .Case("-mips32", "+mips32")
2202 .Case("-mips32r2", "+mips32r2")
2203 .Case("-mips32r3", "+mips32r3")
2204 .Case("-mips32r5", "+mips32r5")
2205 .Case("-mips32r6", "+mips32r6")
2206 .Case("-mips64", "+mips64")
2207 .Case("-mips64r2", "+mips64r2")
2208 .Case("-mips64r3", "+mips64r3")
2209 .Case("-mips64r5", "+mips64r5")
2210 .Case("-mips64r6", "+mips64r6")
2211 .Default(nullptr);
2212 if (MipsTargetFeature)
2213 continue;
2214 }
2215
2216 if (Value == "-force_cpusubtype_ALL") {
2217 // Do nothing, this is the default and we don't support anything else.
2218 } else if (Value == "-L") {
2219 CmdArgs.push_back("-msave-temp-labels");
2220 } else if (Value == "--fatal-warnings") {
2221 CmdArgs.push_back("-massembler-fatal-warnings");
Brian Cain7b953b62019-08-08 19:19:20 +00002222 } else if (Value == "--no-warn") {
2223 CmdArgs.push_back("-massembler-no-warn");
David L. Jonesf561aba2017-03-08 01:02:16 +00002224 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002225 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002226 } else if (Value.startswith("-compress-debug-sections") ||
2227 Value.startswith("--compress-debug-sections") ||
2228 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002229 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002230 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002231 } else if (Value == "-mrelax-relocations=yes" ||
2232 Value == "--mrelax-relocations=yes") {
2233 UseRelaxRelocations = true;
2234 } else if (Value == "-mrelax-relocations=no" ||
2235 Value == "--mrelax-relocations=no") {
2236 UseRelaxRelocations = false;
2237 } else if (Value.startswith("-I")) {
2238 CmdArgs.push_back(Value.data());
2239 // We need to consume the next argument if the current arg is a plain
2240 // -I. The next arg will be the include directory.
2241 if (Value == "-I")
2242 TakeNextArg = true;
2243 } else if (Value.startswith("-gdwarf-")) {
2244 // "-gdwarf-N" options are not cc1as options.
2245 unsigned DwarfVersion = DwarfVersionNum(Value);
2246 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2247 CmdArgs.push_back(Value.data());
2248 } else {
2249 RenderDebugEnablingArgs(Args, CmdArgs,
2250 codegenoptions::LimitedDebugInfo,
2251 DwarfVersion, llvm::DebuggerKind::Default);
2252 }
2253 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2254 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2255 // Do nothing, we'll validate it later.
2256 } else if (Value == "-defsym") {
2257 if (A->getNumValues() != 2) {
2258 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2259 break;
2260 }
2261 const char *S = A->getValue(1);
2262 auto Pair = StringRef(S).split('=');
2263 auto Sym = Pair.first;
2264 auto SVal = Pair.second;
2265
2266 if (Sym.empty() || SVal.empty()) {
2267 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2268 break;
2269 }
2270 int64_t IVal;
2271 if (SVal.getAsInteger(0, IVal)) {
2272 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2273 break;
2274 }
2275 CmdArgs.push_back(Value.data());
2276 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002277 } else if (Value == "-fdebug-compilation-dir") {
2278 CmdArgs.push_back("-fdebug-compilation-dir");
2279 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002280 } else {
2281 D.Diag(diag::err_drv_unsupported_option_argument)
2282 << A->getOption().getName() << Value;
2283 }
2284 }
2285 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002286 if (UseRelaxRelocations)
2287 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002288 if (UseNoExecStack)
2289 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002290 if (MipsTargetFeature != nullptr) {
2291 CmdArgs.push_back("-target-feature");
2292 CmdArgs.push_back(MipsTargetFeature);
2293 }
Steven Wu098742f2018-12-12 17:30:16 +00002294
2295 // forward -fembed-bitcode to assmebler
2296 if (C.getDriver().embedBitcodeEnabled() ||
2297 C.getDriver().embedBitcodeMarkerOnly())
2298 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002299}
2300
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002301static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2302 bool OFastEnabled, const ArgList &Args,
2303 ArgStringList &CmdArgs) {
2304 // Handle various floating point optimization flags, mapping them to the
2305 // appropriate LLVM code generation flags. This is complicated by several
2306 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002307 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002308 // LLVM flags based on the final state.
2309 bool HonorINFs = true;
2310 bool HonorNaNs = true;
2311 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2312 bool MathErrno = TC.IsMathErrnoDefault();
2313 bool AssociativeMath = false;
2314 bool ReciprocalMath = false;
2315 bool SignedZeros = true;
2316 bool TrappingMath = true;
2317 StringRef DenormalFPMath = "";
2318 StringRef FPContract = "";
2319
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002320 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2321 CmdArgs.push_back("-mlimit-float-precision");
2322 CmdArgs.push_back(A->getValue());
2323 }
2324
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002325 for (const Arg *A : Args) {
2326 switch (A->getOption().getID()) {
2327 // If this isn't an FP option skip the claim below
2328 default: continue;
2329
2330 // Options controlling individual features
2331 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2332 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2333 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2334 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2335 case options::OPT_fmath_errno: MathErrno = true; break;
2336 case options::OPT_fno_math_errno: MathErrno = false; break;
2337 case options::OPT_fassociative_math: AssociativeMath = true; break;
2338 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2339 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2340 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2341 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2342 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2343 case options::OPT_ftrapping_math: TrappingMath = true; break;
2344 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2345
2346 case options::OPT_fdenormal_fp_math_EQ:
2347 DenormalFPMath = A->getValue();
2348 break;
2349
2350 // Validate and pass through -fp-contract option.
2351 case options::OPT_ffp_contract: {
2352 StringRef Val = A->getValue();
2353 if (Val == "fast" || Val == "on" || Val == "off")
2354 FPContract = Val;
2355 else
2356 D.Diag(diag::err_drv_unsupported_option_argument)
2357 << A->getOption().getName() << Val;
2358 break;
2359 }
2360
2361 case options::OPT_ffinite_math_only:
2362 HonorINFs = false;
2363 HonorNaNs = false;
2364 break;
2365 case options::OPT_fno_finite_math_only:
2366 HonorINFs = true;
2367 HonorNaNs = true;
2368 break;
2369
2370 case options::OPT_funsafe_math_optimizations:
2371 AssociativeMath = true;
2372 ReciprocalMath = true;
2373 SignedZeros = false;
2374 TrappingMath = false;
2375 break;
2376 case options::OPT_fno_unsafe_math_optimizations:
2377 AssociativeMath = false;
2378 ReciprocalMath = false;
2379 SignedZeros = true;
2380 TrappingMath = true;
2381 // -fno_unsafe_math_optimizations restores default denormal handling
2382 DenormalFPMath = "";
2383 break;
2384
2385 case options::OPT_Ofast:
2386 // If -Ofast is the optimization level, then -ffast-math should be enabled
2387 if (!OFastEnabled)
2388 continue;
2389 LLVM_FALLTHROUGH;
2390 case options::OPT_ffast_math:
2391 HonorINFs = false;
2392 HonorNaNs = false;
2393 MathErrno = false;
2394 AssociativeMath = true;
2395 ReciprocalMath = true;
2396 SignedZeros = false;
2397 TrappingMath = false;
2398 // If fast-math is set then set the fp-contract mode to fast.
2399 FPContract = "fast";
2400 break;
2401 case options::OPT_fno_fast_math:
2402 HonorINFs = true;
2403 HonorNaNs = true;
2404 // Turning on -ffast-math (with either flag) removes the need for
2405 // MathErrno. However, turning *off* -ffast-math merely restores the
2406 // toolchain default (which may be false).
2407 MathErrno = TC.IsMathErrnoDefault();
2408 AssociativeMath = false;
2409 ReciprocalMath = false;
2410 SignedZeros = true;
2411 TrappingMath = true;
2412 // -fno_fast_math restores default denormal and fpcontract handling
2413 DenormalFPMath = "";
2414 FPContract = "";
2415 break;
2416 }
2417
2418 // If we handled this option claim it
2419 A->claim();
2420 }
2421
2422 if (!HonorINFs)
2423 CmdArgs.push_back("-menable-no-infs");
2424
2425 if (!HonorNaNs)
2426 CmdArgs.push_back("-menable-no-nans");
2427
2428 if (MathErrno)
2429 CmdArgs.push_back("-fmath-errno");
2430
2431 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2432 !TrappingMath)
2433 CmdArgs.push_back("-menable-unsafe-fp-math");
2434
2435 if (!SignedZeros)
2436 CmdArgs.push_back("-fno-signed-zeros");
2437
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002438 if (AssociativeMath && !SignedZeros && !TrappingMath)
2439 CmdArgs.push_back("-mreassociate");
2440
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002441 if (ReciprocalMath)
2442 CmdArgs.push_back("-freciprocal-math");
2443
2444 if (!TrappingMath)
2445 CmdArgs.push_back("-fno-trapping-math");
2446
2447 if (!DenormalFPMath.empty())
2448 CmdArgs.push_back(
2449 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2450
2451 if (!FPContract.empty())
2452 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2453
2454 ParseMRecip(D, Args, CmdArgs);
2455
2456 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2457 // individual features enabled by -ffast-math instead of the option itself as
2458 // that's consistent with gcc's behaviour.
2459 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2460 ReciprocalMath && !SignedZeros && !TrappingMath)
2461 CmdArgs.push_back("-ffast-math");
2462
2463 // Handle __FINITE_MATH_ONLY__ similarly.
2464 if (!HonorINFs && !HonorNaNs)
2465 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002466
2467 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2468 CmdArgs.push_back("-mfpmath");
2469 CmdArgs.push_back(A->getValue());
2470 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002471
2472 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002473 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2474 options::OPT_fstrict_float_cast_overflow, false))
2475 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002476}
2477
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002478static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2479 const llvm::Triple &Triple,
2480 const InputInfo &Input) {
2481 // Enable region store model by default.
2482 CmdArgs.push_back("-analyzer-store=region");
2483
2484 // Treat blocks as analysis entry points.
2485 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2486
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002487 // Add default argument set.
2488 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2489 CmdArgs.push_back("-analyzer-checker=core");
2490 CmdArgs.push_back("-analyzer-checker=apiModeling");
2491
2492 if (!Triple.isWindowsMSVCEnvironment()) {
2493 CmdArgs.push_back("-analyzer-checker=unix");
2494 } else {
2495 // Enable "unix" checkers that also work on Windows.
2496 CmdArgs.push_back("-analyzer-checker=unix.API");
2497 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2498 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2499 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2500 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2501 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2502 }
2503
2504 // Disable some unix checkers for PS4.
2505 if (Triple.isPS4CPU()) {
2506 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2507 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2508 }
2509
2510 if (Triple.isOSDarwin())
2511 CmdArgs.push_back("-analyzer-checker=osx");
2512
2513 CmdArgs.push_back("-analyzer-checker=deadcode");
2514
2515 if (types::isCXX(Input.getType()))
2516 CmdArgs.push_back("-analyzer-checker=cplusplus");
2517
2518 if (!Triple.isPS4CPU()) {
2519 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2520 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2521 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2522 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2523 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2524 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2525 }
2526
2527 // Default nullability checks.
2528 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2529 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2530 }
2531
2532 // Set the output format. The default is plist, for (lame) historical reasons.
2533 CmdArgs.push_back("-analyzer-output");
2534 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2535 CmdArgs.push_back(A->getValue());
2536 else
2537 CmdArgs.push_back("plist");
2538
2539 // Disable the presentation of standard compiler warnings when using
2540 // --analyze. We only want to show static analyzer diagnostics or frontend
2541 // errors.
2542 CmdArgs.push_back("-w");
2543
2544 // Add -Xanalyzer arguments when running as analyzer.
2545 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2546}
2547
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002548static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002549 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002550 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2551
2552 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2553 // doesn't even have a stack!
2554 if (EffectiveTriple.isNVPTX())
2555 return;
2556
2557 // -stack-protector=0 is default.
2558 unsigned StackProtectorLevel = 0;
2559 unsigned DefaultStackProtectorLevel =
2560 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2561
2562 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2563 options::OPT_fstack_protector_all,
2564 options::OPT_fstack_protector_strong,
2565 options::OPT_fstack_protector)) {
2566 if (A->getOption().matches(options::OPT_fstack_protector))
2567 StackProtectorLevel =
2568 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2569 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2570 StackProtectorLevel = LangOptions::SSPStrong;
2571 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2572 StackProtectorLevel = LangOptions::SSPReq;
2573 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002574 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002575 }
2576
2577 if (StackProtectorLevel) {
2578 CmdArgs.push_back("-stack-protector");
2579 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2580 }
2581
2582 // --param ssp-buffer-size=
2583 for (const Arg *A : Args.filtered(options::OPT__param)) {
2584 StringRef Str(A->getValue());
2585 if (Str.startswith("ssp-buffer-size=")) {
2586 if (StackProtectorLevel) {
2587 CmdArgs.push_back("-stack-protector-buffer-size");
2588 // FIXME: Verify the argument is a valid integer.
2589 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2590 }
2591 A->claim();
2592 }
2593 }
2594}
2595
JF Bastien14daa202018-12-18 05:12:21 +00002596static void RenderTrivialAutoVarInitOptions(const Driver &D,
2597 const ToolChain &TC,
2598 const ArgList &Args,
2599 ArgStringList &CmdArgs) {
2600 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2601 StringRef TrivialAutoVarInit = "";
2602
2603 for (const Arg *A : Args) {
2604 switch (A->getOption().getID()) {
2605 default:
2606 continue;
2607 case options::OPT_ftrivial_auto_var_init: {
2608 A->claim();
2609 StringRef Val = A->getValue();
2610 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2611 TrivialAutoVarInit = Val;
2612 else
2613 D.Diag(diag::err_drv_unsupported_option_argument)
2614 << A->getOption().getName() << Val;
2615 break;
2616 }
2617 }
2618 }
2619
2620 if (TrivialAutoVarInit.empty())
2621 switch (DefaultTrivialAutoVarInit) {
2622 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2623 break;
2624 case LangOptions::TrivialAutoVarInitKind::Pattern:
2625 TrivialAutoVarInit = "pattern";
2626 break;
2627 case LangOptions::TrivialAutoVarInitKind::Zero:
2628 TrivialAutoVarInit = "zero";
2629 break;
2630 }
2631
2632 if (!TrivialAutoVarInit.empty()) {
2633 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2634 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2635 CmdArgs.push_back(
2636 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2637 }
2638}
2639
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002640static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2641 const unsigned ForwardedArguments[] = {
2642 options::OPT_cl_opt_disable,
2643 options::OPT_cl_strict_aliasing,
2644 options::OPT_cl_single_precision_constant,
2645 options::OPT_cl_finite_math_only,
2646 options::OPT_cl_kernel_arg_info,
2647 options::OPT_cl_unsafe_math_optimizations,
2648 options::OPT_cl_fast_relaxed_math,
2649 options::OPT_cl_mad_enable,
2650 options::OPT_cl_no_signed_zeros,
2651 options::OPT_cl_denorms_are_zero,
2652 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002653 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002654 };
2655
2656 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2657 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2658 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2659 }
2660
2661 for (const auto &Arg : ForwardedArguments)
2662 if (const auto *A = Args.getLastArg(Arg))
2663 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2664}
2665
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002666static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2667 ArgStringList &CmdArgs) {
2668 bool ARCMTEnabled = false;
2669 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2670 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2671 options::OPT_ccc_arcmt_modify,
2672 options::OPT_ccc_arcmt_migrate)) {
2673 ARCMTEnabled = true;
2674 switch (A->getOption().getID()) {
2675 default: llvm_unreachable("missed a case");
2676 case options::OPT_ccc_arcmt_check:
2677 CmdArgs.push_back("-arcmt-check");
2678 break;
2679 case options::OPT_ccc_arcmt_modify:
2680 CmdArgs.push_back("-arcmt-modify");
2681 break;
2682 case options::OPT_ccc_arcmt_migrate:
2683 CmdArgs.push_back("-arcmt-migrate");
2684 CmdArgs.push_back("-mt-migrate-directory");
2685 CmdArgs.push_back(A->getValue());
2686
2687 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2688 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2689 break;
2690 }
2691 }
2692 } else {
2693 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2694 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2695 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2696 }
2697
2698 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2699 if (ARCMTEnabled)
2700 D.Diag(diag::err_drv_argument_not_allowed_with)
2701 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2702
2703 CmdArgs.push_back("-mt-migrate-directory");
2704 CmdArgs.push_back(A->getValue());
2705
2706 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2707 options::OPT_objcmt_migrate_subscripting,
2708 options::OPT_objcmt_migrate_property)) {
2709 // None specified, means enable them all.
2710 CmdArgs.push_back("-objcmt-migrate-literals");
2711 CmdArgs.push_back("-objcmt-migrate-subscripting");
2712 CmdArgs.push_back("-objcmt-migrate-property");
2713 } else {
2714 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2715 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2716 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2717 }
2718 } else {
2719 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2720 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2721 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2722 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2723 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2724 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2725 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2726 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2727 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2728 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2729 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2730 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2731 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2732 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2733 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2734 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2735 }
2736}
2737
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002738static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2739 const ArgList &Args, ArgStringList &CmdArgs) {
2740 // -fbuiltin is default unless -mkernel is used.
2741 bool UseBuiltins =
2742 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2743 !Args.hasArg(options::OPT_mkernel));
2744 if (!UseBuiltins)
2745 CmdArgs.push_back("-fno-builtin");
2746
2747 // -ffreestanding implies -fno-builtin.
2748 if (Args.hasArg(options::OPT_ffreestanding))
2749 UseBuiltins = false;
2750
2751 // Process the -fno-builtin-* options.
2752 for (const auto &Arg : Args) {
2753 const Option &O = Arg->getOption();
2754 if (!O.matches(options::OPT_fno_builtin_))
2755 continue;
2756
2757 Arg->claim();
2758
2759 // If -fno-builtin is specified, then there's no need to pass the option to
2760 // the frontend.
2761 if (!UseBuiltins)
2762 continue;
2763
2764 StringRef FuncName = Arg->getValue();
2765 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2766 }
2767
2768 // le32-specific flags:
2769 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2770 // by default.
2771 if (TC.getArch() == llvm::Triple::le32)
2772 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002773}
2774
Adrian Prantl70599032018-02-09 18:43:10 +00002775void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2776 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2777 llvm::sys::path::append(Result, "org.llvm.clang.");
2778 appendUserToPath(Result);
2779 llvm::sys::path::append(Result, "ModuleCache");
2780}
2781
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002782static void RenderModulesOptions(Compilation &C, const Driver &D,
2783 const ArgList &Args, const InputInfo &Input,
2784 const InputInfo &Output,
2785 ArgStringList &CmdArgs, bool &HaveModules) {
2786 // -fmodules enables the use of precompiled modules (off by default).
2787 // Users can pass -fno-cxx-modules to turn off modules support for
2788 // C++/Objective-C++ programs.
2789 bool HaveClangModules = false;
2790 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2791 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2792 options::OPT_fno_cxx_modules, true);
2793 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2794 CmdArgs.push_back("-fmodules");
2795 HaveClangModules = true;
2796 }
2797 }
2798
Richard Smithb1b580e2019-04-14 11:11:37 +00002799 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002800 if (Args.hasArg(options::OPT_fmodules_ts)) {
2801 CmdArgs.push_back("-fmodules-ts");
2802 HaveModules = true;
2803 }
2804
2805 // -fmodule-maps enables implicit reading of module map files. By default,
2806 // this is enabled if we are using Clang's flavor of precompiled modules.
2807 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2808 options::OPT_fno_implicit_module_maps, HaveClangModules))
2809 CmdArgs.push_back("-fimplicit-module-maps");
2810
2811 // -fmodules-decluse checks that modules used are declared so (off by default)
2812 if (Args.hasFlag(options::OPT_fmodules_decluse,
2813 options::OPT_fno_modules_decluse, false))
2814 CmdArgs.push_back("-fmodules-decluse");
2815
2816 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2817 // all #included headers are part of modules.
2818 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2819 options::OPT_fno_modules_strict_decluse, false))
2820 CmdArgs.push_back("-fmodules-strict-decluse");
2821
2822 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002823 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002824 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2825 options::OPT_fno_implicit_modules, HaveClangModules)) {
2826 if (HaveModules)
2827 CmdArgs.push_back("-fno-implicit-modules");
2828 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002829 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002830 // -fmodule-cache-path specifies where our implicitly-built module files
2831 // should be written.
2832 SmallString<128> Path;
2833 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2834 Path = A->getValue();
2835
2836 if (C.isForDiagnostics()) {
2837 // When generating crash reports, we want to emit the modules along with
2838 // the reproduction sources, so we ignore any provided module path.
2839 Path = Output.getFilename();
2840 llvm::sys::path::replace_extension(Path, ".cache");
2841 llvm::sys::path::append(Path, "modules");
2842 } else if (Path.empty()) {
2843 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002844 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002845 }
2846
2847 const char Arg[] = "-fmodules-cache-path=";
2848 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2849 CmdArgs.push_back(Args.MakeArgString(Path));
2850 }
2851
2852 if (HaveModules) {
2853 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2854 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2855 CmdArgs.push_back(Args.MakeArgString(
2856 std::string("-fprebuilt-module-path=") + A->getValue()));
2857 A->claim();
2858 }
2859 }
2860
2861 // -fmodule-name specifies the module that is currently being built (or
2862 // used for header checking by -fmodule-maps).
2863 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2864
2865 // -fmodule-map-file can be used to specify files containing module
2866 // definitions.
2867 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2868
2869 // -fbuiltin-module-map can be used to load the clang
2870 // builtin headers modulemap file.
2871 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2872 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2873 llvm::sys::path::append(BuiltinModuleMap, "include");
2874 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2875 if (llvm::sys::fs::exists(BuiltinModuleMap))
2876 CmdArgs.push_back(
2877 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2878 }
2879
2880 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2881 // names to precompiled module files (the module is loaded only if used).
2882 // The -fmodule-file=<file> form can be used to unconditionally load
2883 // precompiled module files (whether used or not).
2884 if (HaveModules)
2885 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2886 else
2887 Args.ClaimAllArgs(options::OPT_fmodule_file);
2888
2889 // When building modules and generating crashdumps, we need to dump a module
2890 // dependency VFS alongside the output.
2891 if (HaveClangModules && C.isForDiagnostics()) {
2892 SmallString<128> VFSDir(Output.getFilename());
2893 llvm::sys::path::replace_extension(VFSDir, ".cache");
2894 // Add the cache directory as a temp so the crash diagnostics pick it up.
2895 C.addTempFile(Args.MakeArgString(VFSDir));
2896
2897 llvm::sys::path::append(VFSDir, "vfs");
2898 CmdArgs.push_back("-module-dependency-dir");
2899 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2900 }
2901
2902 if (HaveClangModules)
2903 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2904
2905 // Pass through all -fmodules-ignore-macro arguments.
2906 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2907 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2908 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2909
2910 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2911
2912 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2913 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2914 D.Diag(diag::err_drv_argument_not_allowed_with)
2915 << A->getAsString(Args) << "-fbuild-session-timestamp";
2916
2917 llvm::sys::fs::file_status Status;
2918 if (llvm::sys::fs::status(A->getValue(), Status))
2919 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2920 CmdArgs.push_back(
2921 Args.MakeArgString("-fbuild-session-timestamp=" +
2922 Twine((uint64_t)Status.getLastModificationTime()
2923 .time_since_epoch()
2924 .count())));
2925 }
2926
2927 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2928 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2929 options::OPT_fbuild_session_file))
2930 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2931
2932 Args.AddLastArg(CmdArgs,
2933 options::OPT_fmodules_validate_once_per_build_session);
2934 }
2935
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002936 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2937 options::OPT_fno_modules_validate_system_headers,
2938 ImplicitModules))
2939 CmdArgs.push_back("-fmodules-validate-system-headers");
2940
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002941 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2942}
2943
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002944static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2945 ArgStringList &CmdArgs) {
2946 // -fsigned-char is default.
2947 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2948 options::OPT_fno_signed_char,
2949 options::OPT_funsigned_char,
2950 options::OPT_fno_unsigned_char)) {
2951 if (A->getOption().matches(options::OPT_funsigned_char) ||
2952 A->getOption().matches(options::OPT_fno_signed_char)) {
2953 CmdArgs.push_back("-fno-signed-char");
2954 }
2955 } else if (!isSignedCharDefault(T)) {
2956 CmdArgs.push_back("-fno-signed-char");
2957 }
2958
Richard Smith28ddb912018-11-14 21:04:34 +00002959 // The default depends on the language standard.
Nico Weber908b6972019-06-26 17:51:47 +00002960 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
Richard Smith3a8244d2018-05-01 05:02:45 +00002961
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002962 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2963 options::OPT_fno_short_wchar)) {
2964 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2965 CmdArgs.push_back("-fwchar-type=short");
2966 CmdArgs.push_back("-fno-signed-wchar");
2967 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002968 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002969 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002970 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2971 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002972 CmdArgs.push_back("-fno-signed-wchar");
2973 else
2974 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002975 }
2976 }
2977}
2978
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002979static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2980 const llvm::Triple &T, const ArgList &Args,
2981 ObjCRuntime &Runtime, bool InferCovariantReturns,
2982 const InputInfo &Input, ArgStringList &CmdArgs) {
2983 const llvm::Triple::ArchType Arch = TC.getArch();
2984
2985 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2986 // is the default. Except for deployment target of 10.5, next runtime is
2987 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2988 if (Runtime.isNonFragile()) {
2989 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2990 options::OPT_fno_objc_legacy_dispatch,
2991 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2992 if (TC.UseObjCMixedDispatch())
2993 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2994 else
2995 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2996 }
2997 }
2998
2999 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3000 // to do Array/Dictionary subscripting by default.
3001 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003002 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3003 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3004
3005 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3006 // NOTE: This logic is duplicated in ToolChains.cpp.
3007 if (isObjCAutoRefCount(Args)) {
3008 TC.CheckObjCARC();
3009
3010 CmdArgs.push_back("-fobjc-arc");
3011
3012 // FIXME: It seems like this entire block, and several around it should be
3013 // wrapped in isObjC, but for now we just use it here as this is where it
3014 // was being used previously.
3015 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3016 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3017 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3018 else
3019 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3020 }
3021
3022 // Allow the user to enable full exceptions code emission.
3023 // We default off for Objective-C, on for Objective-C++.
3024 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3025 options::OPT_fno_objc_arc_exceptions,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003026 /*Default=*/types::isCXX(Input.getType())))
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003027 CmdArgs.push_back("-fobjc-arc-exceptions");
3028 }
3029
3030 // Silence warning for full exception code emission options when explicitly
3031 // set to use no ARC.
3032 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3033 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3034 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3035 }
3036
Pete Coopere3886802018-12-08 05:13:50 +00003037 // Allow the user to control whether messages can be converted to runtime
3038 // functions.
3039 if (types::isObjC(Input.getType())) {
3040 auto *Arg = Args.getLastArg(
3041 options::OPT_fobjc_convert_messages_to_runtime_calls,
3042 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3043 if (Arg &&
3044 Arg->getOption().matches(
3045 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3046 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3047 }
3048
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00003049 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3050 // rewriter.
3051 if (InferCovariantReturns)
3052 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3053
3054 // Pass down -fobjc-weak or -fno-objc-weak if present.
3055 if (types::isObjC(Input.getType())) {
3056 auto WeakArg =
3057 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3058 if (!WeakArg) {
3059 // nothing to do
3060 } else if (!Runtime.allowsWeak()) {
3061 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3062 D.Diag(diag::err_objc_weak_unsupported);
3063 } else {
3064 WeakArg->render(Args, CmdArgs);
3065 }
3066 }
3067}
3068
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003069static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3070 ArgStringList &CmdArgs) {
3071 bool CaretDefault = true;
3072 bool ColumnDefault = true;
3073
3074 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3075 options::OPT__SLASH_diagnostics_column,
3076 options::OPT__SLASH_diagnostics_caret)) {
3077 switch (A->getOption().getID()) {
3078 case options::OPT__SLASH_diagnostics_caret:
3079 CaretDefault = true;
3080 ColumnDefault = true;
3081 break;
3082 case options::OPT__SLASH_diagnostics_column:
3083 CaretDefault = false;
3084 ColumnDefault = true;
3085 break;
3086 case options::OPT__SLASH_diagnostics_classic:
3087 CaretDefault = false;
3088 ColumnDefault = false;
3089 break;
3090 }
3091 }
3092
3093 // -fcaret-diagnostics is default.
3094 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3095 options::OPT_fno_caret_diagnostics, CaretDefault))
3096 CmdArgs.push_back("-fno-caret-diagnostics");
3097
3098 // -fdiagnostics-fixit-info is default, only pass non-default.
3099 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3100 options::OPT_fno_diagnostics_fixit_info))
3101 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3102
3103 // Enable -fdiagnostics-show-option by default.
3104 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3105 options::OPT_fno_diagnostics_show_option))
3106 CmdArgs.push_back("-fdiagnostics-show-option");
3107
3108 if (const Arg *A =
3109 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3110 CmdArgs.push_back("-fdiagnostics-show-category");
3111 CmdArgs.push_back(A->getValue());
3112 }
3113
3114 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3115 options::OPT_fno_diagnostics_show_hotness, false))
3116 CmdArgs.push_back("-fdiagnostics-show-hotness");
3117
3118 if (const Arg *A =
3119 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3120 std::string Opt =
3121 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3122 CmdArgs.push_back(Args.MakeArgString(Opt));
3123 }
3124
3125 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3126 CmdArgs.push_back("-fdiagnostics-format");
3127 CmdArgs.push_back(A->getValue());
3128 }
3129
3130 if (const Arg *A = Args.getLastArg(
3131 options::OPT_fdiagnostics_show_note_include_stack,
3132 options::OPT_fno_diagnostics_show_note_include_stack)) {
3133 const Option &O = A->getOption();
3134 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3135 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3136 else
3137 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3138 }
3139
3140 // Color diagnostics are parsed by the driver directly from argv and later
3141 // re-parsed to construct this job; claim any possible color diagnostic here
3142 // to avoid warn_drv_unused_argument and diagnose bad
3143 // OPT_fdiagnostics_color_EQ values.
3144 for (const Arg *A : Args) {
3145 const Option &O = A->getOption();
3146 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3147 !O.matches(options::OPT_fdiagnostics_color) &&
3148 !O.matches(options::OPT_fno_color_diagnostics) &&
3149 !O.matches(options::OPT_fno_diagnostics_color) &&
3150 !O.matches(options::OPT_fdiagnostics_color_EQ))
3151 continue;
3152
3153 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3154 StringRef Value(A->getValue());
3155 if (Value != "always" && Value != "never" && Value != "auto")
3156 D.Diag(diag::err_drv_clang_unsupported)
3157 << ("-fdiagnostics-color=" + Value).str();
3158 }
3159 A->claim();
3160 }
3161
3162 if (D.getDiags().getDiagnosticOptions().ShowColors)
3163 CmdArgs.push_back("-fcolor-diagnostics");
3164
3165 if (Args.hasArg(options::OPT_fansi_escape_codes))
3166 CmdArgs.push_back("-fansi-escape-codes");
3167
3168 if (!Args.hasFlag(options::OPT_fshow_source_location,
3169 options::OPT_fno_show_source_location))
3170 CmdArgs.push_back("-fno-show-source-location");
3171
3172 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3173 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3174
3175 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3176 ColumnDefault))
3177 CmdArgs.push_back("-fno-show-column");
3178
3179 if (!Args.hasFlag(options::OPT_fspell_checking,
3180 options::OPT_fno_spell_checking))
3181 CmdArgs.push_back("-fno-spell-checking");
3182}
3183
George Rimar91829ee2018-11-14 09:22:16 +00003184enum class DwarfFissionKind { None, Split, Single };
3185
3186static DwarfFissionKind getDebugFissionKind(const Driver &D,
3187 const ArgList &Args, Arg *&Arg) {
3188 Arg =
3189 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3190 if (!Arg)
3191 return DwarfFissionKind::None;
3192
3193 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3194 return DwarfFissionKind::Split;
3195
3196 StringRef Value = Arg->getValue();
3197 if (Value == "split")
3198 return DwarfFissionKind::Split;
3199 if (Value == "single")
3200 return DwarfFissionKind::Single;
3201
3202 D.Diag(diag::err_drv_unsupported_option_argument)
3203 << Arg->getOption().getName() << Arg->getValue();
3204 return DwarfFissionKind::None;
3205}
3206
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003207static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3208 const llvm::Triple &T, const ArgList &Args,
3209 bool EmitCodeView, bool IsWindowsMSVC,
3210 ArgStringList &CmdArgs,
3211 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003212 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003213 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003214 options::OPT_fno_debug_info_for_profiling, false) &&
3215 checkDebugInfoOption(
3216 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003217 CmdArgs.push_back("-fdebug-info-for-profiling");
3218
3219 // The 'g' groups options involve a somewhat intricate sequence of decisions
3220 // about what to pass from the driver to the frontend, but by the time they
3221 // reach cc1 they've been factored into three well-defined orthogonal choices:
3222 // * what level of debug info to generate
3223 // * what dwarf version to write
3224 // * what debugger tuning to use
3225 // This avoids having to monkey around further in cc1 other than to disable
3226 // codeview if not running in a Windows environment. Perhaps even that
3227 // decision should be made in the driver as well though.
3228 unsigned DWARFVersion = 0;
3229 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3230
3231 bool SplitDWARFInlining =
3232 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3233 options::OPT_fno_split_dwarf_inlining, true);
3234
3235 Args.ClaimAllArgs(options::OPT_g_Group);
3236
George Rimar91829ee2018-11-14 09:22:16 +00003237 Arg* SplitDWARFArg;
3238 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003239
George Rimar91829ee2018-11-14 09:22:16 +00003240 if (DwarfFission != DwarfFissionKind::None &&
3241 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3242 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003243 SplitDWARFInlining = false;
3244 }
3245
Fangrui Songe3576b02019-04-17 01:46:27 +00003246 if (const Arg *A =
3247 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3248 options::OPT_gsplit_dwarf_EQ)) {
3249 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3250
3251 // If the last option explicitly specified a debug-info level, use it.
3252 if (checkDebugInfoOption(A, Args, D, TC) &&
3253 A->getOption().matches(options::OPT_gN_Group)) {
3254 DebugInfoKind = DebugLevelToInfoKind(*A);
3255 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3256 // complicated if you've disabled inline info in the skeleton CUs
3257 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3258 // line-tables-only, so let those compose naturally in that case.
3259 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3260 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3261 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3262 SplitDWARFInlining))
3263 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003264 }
3265 }
3266
3267 // If a debugger tuning argument appeared, remember it.
3268 if (const Arg *A =
3269 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003270 if (checkDebugInfoOption(A, Args, D, TC)) {
3271 if (A->getOption().matches(options::OPT_glldb))
3272 DebuggerTuning = llvm::DebuggerKind::LLDB;
3273 else if (A->getOption().matches(options::OPT_gsce))
3274 DebuggerTuning = llvm::DebuggerKind::SCE;
3275 else
3276 DebuggerTuning = llvm::DebuggerKind::GDB;
3277 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003278 }
3279
3280 // If a -gdwarf argument appeared, remember it.
3281 if (const Arg *A =
3282 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3283 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003284 if (checkDebugInfoOption(A, Args, D, TC))
3285 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003286
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003287 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3288 if (checkDebugInfoOption(A, Args, D, TC))
3289 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003290 }
3291
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003292 // If the user asked for debug info but did not explicitly specify -gcodeview
3293 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003294 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003295 DebugInfoKind != codegenoptions::NoDebugInfo) {
3296 switch (TC.getDefaultDebugFormat()) {
3297 case codegenoptions::DIF_CodeView:
3298 EmitCodeView = true;
3299 break;
3300 case codegenoptions::DIF_DWARF:
3301 DWARFVersion = TC.GetDefaultDwarfVersion();
3302 break;
3303 }
3304 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003305
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003306 // -gline-directives-only supported only for the DWARF debug info.
3307 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3308 DebugInfoKind = codegenoptions::NoDebugInfo;
3309
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003310 // We ignore flag -gstrict-dwarf for now.
3311 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3312 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3313
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003314 // Column info is included by default for everything except SCE and
3315 // CodeView. Clang doesn't track end columns, just starting columns, which,
3316 // in theory, is fine for CodeView (and PDB). In practice, however, the
3317 // Microsoft debuggers don't handle missing end columns well, so it's better
3318 // not to include any column info.
3319 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3320 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003321 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003322 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003323 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003324 CmdArgs.push_back("-dwarf-column-info");
3325
3326 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003327 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003328 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3329 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003330 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3331 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003332 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3333 CmdArgs.push_back("-dwarf-ext-refs");
3334 CmdArgs.push_back("-fmodule-format=obj");
3335 }
3336 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003337
Aaron Puchertb207bae2019-06-26 21:36:35 +00003338 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3339 CmdArgs.push_back("-fno-split-dwarf-inlining");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003340
3341 // After we've dealt with all combinations of things that could
3342 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3343 // figure out if we need to "upgrade" it to standalone debug info.
3344 // We parse these two '-f' options whether or not they will be used,
3345 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003346 bool NeedFullDebug = Args.hasFlag(
3347 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3348 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3349 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003350 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3351 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003352 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3353 DebugInfoKind = codegenoptions::FullDebugInfo;
3354
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003355 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3356 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003357 // Source embedding is a vendor extension to DWARF v5. By now we have
3358 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003359 // fallen back to the target default, so if this is still not at least 5
3360 // we emit an error.
3361 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003362 if (DWARFVersion < 5)
3363 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003364 << A->getAsString(Args) << "-gdwarf-5";
3365 else if (checkDebugInfoOption(A, Args, D, TC))
3366 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003367 }
3368
Reid Kleckner75557712018-11-16 18:47:41 +00003369 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003370 CmdArgs.push_back("-gcodeview");
3371
Reid Kleckner75557712018-11-16 18:47:41 +00003372 // Emit codeview type hashes if requested.
3373 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3374 options::OPT_gno_codeview_ghash, false)) {
3375 CmdArgs.push_back("-gcodeview-ghash");
3376 }
3377 }
3378
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003379 // Adjust the debug info kind for the given toolchain.
3380 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3381
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003382 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3383 DebuggerTuning);
3384
3385 // -fdebug-macro turns on macro debug info generation.
3386 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3387 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003388 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3389 D, TC))
3390 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003391
3392 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003393 const auto *PubnamesArg =
3394 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3395 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003396 if (DwarfFission != DwarfFissionKind::None ||
David Blaikie65864522018-08-20 20:14:08 +00003397 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3398 if (!PubnamesArg ||
3399 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3400 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3401 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3402 options::OPT_gpubnames)
3403 ? "-gpubnames"
3404 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003405
David Blaikie27692de2018-11-13 20:08:13 +00003406 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3407 options::OPT_fno_debug_ranges_base_address, false)) {
3408 CmdArgs.push_back("-fdebug-ranges-base-address");
3409 }
3410
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003411 // -gdwarf-aranges turns on the emission of the aranges section in the
3412 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003413 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003414 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3415 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3416 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3417 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003418 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003419 CmdArgs.push_back("-generate-arange-section");
3420 }
3421
3422 if (Args.hasFlag(options::OPT_fdebug_types_section,
3423 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003424 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003425 D.Diag(diag::err_drv_unsupported_opt_for_target)
3426 << Args.getLastArg(options::OPT_fdebug_types_section)
3427 ->getAsString(Args)
3428 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003429 } else if (checkDebugInfoOption(
3430 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3431 TC)) {
3432 CmdArgs.push_back("-mllvm");
3433 CmdArgs.push_back("-generate-type-units");
3434 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003435 }
3436
Paul Robinson1787f812017-09-28 18:37:02 +00003437 // Decide how to render forward declarations of template instantiations.
3438 // SCE wants full descriptions, others just get them in the name.
3439 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3440 CmdArgs.push_back("-debug-forward-template-params");
3441
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003442 // Do we need to explicitly import anonymous namespaces into the parent
3443 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003444 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3445 CmdArgs.push_back("-dwarf-explicit-import");
3446
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003447 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003448}
3449
David L. Jonesf561aba2017-03-08 01:02:16 +00003450void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3451 const InputInfo &Output, const InputInfoList &Inputs,
3452 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003453 const auto &TC = getToolChain();
3454 const llvm::Triple &RawTriple = TC.getTriple();
3455 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003456 const std::string &TripleStr = Triple.getTriple();
3457
3458 bool KernelOrKext =
3459 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003460 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003461 ArgStringList CmdArgs;
3462
3463 // Check number of inputs for sanity. We need at least one input.
3464 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003465 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003466 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003467 // second input. Module precompilation accepts a list of header files to
3468 // include as part of the module. All other jobs are expected to have exactly
3469 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003470 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003471 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003472 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003473 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3474
3475 // A header module compilation doesn't have a main input file, so invent a
3476 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003477 const char *ModuleName = [&]{
3478 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3479 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3480 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003481 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003482
3483 const InputInfo &Input =
3484 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3485
3486 InputInfoList ModuleHeaderInputs;
3487 const InputInfo *CudaDeviceInput = nullptr;
3488 const InputInfo *OpenMPDeviceInput = nullptr;
3489 for (const InputInfo &I : Inputs) {
3490 if (&I == &Input) {
3491 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003492 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003493 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003494 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003495 if (I.getType() != Expected) {
3496 D.Diag(diag::err_drv_module_header_wrong_kind)
3497 << I.getFilename() << types::getTypeName(I.getType())
3498 << types::getTypeName(Expected);
3499 }
3500 ModuleHeaderInputs.push_back(I);
3501 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3502 CudaDeviceInput = &I;
3503 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3504 OpenMPDeviceInput = &I;
3505 } else {
3506 llvm_unreachable("unexpectedly given multiple inputs");
3507 }
3508 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003509
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003510 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003511 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003512 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003513
Yaxun Liu398612b2018-05-08 21:02:12 +00003514 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3515 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3516 // Windows), we need to pass Windows-specific flags to cc1.
Fangrui Songe6e09562019-07-12 13:21:58 +00003517 if (IsCuda || IsHIP)
David L. Jonesf561aba2017-03-08 01:02:16 +00003518 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003519
3520 // C++ is not supported for IAMCU.
3521 if (IsIAMCU && types::isCXX(Input.getType()))
3522 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3523
3524 // Invoke ourselves in -cc1 mode.
3525 //
3526 // FIXME: Implement custom jobs for internal actions.
3527 CmdArgs.push_back("-cc1");
3528
3529 // Add the "effective" target triple.
3530 CmdArgs.push_back("-triple");
3531 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3532
3533 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3534 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3535 Args.ClaimAllArgs(options::OPT_MJ);
Alex Lorenz8679ef42019-08-26 17:59:41 +00003536 } else if (const Arg *GenCDBFragment =
3537 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
3538 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
3539 TripleStr, Output, Input, Args);
3540 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
David L. Jonesf561aba2017-03-08 01:02:16 +00003541 }
3542
Yaxun Liu398612b2018-05-08 21:02:12 +00003543 if (IsCuda || IsHIP) {
3544 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3545 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003546 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003547 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3548 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003549 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3550 ->getTriple()
3551 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003552 else {
3553 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003554 NormalizedTriple =
3555 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3556 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3557 ->getTriple()
3558 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003559 if (IsCuda) {
3560 // We need to figure out which CUDA version we're compiling for, as that
3561 // determines how we load and launch GPU kernels.
3562 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3563 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3564 assert(CTC && "Expected valid CUDA Toolchain.");
3565 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3566 CmdArgs.push_back(Args.MakeArgString(
3567 Twine("-target-sdk-version=") +
3568 CudaVersionToString(CTC->CudaInstallation.version())));
3569 }
3570 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003571 CmdArgs.push_back("-aux-triple");
3572 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3573 }
3574
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003575 if (IsOpenMPDevice) {
3576 // We have to pass the triple of the host if compiling for an OpenMP device.
3577 std::string NormalizedTriple =
3578 C.getSingleOffloadToolChain<Action::OFK_Host>()
3579 ->getTriple()
3580 .normalize();
3581 CmdArgs.push_back("-aux-triple");
3582 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3583 }
3584
David L. Jonesf561aba2017-03-08 01:02:16 +00003585 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3586 Triple.getArch() == llvm::Triple::thumb)) {
3587 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3588 unsigned Version;
3589 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3590 if (Version < 7)
3591 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3592 << TripleStr;
3593 }
3594
3595 // Push all default warning arguments that are specific to
3596 // the given target. These come before user provided warning options
3597 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003598 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003599
3600 // Select the appropriate action.
3601 RewriteKind rewriteKind = RK_None;
3602
Nico Weberb28ffd82019-07-27 01:13:00 +00003603 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
3604 // it claims when not running an assembler. Otherwise, clang would emit
3605 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
3606 // flags while debugging something. That'd be somewhat inconvenient, and it's
3607 // also inconsistent with most other flags -- we don't warn on
3608 // -ffunction-sections not being used in -E mode either for example, even
3609 // though it's not really used either.
3610 if (!isa<AssembleJobAction>(JA)) {
3611 // The args claimed here should match the args used in
3612 // CollectArgsForIntegratedAssembler().
3613 if (TC.useIntegratedAs()) {
3614 Args.ClaimAllArgs(options::OPT_mrelax_all);
3615 Args.ClaimAllArgs(options::OPT_mno_relax_all);
3616 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
3617 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
3618 switch (C.getDefaultToolChain().getArch()) {
3619 case llvm::Triple::arm:
3620 case llvm::Triple::armeb:
3621 case llvm::Triple::thumb:
3622 case llvm::Triple::thumbeb:
3623 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
Bjorn Pettersson60c1ee22019-07-27 17:09:08 +00003624 break;
Nico Weberb28ffd82019-07-27 01:13:00 +00003625 default:
3626 break;
3627 }
3628 }
3629 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
3630 Args.ClaimAllArgs(options::OPT_Xassembler);
3631 }
3632
David L. Jonesf561aba2017-03-08 01:02:16 +00003633 if (isa<AnalyzeJobAction>(JA)) {
3634 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3635 CmdArgs.push_back("-analyze");
3636 } else if (isa<MigrateJobAction>(JA)) {
3637 CmdArgs.push_back("-migrate");
3638 } else if (isa<PreprocessJobAction>(JA)) {
3639 if (Output.getType() == types::TY_Dependencies)
3640 CmdArgs.push_back("-Eonly");
3641 else {
3642 CmdArgs.push_back("-E");
3643 if (Args.hasArg(options::OPT_rewrite_objc) &&
3644 !Args.hasArg(options::OPT_g_Group))
3645 CmdArgs.push_back("-P");
3646 }
3647 } else if (isa<AssembleJobAction>(JA)) {
3648 CmdArgs.push_back("-emit-obj");
3649
3650 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3651
3652 // Also ignore explicit -force_cpusubtype_ALL option.
3653 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3654 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003655 if (JA.getType() == types::TY_Nothing)
3656 CmdArgs.push_back("-fsyntax-only");
3657 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003658 CmdArgs.push_back(IsHeaderModulePrecompile
3659 ? "-emit-header-module"
3660 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003661 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003662 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003663 } else if (isa<VerifyPCHJobAction>(JA)) {
3664 CmdArgs.push_back("-verify-pch");
3665 } else {
3666 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3667 "Invalid action for clang tool.");
3668 if (JA.getType() == types::TY_Nothing) {
3669 CmdArgs.push_back("-fsyntax-only");
3670 } else if (JA.getType() == types::TY_LLVM_IR ||
3671 JA.getType() == types::TY_LTO_IR) {
3672 CmdArgs.push_back("-emit-llvm");
3673 } else if (JA.getType() == types::TY_LLVM_BC ||
3674 JA.getType() == types::TY_LTO_BC) {
3675 CmdArgs.push_back("-emit-llvm-bc");
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003676 } else if (JA.getType() == types::TY_IFS) {
Puyan Lotfi926f4f72019-08-22 23:44:34 +00003677 StringRef ArgStr =
3678 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3679 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
3680 : "";
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003681 StringRef StubFormat =
Puyan Lotfi926f4f72019-08-22 23:44:34 +00003682 llvm::StringSwitch<StringRef>(ArgStr)
Puyan Lotfid2418452019-08-22 23:29:22 +00003683 .Case("experimental-ifs-v1", "experimental-ifs-v1")
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003684 .Default("");
3685
Puyan Lotfi926f4f72019-08-22 23:44:34 +00003686 if (StubFormat.empty()) {
3687 std::string ErrorMessage =
3688 "Invalid interface stub format: " + ArgStr.str() +
3689 ((ArgStr == "experimental-yaml-elf-v1" ||
3690 ArgStr == "experimental-tapi-elf-v1")
3691 ? " is deprecated."
3692 : ".");
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003693 D.Diag(diag::err_drv_invalid_value)
Puyan Lotfi926f4f72019-08-22 23:44:34 +00003694 << "Must specify a valid interface stub format type, ie: "
3695 "-interface-stub-version=experimental-ifs-v1"
3696 << ErrorMessage;
3697 }
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003698
3699 CmdArgs.push_back("-emit-interface-stubs");
3700 CmdArgs.push_back(
3701 Args.MakeArgString(Twine("-interface-stub-version=") + StubFormat));
David L. Jonesf561aba2017-03-08 01:02:16 +00003702 } else if (JA.getType() == types::TY_PP_Asm) {
3703 CmdArgs.push_back("-S");
3704 } else if (JA.getType() == types::TY_AST) {
3705 CmdArgs.push_back("-emit-pch");
3706 } else if (JA.getType() == types::TY_ModuleFile) {
3707 CmdArgs.push_back("-module-file-info");
3708 } else if (JA.getType() == types::TY_RewrittenObjC) {
3709 CmdArgs.push_back("-rewrite-objc");
3710 rewriteKind = RK_NonFragile;
3711 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3712 CmdArgs.push_back("-rewrite-objc");
3713 rewriteKind = RK_Fragile;
3714 } else {
3715 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3716 }
3717
3718 // Preserve use-list order by default when emitting bitcode, so that
3719 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3720 // same result as running passes here. For LTO, we don't need to preserve
3721 // the use-list order, since serialization to bitcode is part of the flow.
3722 if (JA.getType() == types::TY_LLVM_BC)
3723 CmdArgs.push_back("-emit-llvm-uselists");
3724
Artem Belevichecb178b2018-03-21 22:22:59 +00003725 // Device-side jobs do not support LTO.
3726 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3727 JA.isDeviceOffloading(Action::OFK_Host));
3728
3729 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003730 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3731
Paul Robinsond23f2a82017-07-13 21:25:47 +00003732 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3733 // does not support LTO unit features (CFI, whole program vtable opt)
3734 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003735 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003736 D.getLTOMode() == LTOK_Full)
3737 CmdArgs.push_back("-flto-unit");
3738 }
3739 }
3740
3741 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3742 if (!types::isLLVMIR(Input.getType()))
Bob Haarman79434642019-07-15 20:51:44 +00003743 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003744 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3745 }
3746
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003747 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003748 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3749
David L. Jonesf561aba2017-03-08 01:02:16 +00003750 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003751 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003752 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3753 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3754 // Add flags implied by -fembed-bitcode.
3755 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3756 // Disable all llvm IR level optimizations.
3757 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003758
Fangrui Song2632ebb2019-05-30 02:30:04 +00003759 // Render target options such as -fuse-init-array on modern ELF platforms.
3760 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3761
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003762 // reject options that shouldn't be supported in bitcode
3763 // also reject kernel/kext
3764 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3765 options::OPT_mkernel,
3766 options::OPT_fapple_kext,
3767 options::OPT_ffunction_sections,
3768 options::OPT_fno_function_sections,
3769 options::OPT_fdata_sections,
3770 options::OPT_fno_data_sections,
3771 options::OPT_funique_section_names,
3772 options::OPT_fno_unique_section_names,
3773 options::OPT_mrestrict_it,
3774 options::OPT_mno_restrict_it,
3775 options::OPT_mstackrealign,
3776 options::OPT_mno_stackrealign,
3777 options::OPT_mstack_alignment,
3778 options::OPT_mcmodel_EQ,
3779 options::OPT_mlong_calls,
3780 options::OPT_mno_long_calls,
3781 options::OPT_ggnu_pubnames,
3782 options::OPT_gdwarf_aranges,
3783 options::OPT_fdebug_types_section,
3784 options::OPT_fno_debug_types_section,
3785 options::OPT_fdwarf_directory_asm,
3786 options::OPT_fno_dwarf_directory_asm,
3787 options::OPT_mrelax_all,
3788 options::OPT_mno_relax_all,
3789 options::OPT_ftrap_function_EQ,
3790 options::OPT_ffixed_r9,
3791 options::OPT_mfix_cortex_a53_835769,
3792 options::OPT_mno_fix_cortex_a53_835769,
3793 options::OPT_ffixed_x18,
3794 options::OPT_mglobal_merge,
3795 options::OPT_mno_global_merge,
3796 options::OPT_mred_zone,
3797 options::OPT_mno_red_zone,
3798 options::OPT_Wa_COMMA,
3799 options::OPT_Xassembler,
3800 options::OPT_mllvm,
3801 };
3802 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003803 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003804 std::end(kBitcodeOptionBlacklist))
3805 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3806
3807 // Render the CodeGen options that need to be passed.
3808 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3809 options::OPT_fno_optimize_sibling_calls))
3810 CmdArgs.push_back("-mdisable-tail-calls");
3811
3812 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3813 CmdArgs);
3814
3815 // Render ABI arguments
3816 switch (TC.getArch()) {
3817 default: break;
3818 case llvm::Triple::arm:
3819 case llvm::Triple::armeb:
3820 case llvm::Triple::thumbeb:
3821 RenderARMABI(Triple, Args, CmdArgs);
3822 break;
3823 case llvm::Triple::aarch64:
3824 case llvm::Triple::aarch64_be:
3825 RenderAArch64ABI(Triple, Args, CmdArgs);
3826 break;
3827 }
3828
3829 // Optimization level for CodeGen.
3830 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3831 if (A->getOption().matches(options::OPT_O4)) {
3832 CmdArgs.push_back("-O3");
3833 D.Diag(diag::warn_O4_is_O3);
3834 } else {
3835 A->render(Args, CmdArgs);
3836 }
3837 }
3838
3839 // Input/Output file.
3840 if (Output.getType() == types::TY_Dependencies) {
3841 // Handled with other dependency code.
3842 } else if (Output.isFilename()) {
3843 CmdArgs.push_back("-o");
3844 CmdArgs.push_back(Output.getFilename());
3845 } else {
3846 assert(Output.isNothing() && "Input output.");
3847 }
3848
3849 for (const auto &II : Inputs) {
3850 addDashXForInput(Args, II, CmdArgs);
3851 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003852 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003853 else
3854 II.getInputArg().renderAsInput(Args, CmdArgs);
3855 }
3856
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00003857 C.addCommand(std::make_unique<Command>(JA, *this, D.getClangProgramPath(),
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003858 CmdArgs, Inputs));
3859 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003860 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003861
David L. Jonesf561aba2017-03-08 01:02:16 +00003862 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3863 CmdArgs.push_back("-fembed-bitcode=marker");
3864
3865 // We normally speed up the clang process a bit by skipping destructors at
3866 // exit, but when we're generating diagnostics we can rely on some of the
3867 // cleanup.
3868 if (!C.isForDiagnostics())
3869 CmdArgs.push_back("-disable-free");
3870
David L. Jonesf561aba2017-03-08 01:02:16 +00003871#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003872 const bool IsAssertBuild = false;
3873#else
3874 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003875#endif
3876
Eric Fiselier123c7492018-02-07 18:36:51 +00003877 // Disable the verification pass in -asserts builds.
3878 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003879 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003880
3881 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003882 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3883 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003884 CmdArgs.push_back("-discard-value-names");
3885
David L. Jonesf561aba2017-03-08 01:02:16 +00003886 // Set the main file name, so that debug info works even with
3887 // -save-temps.
3888 CmdArgs.push_back("-main-file-name");
3889 CmdArgs.push_back(getBaseInputName(Args, Input));
3890
3891 // Some flags which affect the language (via preprocessor
3892 // defines).
3893 if (Args.hasArg(options::OPT_static))
3894 CmdArgs.push_back("-static-define");
3895
Martin Storsjo434ef832018-08-06 19:48:44 +00003896 if (Args.hasArg(options::OPT_municode))
3897 CmdArgs.push_back("-DUNICODE");
3898
Jan Korousb26e9e22019-09-24 03:21:22 +00003899 if (isa<AnalyzeJobAction>(JA))
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003900 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003901
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003902 // Enable compatilibily mode to avoid analyzer-config related errors.
3903 // Since we can't access frontend flags through hasArg, let's manually iterate
3904 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003905 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003906 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003907 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3908 FoundAnalyzerConfig = true;
3909 break;
3910 }
3911 if (!FoundAnalyzerConfig)
3912 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3913 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3914 FoundAnalyzerConfig = true;
3915 break;
3916 }
3917 if (FoundAnalyzerConfig)
3918 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003919
David L. Jonesf561aba2017-03-08 01:02:16 +00003920 CheckCodeGenerationOptions(D, Args);
3921
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003922 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003923 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3924 if (FunctionAlignment) {
3925 CmdArgs.push_back("-function-alignment");
3926 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3927 }
3928
David L. Jonesf561aba2017-03-08 01:02:16 +00003929 llvm::Reloc::Model RelocationModel;
3930 unsigned PICLevel;
3931 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003932 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003933
3934 const char *RMName = RelocationModelName(RelocationModel);
3935
3936 if ((RelocationModel == llvm::Reloc::ROPI ||
3937 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3938 types::isCXX(Input.getType()) &&
3939 !Args.hasArg(options::OPT_fallow_unsupported))
3940 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3941
3942 if (RMName) {
3943 CmdArgs.push_back("-mrelocation-model");
3944 CmdArgs.push_back(RMName);
3945 }
3946 if (PICLevel > 0) {
3947 CmdArgs.push_back("-pic-level");
3948 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3949 if (IsPIE)
3950 CmdArgs.push_back("-pic-is-pie");
3951 }
3952
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003953 if (RelocationModel == llvm::Reloc::ROPI ||
3954 RelocationModel == llvm::Reloc::ROPI_RWPI)
3955 CmdArgs.push_back("-fropi");
3956 if (RelocationModel == llvm::Reloc::RWPI ||
3957 RelocationModel == llvm::Reloc::ROPI_RWPI)
3958 CmdArgs.push_back("-frwpi");
3959
David L. Jonesf561aba2017-03-08 01:02:16 +00003960 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3961 CmdArgs.push_back("-meabi");
3962 CmdArgs.push_back(A->getValue());
3963 }
3964
3965 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003966 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003967 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003968 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3969 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003970 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003971 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003972 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003973 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003974
3975 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3976
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003977 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3978 options::OPT_fno_merge_all_constants, false))
3979 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003980
Manoj Guptada08f6a2018-07-19 00:44:52 +00003981 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3982 options::OPT_fdelete_null_pointer_checks, false))
3983 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3984
David L. Jonesf561aba2017-03-08 01:02:16 +00003985 // LLVM Code Generator Options.
3986
3987 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3988 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3989 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3990 options::OPT_frewrite_map_file_EQ)) {
3991 StringRef Map = A->getValue();
3992 if (!llvm::sys::fs::exists(Map)) {
3993 D.Diag(diag::err_drv_no_such_file) << Map;
3994 } else {
3995 CmdArgs.push_back("-frewrite-map-file");
3996 CmdArgs.push_back(A->getValue());
3997 A->claim();
3998 }
3999 }
4000 }
4001
4002 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4003 StringRef v = A->getValue();
4004 CmdArgs.push_back("-mllvm");
4005 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4006 A->claim();
4007 }
4008
4009 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4010 true))
4011 CmdArgs.push_back("-fno-jump-tables");
4012
Dehao Chen5e97f232017-08-24 21:37:33 +00004013 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4014 options::OPT_fno_profile_sample_accurate, false))
4015 CmdArgs.push_back("-fprofile-sample-accurate");
4016
David L. Jonesf561aba2017-03-08 01:02:16 +00004017 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4018 options::OPT_fno_preserve_as_comments, true))
4019 CmdArgs.push_back("-fno-preserve-as-comments");
4020
4021 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4022 CmdArgs.push_back("-mregparm");
4023 CmdArgs.push_back(A->getValue());
4024 }
4025
4026 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4027 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004028 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004029 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004030 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00004031 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4032 CmdArgs.push_back("-fpcc-struct-return");
4033 } else {
4034 assert(A->getOption().matches(options::OPT_freg_struct_return));
4035 CmdArgs.push_back("-freg-struct-return");
4036 }
4037 }
4038
4039 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4040 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4041
Yuanfang Chenff22ec32019-07-20 22:50:50 +00004042 CodeGenOptions::FramePointerKind FPKeepKind =
4043 getFramePointerKind(Args, RawTriple);
4044 const char *FPKeepKindStr = nullptr;
4045 switch (FPKeepKind) {
4046 case CodeGenOptions::FramePointerKind::None:
4047 FPKeepKindStr = "-mframe-pointer=none";
4048 break;
4049 case CodeGenOptions::FramePointerKind::NonLeaf:
4050 FPKeepKindStr = "-mframe-pointer=non-leaf";
4051 break;
4052 case CodeGenOptions::FramePointerKind::All:
4053 FPKeepKindStr = "-mframe-pointer=all";
4054 break;
Fangrui Songdc039662019-07-12 02:01:51 +00004055 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +00004056 assert(FPKeepKindStr && "unknown FramePointerKind");
4057 CmdArgs.push_back(FPKeepKindStr);
4058
David L. Jonesf561aba2017-03-08 01:02:16 +00004059 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4060 options::OPT_fno_zero_initialized_in_bss))
4061 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4062
4063 bool OFastEnabled = isOptimizationLevelFast(Args);
4064 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4065 // enabled. This alias option is being used to simplify the hasFlag logic.
4066 OptSpecifier StrictAliasingAliasOption =
4067 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4068 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4069 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004070 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004071 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4072 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4073 CmdArgs.push_back("-relaxed-aliasing");
4074 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4075 options::OPT_fno_struct_path_tbaa))
4076 CmdArgs.push_back("-no-struct-path-tbaa");
4077 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4078 false))
4079 CmdArgs.push_back("-fstrict-enums");
4080 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4081 true))
4082 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00004083 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4084 options::OPT_fno_allow_editor_placeholders, false))
4085 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00004086 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4087 options::OPT_fno_strict_vtable_pointers,
4088 false))
4089 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00004090 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4091 options::OPT_fno_force_emit_vtables,
4092 false))
4093 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00004094 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4095 options::OPT_fno_optimize_sibling_calls))
4096 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00004097 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00004098 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00004099 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00004100
Wei Mi9b3d6272017-10-16 16:50:27 +00004101 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4102 options::OPT_fno_fine_grained_bitfield_accesses);
4103
David L. Jonesf561aba2017-03-08 01:02:16 +00004104 // Handle segmented stacks.
4105 if (Args.hasArg(options::OPT_fsplit_stack))
4106 CmdArgs.push_back("-split-stacks");
4107
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004108 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004109
Troy A. Johnsonc0d70bc2019-08-17 04:20:24 +00004110 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
Fangrui Song11cb39c2019-07-09 00:27:43 +00004111 if (TC.getArch() == llvm::Triple::x86 ||
Troy A. Johnsonc0d70bc2019-08-17 04:20:24 +00004112 TC.getArch() == llvm::Triple::x86_64)
4113 A->render(Args, CmdArgs);
4114 else if ((TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64()) &&
4115 (A->getOption().getID() != options::OPT_mlong_double_80))
Fangrui Songc46d78d2019-07-12 02:32:15 +00004116 A->render(Args, CmdArgs);
4117 else
Fangrui Song11cb39c2019-07-09 00:27:43 +00004118 D.Diag(diag::err_drv_unsupported_opt_for_target)
4119 << A->getAsString(Args) << TripleStr;
Fangrui Song11cb39c2019-07-09 00:27:43 +00004120 }
4121
David L. Jonesf561aba2017-03-08 01:02:16 +00004122 // Decide whether to use verbose asm. Verbose assembly is the default on
4123 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004124 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004125 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
Erich Keanee30b71f2019-08-26 17:00:13 +00004126 IsIntegratedAssemblerDefault))
David L. Jonesf561aba2017-03-08 01:02:16 +00004127 CmdArgs.push_back("-masm-verbose");
4128
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004129 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004130 CmdArgs.push_back("-no-integrated-as");
4131
4132 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4133 CmdArgs.push_back("-mdebug-pass");
4134 CmdArgs.push_back("Structure");
4135 }
4136 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4137 CmdArgs.push_back("-mdebug-pass");
4138 CmdArgs.push_back("Arguments");
4139 }
4140
4141 // Enable -mconstructor-aliases except on darwin, where we have to work around
4142 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4143 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004144 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004145 CmdArgs.push_back("-mconstructor-aliases");
4146
4147 // Darwin's kernel doesn't support guard variables; just die if we
4148 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004149 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004150 CmdArgs.push_back("-fforbid-guard-variables");
4151
4152 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4153 false)) {
4154 CmdArgs.push_back("-mms-bitfields");
4155 }
4156
4157 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4158 options::OPT_mno_pie_copy_relocations,
4159 false)) {
4160 CmdArgs.push_back("-mpie-copy-relocations");
4161 }
4162
Sriraman Tallam5c651482017-11-07 19:37:51 +00004163 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4164 CmdArgs.push_back("-fno-plt");
4165 }
4166
Vedant Kumardf502592017-09-12 22:51:53 +00004167 // -fhosted is default.
4168 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4169 // use Freestanding.
4170 bool Freestanding =
4171 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4172 KernelOrKext;
4173 if (Freestanding)
4174 CmdArgs.push_back("-ffreestanding");
4175
David L. Jonesf561aba2017-03-08 01:02:16 +00004176 // This is a coarse approximation of what llvm-gcc actually does, both
4177 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4178 // complicated ways.
4179 bool AsynchronousUnwindTables =
4180 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4181 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004182 (TC.IsUnwindTablesDefault(Args) ||
4183 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004184 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004185 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4186 AsynchronousUnwindTables))
4187 CmdArgs.push_back("-munwind-tables");
4188
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004189 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004190
David L. Jonesf561aba2017-03-08 01:02:16 +00004191 // FIXME: Handle -mtune=.
4192 (void)Args.hasArg(options::OPT_mtune_EQ);
4193
4194 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4195 CmdArgs.push_back("-mcode-model");
4196 CmdArgs.push_back(A->getValue());
4197 }
4198
4199 // Add the target cpu
4200 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4201 if (!CPU.empty()) {
4202 CmdArgs.push_back("-target-cpu");
4203 CmdArgs.push_back(Args.MakeArgString(CPU));
4204 }
4205
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004206 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004207
David L. Jonesf561aba2017-03-08 01:02:16 +00004208 // These two are potentially updated by AddClangCLArgs.
4209 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4210 bool EmitCodeView = false;
4211
4212 // Add clang-cl arguments.
4213 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004214 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004215 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4216
George Rimar91829ee2018-11-14 09:22:16 +00004217 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004218 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004219 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004220
4221 // Add the split debug info name to the command lines here so we
4222 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004223 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004224 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004225 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4226 isa<BackendJobAction>(JA));
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004227 if (SplitDWARF) {
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004228 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4229 CmdArgs.push_back("-split-dwarf-file");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004230 CmdArgs.push_back(SplitDWARFOut);
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004231 if (DwarfFission == DwarfFissionKind::Split) {
4232 CmdArgs.push_back("-split-dwarf-output");
4233 CmdArgs.push_back(SplitDWARFOut);
4234 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004235 }
4236
David L. Jonesf561aba2017-03-08 01:02:16 +00004237 // Pass the linker version in use.
4238 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4239 CmdArgs.push_back("-target-linker-version");
4240 CmdArgs.push_back(A->getValue());
4241 }
4242
David L. Jonesf561aba2017-03-08 01:02:16 +00004243 // Explicitly error on some things we know we don't support and can't just
4244 // ignore.
4245 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4246 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004247 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004248 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004249 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4250 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4251 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4252 << Unsupported->getOption().getName();
4253 }
Eric Christopher758aad72017-03-21 22:06:18 +00004254 // The faltivec option has been superseded by the maltivec option.
4255 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4256 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4257 << Unsupported->getOption().getName()
4258 << "please use -maltivec and include altivec.h explicitly";
4259 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4260 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4261 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004262 }
4263
4264 Args.AddAllArgs(CmdArgs, options::OPT_v);
4265 Args.AddLastArg(CmdArgs, options::OPT_H);
4266 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4267 CmdArgs.push_back("-header-include-file");
4268 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4269 : "-");
4270 }
4271 Args.AddLastArg(CmdArgs, options::OPT_P);
4272 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4273
4274 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4275 CmdArgs.push_back("-diagnostic-log-file");
4276 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4277 : "-");
4278 }
4279
David L. Jonesf561aba2017-03-08 01:02:16 +00004280 bool UseSeparateSections = isUseSeparateSections(Triple);
4281
4282 if (Args.hasFlag(options::OPT_ffunction_sections,
4283 options::OPT_fno_function_sections, UseSeparateSections)) {
4284 CmdArgs.push_back("-ffunction-sections");
4285 }
4286
4287 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4288 UseSeparateSections)) {
4289 CmdArgs.push_back("-fdata-sections");
4290 }
4291
4292 if (!Args.hasFlag(options::OPT_funique_section_names,
4293 options::OPT_fno_unique_section_names, true))
4294 CmdArgs.push_back("-fno-unique-section-names");
4295
Nico Weber908b6972019-06-26 17:51:47 +00004296 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4297 options::OPT_finstrument_functions_after_inlining,
4298 options::OPT_finstrument_function_entry_bare);
David L. Jonesf561aba2017-03-08 01:02:16 +00004299
Artem Belevichc30bcad2018-01-24 17:41:02 +00004300 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4301 // sampling, overhead of call arc collection is way too high and there's no
4302 // way to collect the output.
4303 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004304 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004305
Nico Weber908b6972019-06-26 17:51:47 +00004306 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
Richard Smithf667ad52017-08-26 01:04:35 +00004307
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004308 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004309 if (RawTriple.isPS4CPU() &&
4310 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004311 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4312 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004313 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004314
4315 // Pass options for controlling the default header search paths.
4316 if (Args.hasArg(options::OPT_nostdinc)) {
4317 CmdArgs.push_back("-nostdsysteminc");
4318 CmdArgs.push_back("-nobuiltininc");
4319 } else {
4320 if (Args.hasArg(options::OPT_nostdlibinc))
4321 CmdArgs.push_back("-nostdsysteminc");
4322 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4323 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4324 }
4325
4326 // Pass the path to compiler resource files.
4327 CmdArgs.push_back("-resource-dir");
4328 CmdArgs.push_back(D.ResourceDir.c_str());
4329
4330 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4331
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004332 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004333
4334 // Add preprocessing options like -I, -D, etc. if we are using the
4335 // preprocessor.
4336 //
4337 // FIXME: Support -fpreprocessed
4338 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4339 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4340
4341 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4342 // that "The compiler can only warn and ignore the option if not recognized".
4343 // When building with ccache, it will pass -D options to clang even on
4344 // preprocessed inputs and configure concludes that -fPIC is not supported.
4345 Args.ClaimAllArgs(options::OPT_D);
4346
4347 // Manually translate -O4 to -O3; let clang reject others.
4348 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4349 if (A->getOption().matches(options::OPT_O4)) {
4350 CmdArgs.push_back("-O3");
4351 D.Diag(diag::warn_O4_is_O3);
4352 } else {
4353 A->render(Args, CmdArgs);
4354 }
4355 }
4356
4357 // Warn about ignored options to clang.
4358 for (const Arg *A :
4359 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4360 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4361 A->claim();
4362 }
4363
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004364 for (const Arg *A :
4365 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4366 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4367 A->claim();
4368 }
4369
David L. Jonesf561aba2017-03-08 01:02:16 +00004370 claimNoWarnArgs(Args);
4371
4372 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4373
4374 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4375 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4376 CmdArgs.push_back("-pedantic");
4377 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4378 Args.AddLastArg(CmdArgs, options::OPT_w);
4379
Leonard Chanf921d852018-06-04 16:07:52 +00004380 // Fixed point flags
4381 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4382 /*Default=*/false))
4383 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4384
David L. Jonesf561aba2017-03-08 01:02:16 +00004385 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4386 // (-ansi is equivalent to -std=c89 or -std=c++98).
4387 //
4388 // If a std is supplied, only add -trigraphs if it follows the
4389 // option.
4390 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004391 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4392 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004393 if (Std->getOption().matches(options::OPT_ansi))
4394 if (types::isCXX(InputType))
4395 CmdArgs.push_back("-std=c++98");
4396 else
4397 CmdArgs.push_back("-std=c89");
4398 else
4399 Std->render(Args, CmdArgs);
4400
4401 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4402 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4403 options::OPT_ftrigraphs,
4404 options::OPT_fno_trigraphs))
4405 if (A != Std)
4406 A->render(Args, CmdArgs);
4407 } else {
4408 // Honor -std-default.
4409 //
4410 // FIXME: Clang doesn't correctly handle -std= when the input language
4411 // doesn't match. For the time being just ignore this for C++ inputs;
4412 // eventually we want to do all the standard defaulting here instead of
4413 // splitting it between the driver and clang -cc1.
4414 if (!types::isCXX(InputType))
4415 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4416 /*Joined=*/true);
4417 else if (IsWindowsMSVC)
4418 ImplyVCPPCXXVer = true;
4419
4420 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4421 options::OPT_fno_trigraphs);
4422 }
4423
4424 // GCC's behavior for -Wwrite-strings is a bit strange:
4425 // * In C, this "warning flag" changes the types of string literals from
4426 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4427 // for the discarded qualifier.
4428 // * In C++, this is just a normal warning flag.
4429 //
4430 // Implementing this warning correctly in C is hard, so we follow GCC's
4431 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4432 // a non-const char* in C, rather than using this crude hack.
4433 if (!types::isCXX(InputType)) {
4434 // FIXME: This should behave just like a warning flag, and thus should also
4435 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4436 Arg *WriteStrings =
4437 Args.getLastArg(options::OPT_Wwrite_strings,
4438 options::OPT_Wno_write_strings, options::OPT_w);
4439 if (WriteStrings &&
4440 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4441 CmdArgs.push_back("-fconst-strings");
4442 }
4443
4444 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4445 // during C++ compilation, which it is by default. GCC keeps this define even
4446 // in the presence of '-w', match this behavior bug-for-bug.
4447 if (types::isCXX(InputType) &&
4448 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4449 true)) {
4450 CmdArgs.push_back("-fdeprecated-macro");
4451 }
4452
4453 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4454 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4455 if (Asm->getOption().matches(options::OPT_fasm))
4456 CmdArgs.push_back("-fgnu-keywords");
4457 else
4458 CmdArgs.push_back("-fno-gnu-keywords");
4459 }
4460
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004461 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004462 CmdArgs.push_back("-fno-dwarf-directory-asm");
4463
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004464 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004465 CmdArgs.push_back("-fno-autolink");
4466
4467 // Add in -fdebug-compilation-dir if necessary.
Hans Wennborg999f8a72019-09-05 08:43:00 +00004468 addDebugCompDirArg(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004469
Paul Robinson9b292b42018-07-10 15:15:24 +00004470 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004471
4472 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4473 options::OPT_ftemplate_depth_EQ)) {
4474 CmdArgs.push_back("-ftemplate-depth");
4475 CmdArgs.push_back(A->getValue());
4476 }
4477
4478 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4479 CmdArgs.push_back("-foperator-arrow-depth");
4480 CmdArgs.push_back(A->getValue());
4481 }
4482
4483 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4484 CmdArgs.push_back("-fconstexpr-depth");
4485 CmdArgs.push_back(A->getValue());
4486 }
4487
4488 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4489 CmdArgs.push_back("-fconstexpr-steps");
4490 CmdArgs.push_back(A->getValue());
4491 }
4492
Nandor Licker950b70d2019-09-13 09:46:16 +00004493 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
4494 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
4495
4496 if (Args.hasArg(options::OPT_fforce_experimental_new_constant_interpreter))
4497 CmdArgs.push_back("-fforce-experimental-new-constant-interpreter");
4498
David L. Jonesf561aba2017-03-08 01:02:16 +00004499 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4500 CmdArgs.push_back("-fbracket-depth");
4501 CmdArgs.push_back(A->getValue());
4502 }
4503
4504 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4505 options::OPT_Wlarge_by_value_copy_def)) {
4506 if (A->getNumValues()) {
4507 StringRef bytes = A->getValue();
4508 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4509 } else
4510 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4511 }
4512
4513 if (Args.hasArg(options::OPT_relocatable_pch))
4514 CmdArgs.push_back("-relocatable-pch");
4515
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004516 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4517 static const char *kCFABIs[] = {
4518 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4519 };
4520
4521 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4522 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4523 else
4524 A->render(Args, CmdArgs);
4525 }
4526
David L. Jonesf561aba2017-03-08 01:02:16 +00004527 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4528 CmdArgs.push_back("-fconstant-string-class");
4529 CmdArgs.push_back(A->getValue());
4530 }
4531
4532 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4533 CmdArgs.push_back("-ftabstop");
4534 CmdArgs.push_back(A->getValue());
4535 }
4536
Sean Eveson5110d4f2018-01-08 13:42:26 +00004537 if (Args.hasFlag(options::OPT_fstack_size_section,
4538 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4539 CmdArgs.push_back("-fstack-size-section");
4540
David L. Jonesf561aba2017-03-08 01:02:16 +00004541 CmdArgs.push_back("-ferror-limit");
4542 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4543 CmdArgs.push_back(A->getValue());
4544 else
4545 CmdArgs.push_back("19");
4546
4547 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4548 CmdArgs.push_back("-fmacro-backtrace-limit");
4549 CmdArgs.push_back(A->getValue());
4550 }
4551
4552 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4553 CmdArgs.push_back("-ftemplate-backtrace-limit");
4554 CmdArgs.push_back(A->getValue());
4555 }
4556
4557 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4558 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4559 CmdArgs.push_back(A->getValue());
4560 }
4561
4562 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4563 CmdArgs.push_back("-fspell-checking-limit");
4564 CmdArgs.push_back(A->getValue());
4565 }
4566
4567 // Pass -fmessage-length=.
4568 CmdArgs.push_back("-fmessage-length");
4569 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4570 CmdArgs.push_back(A->getValue());
4571 } else {
4572 // If -fmessage-length=N was not specified, determine whether this is a
4573 // terminal and, if so, implicitly define -fmessage-length appropriately.
4574 unsigned N = llvm::sys::Process::StandardErrColumns();
4575 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4576 }
4577
4578 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4579 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4580 options::OPT_fvisibility_ms_compat)) {
4581 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4582 CmdArgs.push_back("-fvisibility");
4583 CmdArgs.push_back(A->getValue());
4584 } else {
4585 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4586 CmdArgs.push_back("-fvisibility");
4587 CmdArgs.push_back("hidden");
4588 CmdArgs.push_back("-ftype-visibility");
4589 CmdArgs.push_back("default");
4590 }
4591 }
4592
4593 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004594 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004595
4596 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4597
David L. Jonesf561aba2017-03-08 01:02:16 +00004598 // Forward -f (flag) options which we can pass directly.
4599 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4600 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004601 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004602 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004603 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4604 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004605 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004606
David L. Jonesf561aba2017-03-08 01:02:16 +00004607 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004608 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004609 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004610
David L. Jonesf561aba2017-03-08 01:02:16 +00004611 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4612 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4613
4614 // Forward flags for OpenMP. We don't do this if the current action is an
4615 // device offloading action other than OpenMP.
4616 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4617 options::OPT_fno_openmp, false) &&
4618 (JA.isDeviceOffloading(Action::OFK_None) ||
4619 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004620 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004621 case Driver::OMPRT_OMP:
4622 case Driver::OMPRT_IOMP5:
4623 // Clang can generate useful OpenMP code for these two runtime libraries.
4624 CmdArgs.push_back("-fopenmp");
4625
4626 // If no option regarding the use of TLS in OpenMP codegeneration is
4627 // given, decide a default based on the target. Otherwise rely on the
4628 // options and pass the right information to the frontend.
4629 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4630 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4631 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004632 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4633 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004634 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004635 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4636 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004637 Args.AddAllArgs(CmdArgs,
4638 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004639 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4640 options::OPT_fno_openmp_optimistic_collapse,
4641 /*Default=*/false))
4642 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004643
4644 // When in OpenMP offloading mode with NVPTX target, forward
4645 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004646 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4647 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4648 CmdArgs.push_back("-fopenmp-cuda-mode");
4649
4650 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4651 // is required.
4652 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4653 options::OPT_fno_openmp_cuda_force_full_runtime,
4654 /*Default=*/false))
4655 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004656 break;
4657 default:
4658 // By default, if Clang doesn't know how to generate useful OpenMP code
4659 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4660 // down to the actual compilation.
4661 // FIXME: It would be better to have a mode which *only* omits IR
4662 // generation based on the OpenMP support so that we get consistent
4663 // semantic analysis, etc.
4664 break;
4665 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004666 } else {
4667 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4668 options::OPT_fno_openmp_simd);
4669 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004670 }
4671
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004672 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4673 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004674
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004675 const XRayArgs &XRay = TC.getXRayArgs();
4676 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004677
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004678 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004679 Args.AddLastArg(CmdArgs, options::OPT_pg);
4680
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004681 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004682 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4683
David L. Jonesf561aba2017-03-08 01:02:16 +00004684 if (Args.getLastArg(options::OPT_fapple_kext) ||
4685 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4686 CmdArgs.push_back("-fapple-kext");
4687
Richard Smithc6245102019-09-13 06:02:15 +00004688 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004689 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4690 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4691 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4692 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004693 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00004694 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004695 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004696 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004697
4698 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4699 CmdArgs.push_back("-ftrapv-handler");
4700 CmdArgs.push_back(A->getValue());
4701 }
4702
4703 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4704
4705 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4706 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4707 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4708 if (A->getOption().matches(options::OPT_fwrapv))
4709 CmdArgs.push_back("-fwrapv");
4710 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4711 options::OPT_fno_strict_overflow)) {
4712 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4713 CmdArgs.push_back("-fwrapv");
4714 }
4715
4716 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4717 options::OPT_fno_reroll_loops))
4718 if (A->getOption().matches(options::OPT_freroll_loops))
4719 CmdArgs.push_back("-freroll-loops");
4720
4721 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4722 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4723 options::OPT_fno_unroll_loops);
4724
4725 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4726
Zola Bridgesc8666792018-11-26 18:13:31 +00004727 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4728 false))
4729 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004730
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004731 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004732 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004733
4734 // Translate -mstackrealign
4735 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4736 false))
4737 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4738
4739 if (Args.hasArg(options::OPT_mstack_alignment)) {
4740 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4741 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4742 }
4743
4744 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4745 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4746
4747 if (!Size.empty())
4748 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4749 else
4750 CmdArgs.push_back("-mstack-probe-size=0");
4751 }
4752
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004753 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4754 options::OPT_mno_stack_arg_probe, true))
4755 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4756
David L. Jonesf561aba2017-03-08 01:02:16 +00004757 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4758 options::OPT_mno_restrict_it)) {
4759 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004760 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004761 CmdArgs.push_back("-arm-restrict-it");
4762 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004763 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004764 CmdArgs.push_back("-arm-no-restrict-it");
4765 }
4766 } else if (Triple.isOSWindows() &&
4767 (Triple.getArch() == llvm::Triple::arm ||
4768 Triple.getArch() == llvm::Triple::thumb)) {
4769 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004770 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004771 CmdArgs.push_back("-arm-restrict-it");
4772 }
4773
4774 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004775 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004776
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004777 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4778 CmdArgs.push_back(
4779 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4780 }
4781
David L. Jonesf561aba2017-03-08 01:02:16 +00004782 // Forward -f options with positive and negative forms; we translate
4783 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004784 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004785 auto *PGOArg = Args.getLastArg(
4786 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4787 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4788 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4789 if (PGOArg)
4790 D.Diag(diag::err_drv_argument_not_allowed_with)
4791 << "SampleUse with PGO options";
4792
David L. Jonesf561aba2017-03-08 01:02:16 +00004793 StringRef fname = A->getValue();
4794 if (!llvm::sys::fs::exists(fname))
4795 D.Diag(diag::err_drv_no_such_file) << fname;
4796 else
4797 A->render(Args, CmdArgs);
4798 }
Richard Smith8654ae52018-10-10 23:13:35 +00004799 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004800
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004801 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004802
4803 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4804 options::OPT_fno_assume_sane_operator_new))
4805 CmdArgs.push_back("-fno-assume-sane-operator-new");
4806
4807 // -fblocks=0 is default.
4808 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004809 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004810 (Args.hasArg(options::OPT_fgnu_runtime) &&
4811 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4812 !Args.hasArg(options::OPT_fno_blocks))) {
4813 CmdArgs.push_back("-fblocks");
4814
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004815 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004816 CmdArgs.push_back("-fblocks-runtime-optional");
4817 }
4818
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004819 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004820 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004821 CmdArgs.push_back("-fencode-extended-block-signature");
4822
David L. Jonesf561aba2017-03-08 01:02:16 +00004823 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4824 false) &&
4825 types::isCXX(InputType)) {
4826 CmdArgs.push_back("-fcoroutines-ts");
4827 }
4828
Aaron Ballman61736552017-10-21 20:28:58 +00004829 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4830 options::OPT_fno_double_square_bracket_attributes);
4831
David L. Jonesf561aba2017-03-08 01:02:16 +00004832 // -faccess-control is default.
4833 if (Args.hasFlag(options::OPT_fno_access_control,
4834 options::OPT_faccess_control, false))
4835 CmdArgs.push_back("-fno-access-control");
4836
4837 // -felide-constructors is the default.
4838 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4839 options::OPT_felide_constructors, false))
4840 CmdArgs.push_back("-fno-elide-constructors");
4841
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004842 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004843
4844 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004845 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004846 CmdArgs.push_back("-fno-rtti");
4847
4848 // -fshort-enums=0 is default for all architectures except Hexagon.
4849 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004850 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004851 CmdArgs.push_back("-fshort-enums");
4852
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004853 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004854
4855 // -fuse-cxa-atexit is default.
4856 if (!Args.hasFlag(
4857 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004858 !RawTriple.isOSWindows() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004859 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004860 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4861 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004862 KernelOrKext)
4863 CmdArgs.push_back("-fno-use-cxa-atexit");
4864
Akira Hatanaka617e2612018-04-17 18:41:52 +00004865 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4866 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004867 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004868 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4869
David L. Jonesf561aba2017-03-08 01:02:16 +00004870 // -fms-extensions=0 is default.
4871 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4872 IsWindowsMSVC))
4873 CmdArgs.push_back("-fms-extensions");
4874
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004875 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004876 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004877 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004878 CmdArgs.push_back("-fuse-line-directives");
4879
4880 // -fms-compatibility=0 is default.
4881 if (Args.hasFlag(options::OPT_fms_compatibility,
4882 options::OPT_fno_ms_compatibility,
4883 (IsWindowsMSVC &&
4884 Args.hasFlag(options::OPT_fms_extensions,
4885 options::OPT_fno_ms_extensions, true))))
4886 CmdArgs.push_back("-fms-compatibility");
4887
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004888 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004889 if (!MSVT.empty())
4890 CmdArgs.push_back(
4891 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4892
4893 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4894 if (ImplyVCPPCXXVer) {
4895 StringRef LanguageStandard;
4896 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004897 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004898 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4899 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004900 .Case("c++17", "-std=c++17")
4901 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004902 .Default("");
4903 if (LanguageStandard.empty())
4904 D.Diag(clang::diag::warn_drv_unused_argument)
4905 << StdArg->getAsString(Args);
4906 }
4907
4908 if (LanguageStandard.empty()) {
4909 if (IsMSVC2015Compatible)
4910 LanguageStandard = "-std=c++14";
4911 else
4912 LanguageStandard = "-std=c++11";
4913 }
4914
4915 CmdArgs.push_back(LanguageStandard.data());
4916 }
4917
4918 // -fno-borland-extensions is default.
4919 if (Args.hasFlag(options::OPT_fborland_extensions,
4920 options::OPT_fno_borland_extensions, false))
4921 CmdArgs.push_back("-fborland-extensions");
4922
4923 // -fno-declspec is default, except for PS4.
4924 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004925 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004926 CmdArgs.push_back("-fdeclspec");
4927 else if (Args.hasArg(options::OPT_fno_declspec))
4928 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4929
4930 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4931 // than 19.
4932 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4933 options::OPT_fno_threadsafe_statics,
4934 !IsWindowsMSVC || IsMSVC2015Compatible))
4935 CmdArgs.push_back("-fno-threadsafe-statics");
4936
Hans Wennborg82884532019-08-22 13:15:36 +00004937 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4938 // Many old Windows SDK versions require this to parse.
4939 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4940 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004941 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
Hans Wennborg82884532019-08-22 13:15:36 +00004942 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004943 CmdArgs.push_back("-fdelayed-template-parsing");
4944
4945 // -fgnu-keywords default varies depending on language; only pass if
4946 // specified.
Nico Weber908b6972019-06-26 17:51:47 +00004947 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4948 options::OPT_fno_gnu_keywords);
David L. Jonesf561aba2017-03-08 01:02:16 +00004949
4950 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4951 false))
4952 CmdArgs.push_back("-fgnu89-inline");
4953
4954 if (Args.hasArg(options::OPT_fno_inline))
4955 CmdArgs.push_back("-fno-inline");
4956
Nico Weber908b6972019-06-26 17:51:47 +00004957 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4958 options::OPT_finline_hint_functions,
4959 options::OPT_fno_inline_functions);
David L. Jonesf561aba2017-03-08 01:02:16 +00004960
Richard Smithb1b580e2019-04-14 11:11:37 +00004961 // FIXME: Find a better way to determine whether the language has modules
4962 // support by default, or just assume that all languages do.
4963 bool HaveModules =
4964 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4965 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4966
David L. Jonesf561aba2017-03-08 01:02:16 +00004967 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4968 options::OPT_fno_experimental_new_pass_manager);
4969
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004970 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004971 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4972 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004973
4974 if (Args.hasFlag(options::OPT_fapplication_extension,
4975 options::OPT_fno_application_extension, false))
4976 CmdArgs.push_back("-fapplication-extension");
4977
4978 // Handle GCC-style exception args.
4979 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004980 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004981
Martell Malonec950c652017-11-29 07:25:12 +00004982 // Handle exception personalities
Heejin Ahne8b2b882019-09-12 04:01:37 +00004983 Arg *A = Args.getLastArg(
4984 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
4985 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
Martell Malonec950c652017-11-29 07:25:12 +00004986 if (A) {
4987 const Option &Opt = A->getOption();
4988 if (Opt.matches(options::OPT_fsjlj_exceptions))
4989 CmdArgs.push_back("-fsjlj-exceptions");
4990 if (Opt.matches(options::OPT_fseh_exceptions))
4991 CmdArgs.push_back("-fseh-exceptions");
4992 if (Opt.matches(options::OPT_fdwarf_exceptions))
4993 CmdArgs.push_back("-fdwarf-exceptions");
Heejin Ahne8b2b882019-09-12 04:01:37 +00004994 if (Opt.matches(options::OPT_fwasm_exceptions))
4995 CmdArgs.push_back("-fwasm-exceptions");
Martell Malonec950c652017-11-29 07:25:12 +00004996 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004997 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004998 default:
4999 break;
5000 case llvm::ExceptionHandling::DwarfCFI:
5001 CmdArgs.push_back("-fdwarf-exceptions");
5002 break;
5003 case llvm::ExceptionHandling::SjLj:
5004 CmdArgs.push_back("-fsjlj-exceptions");
5005 break;
5006 case llvm::ExceptionHandling::WinEH:
5007 CmdArgs.push_back("-fseh-exceptions");
5008 break;
Martell Malonec950c652017-11-29 07:25:12 +00005009 }
5010 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005011
5012 // C++ "sane" operator new.
5013 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5014 options::OPT_fno_assume_sane_operator_new))
5015 CmdArgs.push_back("-fno-assume-sane-operator-new");
5016
5017 // -frelaxed-template-template-args is off by default, as it is a severe
5018 // breaking change until a corresponding change to template partial ordering
5019 // is provided.
5020 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
5021 options::OPT_fno_relaxed_template_template_args, false))
5022 CmdArgs.push_back("-frelaxed-template-template-args");
5023
5024 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5025 // most platforms.
5026 if (Args.hasFlag(options::OPT_fsized_deallocation,
5027 options::OPT_fno_sized_deallocation, false))
5028 CmdArgs.push_back("-fsized-deallocation");
5029
5030 // -faligned-allocation is on by default in C++17 onwards and otherwise off
5031 // by default.
5032 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
5033 options::OPT_fno_aligned_allocation,
5034 options::OPT_faligned_new_EQ)) {
5035 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
5036 CmdArgs.push_back("-fno-aligned-allocation");
5037 else
5038 CmdArgs.push_back("-faligned-allocation");
5039 }
5040
5041 // The default new alignment can be specified using a dedicated option or via
5042 // a GCC-compatible option that also turns on aligned allocation.
5043 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
5044 options::OPT_faligned_new_EQ))
5045 CmdArgs.push_back(
5046 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
5047
5048 // -fconstant-cfstrings is default, and may be subject to argument translation
5049 // on Darwin.
5050 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5051 options::OPT_fno_constant_cfstrings) ||
5052 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5053 options::OPT_mno_constant_cfstrings))
5054 CmdArgs.push_back("-fno-constant-cfstrings");
5055
David L. Jonesf561aba2017-03-08 01:02:16 +00005056 // -fno-pascal-strings is default, only pass non-default.
5057 if (Args.hasFlag(options::OPT_fpascal_strings,
5058 options::OPT_fno_pascal_strings, false))
5059 CmdArgs.push_back("-fpascal-strings");
5060
5061 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5062 // -fno-pack-struct doesn't apply to -fpack-struct=.
5063 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5064 std::string PackStructStr = "-fpack-struct=";
5065 PackStructStr += A->getValue();
5066 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5067 } else if (Args.hasFlag(options::OPT_fpack_struct,
5068 options::OPT_fno_pack_struct, false)) {
5069 CmdArgs.push_back("-fpack-struct=1");
5070 }
5071
5072 // Handle -fmax-type-align=N and -fno-type-align
5073 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5074 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5075 if (!SkipMaxTypeAlign) {
5076 std::string MaxTypeAlignStr = "-fmax-type-align=";
5077 MaxTypeAlignStr += A->getValue();
5078 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5079 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005080 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005081 if (!SkipMaxTypeAlign) {
5082 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5083 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5084 }
5085 }
5086
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00005087 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
5088 CmdArgs.push_back("-Qn");
5089
David L. Jonesf561aba2017-03-08 01:02:16 +00005090 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00005091 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00005092 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5093 !NoCommonDefault))
5094 CmdArgs.push_back("-fno-common");
5095
5096 // -fsigned-bitfields is default, and clang doesn't yet support
5097 // -funsigned-bitfields.
5098 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5099 options::OPT_funsigned_bitfields))
5100 D.Diag(diag::warn_drv_clang_unsupported)
5101 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5102
5103 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5104 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5105 D.Diag(diag::err_drv_clang_unsupported)
5106 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5107
5108 // -finput_charset=UTF-8 is default. Reject others
5109 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5110 StringRef value = inputCharset->getValue();
5111 if (!value.equals_lower("utf-8"))
5112 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5113 << value;
5114 }
5115
5116 // -fexec_charset=UTF-8 is default. Reject others
5117 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5118 StringRef value = execCharset->getValue();
5119 if (!value.equals_lower("utf-8"))
5120 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5121 << value;
5122 }
5123
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005124 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005125
5126 // -fno-asm-blocks is default.
5127 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5128 false))
5129 CmdArgs.push_back("-fasm-blocks");
5130
5131 // -fgnu-inline-asm is default.
5132 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5133 options::OPT_fno_gnu_inline_asm, true))
5134 CmdArgs.push_back("-fno-gnu-inline-asm");
5135
5136 // Enable vectorization per default according to the optimization level
5137 // selected. For optimization levels that want vectorization we use the alias
5138 // option to simplify the hasFlag logic.
5139 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5140 OptSpecifier VectorizeAliasOption =
5141 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5142 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5143 options::OPT_fno_vectorize, EnableVec))
5144 CmdArgs.push_back("-vectorize-loops");
5145
5146 // -fslp-vectorize is enabled based on the optimization level selected.
5147 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5148 OptSpecifier SLPVectAliasOption =
5149 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5150 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5151 options::OPT_fno_slp_vectorize, EnableSLPVec))
5152 CmdArgs.push_back("-vectorize-slp");
5153
Craig Topper9a724aa2017-12-11 21:09:19 +00005154 ParseMPreferVectorWidth(D, Args, CmdArgs);
5155
Nico Weber908b6972019-06-26 17:51:47 +00005156 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5157 Args.AddLastArg(CmdArgs,
5158 options::OPT_fsanitize_undefined_strip_path_components_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005159
5160 // -fdollars-in-identifiers default varies depending on platform and
5161 // language; only pass if specified.
5162 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5163 options::OPT_fno_dollars_in_identifiers)) {
5164 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5165 CmdArgs.push_back("-fdollars-in-identifiers");
5166 else
5167 CmdArgs.push_back("-fno-dollars-in-identifiers");
5168 }
5169
5170 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5171 // practical purposes.
5172 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5173 options::OPT_fno_unit_at_a_time)) {
5174 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5175 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5176 }
5177
5178 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5179 options::OPT_fno_apple_pragma_pack, false))
5180 CmdArgs.push_back("-fapple-pragma-pack");
5181
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005182 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005183 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005184 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005185 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005186 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5187 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005188 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005189 options::OPT_fno_save_optimization_record, false)) {
5190 CmdArgs.push_back("-opt-record-file");
5191
5192 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5193 if (A) {
5194 CmdArgs.push_back(A->getValue());
5195 } else {
5196 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005197
5198 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5199 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5200 F = FinalOutput->getValue();
5201 }
5202
5203 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005204 // Use the input filename.
5205 F = llvm::sys::path::stem(Input.getBaseInput());
5206
5207 // If we're compiling for an offload architecture (i.e. a CUDA device),
5208 // we need to make the file name for the device compilation different
5209 // from the host compilation.
5210 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5211 !JA.isDeviceOffloading(Action::OFK_Host)) {
5212 llvm::sys::path::replace_extension(F, "");
5213 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5214 Triple.normalize());
5215 F += "-";
5216 F += JA.getOffloadingArch();
5217 }
5218 }
5219
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005220 std::string Extension = "opt.";
5221 if (const Arg *A =
5222 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5223 Extension += A->getValue();
5224 else
5225 Extension += "yaml";
5226
5227 llvm::sys::path::replace_extension(F, Extension);
David L. Jonesf561aba2017-03-08 01:02:16 +00005228 CmdArgs.push_back(Args.MakeArgString(F));
5229 }
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005230
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005231 if (const Arg *A =
5232 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5233 CmdArgs.push_back("-opt-record-passes");
5234 CmdArgs.push_back(A->getValue());
5235 }
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005236
5237 if (const Arg *A =
5238 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5239 CmdArgs.push_back("-opt-record-format");
5240 CmdArgs.push_back(A->getValue());
5241 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005242 }
5243
Richard Smith86a3ef52017-06-09 21:24:02 +00005244 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5245 options::OPT_fno_rewrite_imports, false);
5246 if (RewriteImports)
5247 CmdArgs.push_back("-frewrite-imports");
5248
David L. Jonesf561aba2017-03-08 01:02:16 +00005249 // Enable rewrite includes if the user's asked for it or if we're generating
5250 // diagnostics.
5251 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5252 // nice to enable this when doing a crashdump for modules as well.
5253 if (Args.hasFlag(options::OPT_frewrite_includes,
5254 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005255 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005256 CmdArgs.push_back("-frewrite-includes");
5257
5258 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5259 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5260 options::OPT_traditional_cpp)) {
5261 if (isa<PreprocessJobAction>(JA))
5262 CmdArgs.push_back("-traditional-cpp");
5263 else
5264 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5265 }
5266
5267 Args.AddLastArg(CmdArgs, options::OPT_dM);
5268 Args.AddLastArg(CmdArgs, options::OPT_dD);
5269
5270 // Handle serialized diagnostics.
5271 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5272 CmdArgs.push_back("-serialize-diagnostic-file");
5273 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5274 }
5275
5276 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5277 CmdArgs.push_back("-fretain-comments-from-system-headers");
5278
5279 // Forward -fcomment-block-commands to -cc1.
5280 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5281 // Forward -fparse-all-comments to -cc1.
5282 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5283
5284 // Turn -fplugin=name.so into -load name.so
5285 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5286 CmdArgs.push_back("-load");
5287 CmdArgs.push_back(A->getValue());
5288 A->claim();
5289 }
5290
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005291 // Forward -fpass-plugin=name.so to -cc1.
5292 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5293 CmdArgs.push_back(
5294 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5295 A->claim();
5296 }
5297
David L. Jonesf561aba2017-03-08 01:02:16 +00005298 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005299 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5300 if (!StatsFile.empty())
5301 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005302
5303 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5304 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005305 // -finclude-default-header flag is for preprocessor,
5306 // do not pass it to other cc1 commands when save-temps is enabled
5307 if (C.getDriver().isSaveTempsEnabled() &&
5308 !isa<PreprocessJobAction>(JA)) {
5309 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5310 Arg->claim();
5311 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5312 CmdArgs.push_back(Arg->getValue());
5313 }
5314 }
5315 else {
5316 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5317 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005318 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5319 A->claim();
5320
5321 // We translate this by hand to the -cc1 argument, since nightly test uses
5322 // it and developers have been trained to spell it with -mllvm. Both
5323 // spellings are now deprecated and should be removed.
5324 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5325 CmdArgs.push_back("-disable-llvm-optzns");
5326 } else {
5327 A->render(Args, CmdArgs);
5328 }
5329 }
5330
5331 // With -save-temps, we want to save the unoptimized bitcode output from the
5332 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5333 // by the frontend.
5334 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5335 // has slightly different breakdown between stages.
5336 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5337 // pristine IR generated by the frontend. Ideally, a new compile action should
5338 // be added so both IR can be captured.
5339 if (C.getDriver().isSaveTempsEnabled() &&
5340 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5341 isa<CompileJobAction>(JA))
5342 CmdArgs.push_back("-disable-llvm-passes");
5343
David L. Jonesf561aba2017-03-08 01:02:16 +00005344 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5345
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005346 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005347
Scott Linderde6beb02018-12-14 15:38:15 +00005348 // Optionally embed the -cc1 level arguments into the debug info or a
5349 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005350 // Also record command line arguments into the debug info if
5351 // -grecord-gcc-switches options is set on.
5352 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005353 auto GRecordSwitches =
5354 Args.hasFlag(options::OPT_grecord_command_line,
5355 options::OPT_gno_record_command_line, false);
5356 auto FRecordSwitches =
5357 Args.hasFlag(options::OPT_frecord_command_line,
5358 options::OPT_fno_record_command_line, false);
5359 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5360 D.Diag(diag::err_drv_unsupported_opt_for_target)
5361 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5362 << TripleStr;
5363 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005364 ArgStringList OriginalArgs;
5365 for (const auto &Arg : Args)
5366 Arg->render(Args, OriginalArgs);
5367
5368 SmallString<256> Flags;
5369 Flags += Exec;
5370 for (const char *OriginalArg : OriginalArgs) {
5371 SmallString<128> EscapedArg;
5372 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5373 Flags += " ";
5374 Flags += EscapedArg;
5375 }
Scott Linderde6beb02018-12-14 15:38:15 +00005376 auto FlagsArgString = Args.MakeArgString(Flags);
5377 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5378 CmdArgs.push_back("-dwarf-debug-flags");
5379 CmdArgs.push_back(FlagsArgString);
5380 }
5381 if (FRecordSwitches) {
5382 CmdArgs.push_back("-record-command-line");
5383 CmdArgs.push_back(FlagsArgString);
5384 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005385 }
5386
Yaxun Liu97670892018-10-02 17:48:54 +00005387 // Host-side cuda compilation receives all device-side outputs in a single
5388 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5389 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005390 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005391 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005392 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5393 CmdArgs.push_back("-fgpu-rdc");
5394 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005395
Yaxun Liu97670892018-10-02 17:48:54 +00005396 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005397 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5398 options::OPT_fno_cuda_short_ptr, false))
5399 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005400 }
5401
David L. Jonesf561aba2017-03-08 01:02:16 +00005402 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5403 // to specify the result of the compile phase on the host, so the meaningful
5404 // device declarations can be identified. Also, -fopenmp-is-device is passed
5405 // along to tell the frontend that it is generating code for a device, so that
5406 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005407 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005408 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005409 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005410 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005411 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005412 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005413 }
5414
5415 // For all the host OpenMP offloading compile jobs we need to pass the targets
5416 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005417 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005418 SmallString<128> TargetInfo("-fopenmp-targets=");
5419
5420 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5421 assert(Tgts && Tgts->getNumValues() &&
5422 "OpenMP offloading has to have targets specified.");
5423 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5424 if (i)
5425 TargetInfo += ',';
5426 // We need to get the string from the triple because it may be not exactly
5427 // the same as the one we get directly from the arguments.
5428 llvm::Triple T(Tgts->getValue(i));
5429 TargetInfo += T.getTriple();
5430 }
5431 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5432 }
5433
5434 bool WholeProgramVTables =
5435 Args.hasFlag(options::OPT_fwhole_program_vtables,
5436 options::OPT_fno_whole_program_vtables, false);
5437 if (WholeProgramVTables) {
5438 if (!D.isUsingLTO())
5439 D.Diag(diag::err_drv_argument_only_allowed_with)
5440 << "-fwhole-program-vtables"
5441 << "-flto";
5442 CmdArgs.push_back("-fwhole-program-vtables");
5443 }
5444
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005445 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5446 bool SplitLTOUnit =
5447 Args.hasFlag(options::OPT_fsplit_lto_unit,
5448 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5449 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5450 D.Diag(diag::err_drv_argument_not_allowed_with)
5451 << "-fno-split-lto-unit"
5452 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5453 if (SplitLTOUnit)
5454 CmdArgs.push_back("-fsplit-lto-unit");
5455
Amara Emerson4ee9f822018-01-26 00:27:22 +00005456 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5457 options::OPT_fno_experimental_isel)) {
5458 CmdArgs.push_back("-mllvm");
5459 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5460 CmdArgs.push_back("-global-isel=1");
5461
5462 // GISel is on by default on AArch64 -O0, so don't bother adding
5463 // the fallback remarks for it. Other combinations will add a warning of
5464 // some kind.
5465 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5466 bool IsOptLevelSupported = false;
5467
5468 Arg *A = Args.getLastArg(options::OPT_O_Group);
5469 if (Triple.getArch() == llvm::Triple::aarch64) {
5470 if (!A || A->getOption().matches(options::OPT_O0))
5471 IsOptLevelSupported = true;
5472 }
5473 if (!IsArchSupported || !IsOptLevelSupported) {
5474 CmdArgs.push_back("-mllvm");
5475 CmdArgs.push_back("-global-isel-abort=2");
5476
5477 if (!IsArchSupported)
5478 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5479 else
5480 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5481 }
5482 } else {
5483 CmdArgs.push_back("-global-isel=0");
5484 }
5485 }
5486
Manman Ren394d4cc2019-03-04 20:30:30 +00005487 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5488 CmdArgs.push_back("-forder-file-instrumentation");
5489 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5490 // on, we need to pass these flags as linker flags and that will be handled
5491 // outside of the compiler.
5492 if (!D.isUsingLTO()) {
5493 CmdArgs.push_back("-mllvm");
5494 CmdArgs.push_back("-enable-order-file-instrumentation");
5495 }
5496 }
5497
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005498 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5499 options::OPT_fno_force_enable_int128)) {
5500 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5501 CmdArgs.push_back("-fforce-enable-int128");
5502 }
5503
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005504 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5505 options::OPT_fno_complete_member_pointers, false))
5506 CmdArgs.push_back("-fcomplete-member-pointers");
5507
Erik Pilkington5a559e62018-08-21 17:24:06 +00005508 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5509 options::OPT_fno_cxx_static_destructors, true))
5510 CmdArgs.push_back("-fno-c++-static-destructors");
5511
Jessica Paquette36a25672018-06-29 18:06:10 +00005512 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5513 options::OPT_mno_outline)) {
5514 if (A->getOption().matches(options::OPT_moutline)) {
5515 // We only support -moutline in AArch64 right now. If we're not compiling
5516 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5517 // proper mllvm flags.
5518 if (Triple.getArch() != llvm::Triple::aarch64) {
5519 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5520 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005521 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005522 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005523 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005524 } else {
5525 // Disable all outlining behaviour.
5526 CmdArgs.push_back("-mllvm");
5527 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005528 }
5529 }
5530
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005531 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005532 (TC.getTriple().isOSBinFormatELF() ||
5533 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005534 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005535 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005536 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005537 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005538 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005539 CmdArgs.push_back("-faddrsig");
5540
Peter Collingbournee08e68d2019-06-07 19:10:08 +00005541 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5542 std::string Str = A->getAsString(Args);
5543 if (!TC.getTriple().isOSBinFormatELF())
5544 D.Diag(diag::err_drv_unsupported_opt_for_target)
5545 << Str << TC.getTripleString();
5546 CmdArgs.push_back(Args.MakeArgString(Str));
5547 }
5548
Reid Kleckner549ed542019-05-23 18:35:43 +00005549 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5550 // the -cc1 command easier to edit when reproducing compiler crashes.
5551 if (Output.getType() == types::TY_Dependencies) {
5552 // Handled with other dependency code.
5553 } else if (Output.isFilename()) {
5554 CmdArgs.push_back("-o");
5555 CmdArgs.push_back(Output.getFilename());
5556 } else {
5557 assert(Output.isNothing() && "Invalid output.");
5558 }
5559
5560 addDashXForInput(Args, Input, CmdArgs);
5561
5562 ArrayRef<InputInfo> FrontendInputs = Input;
5563 if (IsHeaderModulePrecompile)
5564 FrontendInputs = ModuleHeaderInputs;
5565 else if (Input.isNothing())
5566 FrontendInputs = {};
5567
5568 for (const InputInfo &Input : FrontendInputs) {
5569 if (Input.isFilename())
5570 CmdArgs.push_back(Input.getFilename());
5571 else
5572 Input.getInputArg().renderAsInput(Args, CmdArgs);
5573 }
5574
David L. Jonesf561aba2017-03-08 01:02:16 +00005575 // Finally add the compile command to the compilation.
5576 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5577 Output.getType() == types::TY_Object &&
5578 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5579 auto CLCommand =
5580 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005581 C.addCommand(std::make_unique<FallbackCommand>(
David L. Jonesf561aba2017-03-08 01:02:16 +00005582 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5583 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5584 isa<PrecompileJobAction>(JA)) {
5585 // In /fallback builds, run the main compilation even if the pch generation
5586 // fails, so that the main compilation's fallback to cl.exe runs.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005587 C.addCommand(std::make_unique<ForceSuccessCommand>(JA, *this, Exec,
David L. Jonesf561aba2017-03-08 01:02:16 +00005588 CmdArgs, Inputs));
5589 } else {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00005590 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00005591 }
5592
Hans Wennborg2fe01042018-10-13 19:13:14 +00005593 // Make the compile command echo its inputs for /showFilenames.
5594 if (Output.getType() == types::TY_Object &&
5595 Args.hasFlag(options::OPT__SLASH_showFilenames,
5596 options::OPT__SLASH_showFilenames_, false)) {
5597 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5598 }
5599
David L. Jonesf561aba2017-03-08 01:02:16 +00005600 if (Arg *A = Args.getLastArg(options::OPT_pg))
Yuanfang Chenff22ec32019-07-20 22:50:50 +00005601 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
David L. Jonesf561aba2017-03-08 01:02:16 +00005602 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5603 << A->getAsString(Args);
5604
5605 // Claim some arguments which clang supports automatically.
5606
5607 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005608 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005609 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5610
5611 // Claim some arguments which clang doesn't support, but we don't
5612 // care to warn the user about.
5613 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5614 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5615
5616 // Disable warnings for clang -E -emit-llvm foo.c
5617 Args.ClaimAllArgs(options::OPT_emit_llvm);
5618}
5619
5620Clang::Clang(const ToolChain &TC)
5621 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5622 // as it is for other tools. Some operations on a Tool actually test
5623 // whether that tool is Clang based on the Tool's Name as a string.
5624 : Tool("clang", "clang frontend", TC, RF_Full) {}
5625
5626Clang::~Clang() {}
5627
5628/// Add options related to the Objective-C runtime/ABI.
5629///
5630/// Returns true if the runtime is non-fragile.
5631ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5632 ArgStringList &cmdArgs,
5633 RewriteKind rewriteKind) const {
5634 // Look for the controlling runtime option.
5635 Arg *runtimeArg =
5636 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5637 options::OPT_fobjc_runtime_EQ);
5638
5639 // Just forward -fobjc-runtime= to the frontend. This supercedes
5640 // options about fragility.
5641 if (runtimeArg &&
5642 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5643 ObjCRuntime runtime;
5644 StringRef value = runtimeArg->getValue();
5645 if (runtime.tryParse(value)) {
5646 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5647 << value;
5648 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005649 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5650 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005651 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5652 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005653 getToolChain().getDriver().Diag(
5654 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5655 << runtime.getVersion().getMajor();
5656 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005657
5658 runtimeArg->render(args, cmdArgs);
5659 return runtime;
5660 }
5661
5662 // Otherwise, we'll need the ABI "version". Version numbers are
5663 // slightly confusing for historical reasons:
5664 // 1 - Traditional "fragile" ABI
5665 // 2 - Non-fragile ABI, version 1
5666 // 3 - Non-fragile ABI, version 2
5667 unsigned objcABIVersion = 1;
5668 // If -fobjc-abi-version= is present, use that to set the version.
5669 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5670 StringRef value = abiArg->getValue();
5671 if (value == "1")
5672 objcABIVersion = 1;
5673 else if (value == "2")
5674 objcABIVersion = 2;
5675 else if (value == "3")
5676 objcABIVersion = 3;
5677 else
5678 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5679 } else {
5680 // Otherwise, determine if we are using the non-fragile ABI.
5681 bool nonFragileABIIsDefault =
5682 (rewriteKind == RK_NonFragile ||
5683 (rewriteKind == RK_None &&
5684 getToolChain().IsObjCNonFragileABIDefault()));
5685 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5686 options::OPT_fno_objc_nonfragile_abi,
5687 nonFragileABIIsDefault)) {
5688// Determine the non-fragile ABI version to use.
5689#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5690 unsigned nonFragileABIVersion = 1;
5691#else
5692 unsigned nonFragileABIVersion = 2;
5693#endif
5694
5695 if (Arg *abiArg =
5696 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5697 StringRef value = abiArg->getValue();
5698 if (value == "1")
5699 nonFragileABIVersion = 1;
5700 else if (value == "2")
5701 nonFragileABIVersion = 2;
5702 else
5703 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5704 << value;
5705 }
5706
5707 objcABIVersion = 1 + nonFragileABIVersion;
5708 } else {
5709 objcABIVersion = 1;
5710 }
5711 }
5712
5713 // We don't actually care about the ABI version other than whether
5714 // it's non-fragile.
5715 bool isNonFragile = objcABIVersion != 1;
5716
5717 // If we have no runtime argument, ask the toolchain for its default runtime.
5718 // However, the rewriter only really supports the Mac runtime, so assume that.
5719 ObjCRuntime runtime;
5720 if (!runtimeArg) {
5721 switch (rewriteKind) {
5722 case RK_None:
5723 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5724 break;
5725 case RK_Fragile:
5726 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5727 break;
5728 case RK_NonFragile:
5729 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5730 break;
5731 }
5732
5733 // -fnext-runtime
5734 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5735 // On Darwin, make this use the default behavior for the toolchain.
5736 if (getToolChain().getTriple().isOSDarwin()) {
5737 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5738
5739 // Otherwise, build for a generic macosx port.
5740 } else {
5741 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5742 }
5743
5744 // -fgnu-runtime
5745 } else {
5746 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5747 // Legacy behaviour is to target the gnustep runtime if we are in
5748 // non-fragile mode or the GCC runtime in fragile mode.
5749 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005750 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005751 else
5752 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5753 }
5754
5755 cmdArgs.push_back(
5756 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5757 return runtime;
5758}
5759
5760static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5761 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5762 I += HaveDash;
5763 return !HaveDash;
5764}
5765
5766namespace {
5767struct EHFlags {
5768 bool Synch = false;
5769 bool Asynch = false;
5770 bool NoUnwindC = false;
5771};
5772} // end anonymous namespace
5773
5774/// /EH controls whether to run destructor cleanups when exceptions are
5775/// thrown. There are three modifiers:
5776/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5777/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5778/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5779/// - c: Assume that extern "C" functions are implicitly nounwind.
5780/// The default is /EHs-c-, meaning cleanups are disabled.
5781static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5782 EHFlags EH;
5783
5784 std::vector<std::string> EHArgs =
5785 Args.getAllArgValues(options::OPT__SLASH_EH);
5786 for (auto EHVal : EHArgs) {
5787 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5788 switch (EHVal[I]) {
5789 case 'a':
5790 EH.Asynch = maybeConsumeDash(EHVal, I);
5791 if (EH.Asynch)
5792 EH.Synch = false;
5793 continue;
5794 case 'c':
5795 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5796 continue;
5797 case 's':
5798 EH.Synch = maybeConsumeDash(EHVal, I);
5799 if (EH.Synch)
5800 EH.Asynch = false;
5801 continue;
5802 default:
5803 break;
5804 }
5805 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5806 break;
5807 }
5808 }
5809 // The /GX, /GX- flags are only processed if there are not /EH flags.
5810 // The default is that /GX is not specified.
5811 if (EHArgs.empty() &&
5812 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005813 /*Default=*/false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005814 EH.Synch = true;
5815 EH.NoUnwindC = true;
5816 }
5817
5818 return EH;
5819}
5820
5821void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5822 ArgStringList &CmdArgs,
5823 codegenoptions::DebugInfoKind *DebugInfoKind,
5824 bool *EmitCodeView) const {
5825 unsigned RTOptionID = options::OPT__SLASH_MT;
5826
5827 if (Args.hasArg(options::OPT__SLASH_LDd))
5828 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5829 // but defining _DEBUG is sticky.
5830 RTOptionID = options::OPT__SLASH_MTd;
5831
5832 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5833 RTOptionID = A->getOption().getID();
5834
5835 StringRef FlagForCRT;
5836 switch (RTOptionID) {
5837 case options::OPT__SLASH_MD:
5838 if (Args.hasArg(options::OPT__SLASH_LDd))
5839 CmdArgs.push_back("-D_DEBUG");
5840 CmdArgs.push_back("-D_MT");
5841 CmdArgs.push_back("-D_DLL");
5842 FlagForCRT = "--dependent-lib=msvcrt";
5843 break;
5844 case options::OPT__SLASH_MDd:
5845 CmdArgs.push_back("-D_DEBUG");
5846 CmdArgs.push_back("-D_MT");
5847 CmdArgs.push_back("-D_DLL");
5848 FlagForCRT = "--dependent-lib=msvcrtd";
5849 break;
5850 case options::OPT__SLASH_MT:
5851 if (Args.hasArg(options::OPT__SLASH_LDd))
5852 CmdArgs.push_back("-D_DEBUG");
5853 CmdArgs.push_back("-D_MT");
5854 CmdArgs.push_back("-flto-visibility-public-std");
5855 FlagForCRT = "--dependent-lib=libcmt";
5856 break;
5857 case options::OPT__SLASH_MTd:
5858 CmdArgs.push_back("-D_DEBUG");
5859 CmdArgs.push_back("-D_MT");
5860 CmdArgs.push_back("-flto-visibility-public-std");
5861 FlagForCRT = "--dependent-lib=libcmtd";
5862 break;
5863 default:
5864 llvm_unreachable("Unexpected option ID.");
5865 }
5866
5867 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5868 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5869 } else {
5870 CmdArgs.push_back(FlagForCRT.data());
5871
5872 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5873 // users want. The /Za flag to cl.exe turns this off, but it's not
5874 // implemented in clang.
5875 CmdArgs.push_back("--dependent-lib=oldnames");
5876 }
5877
Nico Weber908b6972019-06-26 17:51:47 +00005878 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
David L. Jonesf561aba2017-03-08 01:02:16 +00005879
5880 // This controls whether or not we emit RTTI data for polymorphic types.
5881 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005882 /*Default=*/false))
David L. Jonesf561aba2017-03-08 01:02:16 +00005883 CmdArgs.push_back("-fno-rtti-data");
5884
5885 // This controls whether or not we emit stack-protector instrumentation.
5886 // In MSVC, Buffer Security Check (/GS) is on by default.
5887 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005888 /*Default=*/true)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005889 CmdArgs.push_back("-stack-protector");
5890 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5891 }
5892
5893 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5894 if (Arg *DebugInfoArg =
5895 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5896 options::OPT_gline_tables_only)) {
5897 *EmitCodeView = true;
5898 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5899 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5900 else
5901 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005902 } else {
5903 *EmitCodeView = false;
5904 }
5905
5906 const Driver &D = getToolChain().getDriver();
5907 EHFlags EH = parseClangCLEHFlags(D, Args);
5908 if (EH.Synch || EH.Asynch) {
5909 if (types::isCXX(InputType))
5910 CmdArgs.push_back("-fcxx-exceptions");
5911 CmdArgs.push_back("-fexceptions");
5912 }
5913 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5914 CmdArgs.push_back("-fexternc-nounwind");
5915
5916 // /EP should expand to -E -P.
5917 if (Args.hasArg(options::OPT__SLASH_EP)) {
5918 CmdArgs.push_back("-E");
5919 CmdArgs.push_back("-P");
5920 }
5921
5922 unsigned VolatileOptionID;
5923 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5924 getToolChain().getArch() == llvm::Triple::x86)
5925 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5926 else
5927 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5928
5929 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5930 VolatileOptionID = A->getOption().getID();
5931
5932 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5933 CmdArgs.push_back("-fms-volatile");
5934
Takuto Ikuta302c6432018-11-03 06:45:00 +00005935 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5936 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005937 false)) {
5938 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5939 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5940 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005941 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005942 }
5943 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005944
David L. Jonesf561aba2017-03-08 01:02:16 +00005945 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5946 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5947 if (MostGeneralArg && BestCaseArg)
5948 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5949 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5950
5951 if (MostGeneralArg) {
5952 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5953 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5954 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5955
5956 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5957 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5958 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5959 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5960 << FirstConflict->getAsString(Args)
5961 << SecondConflict->getAsString(Args);
5962
5963 if (SingleArg)
5964 CmdArgs.push_back("-fms-memptr-rep=single");
5965 else if (MultipleArg)
5966 CmdArgs.push_back("-fms-memptr-rep=multiple");
5967 else
5968 CmdArgs.push_back("-fms-memptr-rep=virtual");
5969 }
5970
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005971 // Parse the default calling convention options.
5972 if (Arg *CCArg =
5973 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005974 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5975 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005976 unsigned DCCOptId = CCArg->getOption().getID();
5977 const char *DCCFlag = nullptr;
5978 bool ArchSupported = true;
5979 llvm::Triple::ArchType Arch = getToolChain().getArch();
5980 switch (DCCOptId) {
5981 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005982 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005983 break;
5984 case options::OPT__SLASH_Gr:
5985 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005986 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005987 break;
5988 case options::OPT__SLASH_Gz:
5989 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005990 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005991 break;
5992 case options::OPT__SLASH_Gv:
5993 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005994 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005995 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005996 case options::OPT__SLASH_Gregcall:
5997 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5998 DCCFlag = "-fdefault-calling-conv=regcall";
5999 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00006000 }
6001
6002 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
6003 if (ArchSupported && DCCFlag)
6004 CmdArgs.push_back(DCCFlag);
6005 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006006
Nico Weber908b6972019-06-26 17:51:47 +00006007 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00006008
6009 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6010 CmdArgs.push_back("-fdiagnostics-format");
6011 if (Args.hasArg(options::OPT__SLASH_fallback))
6012 CmdArgs.push_back("msvc-fallback");
6013 else
6014 CmdArgs.push_back("msvc");
6015 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00006016
Hans Wennborga912e3e2018-08-10 09:49:21 +00006017 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
6018 SmallVector<StringRef, 1> SplitArgs;
6019 StringRef(A->getValue()).split(SplitArgs, ",");
6020 bool Instrument = false;
6021 bool NoChecks = false;
6022 for (StringRef Arg : SplitArgs) {
6023 if (Arg.equals_lower("cf"))
6024 Instrument = true;
6025 else if (Arg.equals_lower("cf-"))
6026 Instrument = false;
6027 else if (Arg.equals_lower("nochecks"))
6028 NoChecks = true;
6029 else if (Arg.equals_lower("nochecks-"))
6030 NoChecks = false;
6031 else
6032 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
6033 }
6034 // Currently there's no support emitting CFG instrumentation; the flag only
6035 // emits the table of address-taken functions.
6036 if (Instrument || NoChecks)
6037 CmdArgs.push_back("-cfguard");
6038 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006039}
6040
6041visualstudio::Compiler *Clang::getCLFallback() const {
6042 if (!CLFallback)
6043 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6044 return CLFallback.get();
6045}
6046
6047
6048const char *Clang::getBaseInputName(const ArgList &Args,
6049 const InputInfo &Input) {
6050 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6051}
6052
6053const char *Clang::getBaseInputStem(const ArgList &Args,
6054 const InputInfoList &Inputs) {
6055 const char *Str = getBaseInputName(Args, Inputs[0]);
6056
6057 if (const char *End = strrchr(Str, '.'))
6058 return Args.MakeArgString(std::string(Str, End));
6059
6060 return Str;
6061}
6062
6063const char *Clang::getDependencyFileName(const ArgList &Args,
6064 const InputInfoList &Inputs) {
6065 // FIXME: Think about this more.
David L. Jonesf561aba2017-03-08 01:02:16 +00006066
6067 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
Luke Cheesemanab9acda2019-09-13 13:15:35 +00006068 SmallString<128> OutputFilename(OutputOpt->getValue());
6069 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
6070 return Args.MakeArgString(OutputFilename);
David L. Jonesf561aba2017-03-08 01:02:16 +00006071 }
Luke Cheesemanab9acda2019-09-13 13:15:35 +00006072
Fangrui Song6fe3d362019-09-14 04:13:15 +00006073 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
David L. Jonesf561aba2017-03-08 01:02:16 +00006074}
6075
6076// Begin ClangAs
6077
6078void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6079 ArgStringList &CmdArgs) const {
6080 StringRef CPUName;
6081 StringRef ABIName;
6082 const llvm::Triple &Triple = getToolChain().getTriple();
6083 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6084
6085 CmdArgs.push_back("-target-abi");
6086 CmdArgs.push_back(ABIName.data());
6087}
6088
6089void ClangAs::AddX86TargetArgs(const ArgList &Args,
6090 ArgStringList &CmdArgs) const {
6091 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6092 StringRef Value = A->getValue();
6093 if (Value == "intel" || Value == "att") {
6094 CmdArgs.push_back("-mllvm");
6095 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6096 } else {
6097 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6098 << A->getOption().getName() << Value;
6099 }
6100 }
6101}
6102
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006103void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6104 ArgStringList &CmdArgs) const {
6105 const llvm::Triple &Triple = getToolChain().getTriple();
6106 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6107
6108 CmdArgs.push_back("-target-abi");
6109 CmdArgs.push_back(ABIName.data());
6110}
6111
David L. Jonesf561aba2017-03-08 01:02:16 +00006112void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6113 const InputInfo &Output, const InputInfoList &Inputs,
6114 const ArgList &Args,
6115 const char *LinkingOutput) const {
6116 ArgStringList CmdArgs;
6117
6118 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6119 const InputInfo &Input = Inputs[0];
6120
Martin Storsjob547ef22018-10-26 08:33:29 +00006121 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00006122 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00006123 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00006124
6125 // Don't warn about "clang -w -c foo.s"
6126 Args.ClaimAllArgs(options::OPT_w);
6127 // and "clang -emit-llvm -c foo.s"
6128 Args.ClaimAllArgs(options::OPT_emit_llvm);
6129
6130 claimNoWarnArgs(Args);
6131
6132 // Invoke ourselves in -cc1as mode.
6133 //
6134 // FIXME: Implement custom jobs for internal actions.
6135 CmdArgs.push_back("-cc1as");
6136
6137 // Add the "effective" target triple.
6138 CmdArgs.push_back("-triple");
6139 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6140
6141 // Set the output mode, we currently only expect to be used as a real
6142 // assembler.
6143 CmdArgs.push_back("-filetype");
6144 CmdArgs.push_back("obj");
6145
6146 // Set the main file name, so that debug info works even with
6147 // -save-temps or preprocessed assembly.
6148 CmdArgs.push_back("-main-file-name");
6149 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6150
6151 // Add the target cpu
6152 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6153 if (!CPU.empty()) {
6154 CmdArgs.push_back("-target-cpu");
6155 CmdArgs.push_back(Args.MakeArgString(CPU));
6156 }
6157
6158 // Add the target features
6159 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6160
6161 // Ignore explicit -force_cpusubtype_ALL option.
6162 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6163
6164 // Pass along any -I options so we get proper .include search paths.
6165 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6166
6167 // Determine the original source input.
6168 const Action *SourceAction = &JA;
6169 while (SourceAction->getKind() != Action::InputClass) {
6170 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6171 SourceAction = SourceAction->getInputs()[0];
6172 }
6173
6174 // Forward -g and handle debug info related flags, assuming we are dealing
6175 // with an actual assembly file.
6176 bool WantDebug = false;
6177 unsigned DwarfVersion = 0;
6178 Args.ClaimAllArgs(options::OPT_g_Group);
6179 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6180 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6181 !A->getOption().matches(options::OPT_ggdb0);
6182 if (WantDebug)
6183 DwarfVersion = DwarfVersionNum(A->getSpelling());
6184 }
6185 if (DwarfVersion == 0)
6186 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6187
6188 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6189
6190 if (SourceAction->getType() == types::TY_Asm ||
6191 SourceAction->getType() == types::TY_PP_Asm) {
6192 // You might think that it would be ok to set DebugInfoKind outside of
6193 // the guard for source type, however there is a test which asserts
6194 // that some assembler invocation receives no -debug-info-kind,
6195 // and it's not clear whether that test is just overly restrictive.
6196 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6197 : codegenoptions::NoDebugInfo);
6198 // Add the -fdebug-compilation-dir flag if needed.
Hans Wennborg999f8a72019-09-05 08:43:00 +00006199 addDebugCompDirArg(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00006200
Paul Robinson9b292b42018-07-10 15:15:24 +00006201 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6202
David L. Jonesf561aba2017-03-08 01:02:16 +00006203 // Set the AT_producer to the clang version when using the integrated
6204 // assembler on assembly source files.
6205 CmdArgs.push_back("-dwarf-debug-producer");
6206 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6207
6208 // And pass along -I options
6209 Args.AddAllArgs(CmdArgs, options::OPT_I);
6210 }
6211 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6212 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006213 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006214
David L. Jonesf561aba2017-03-08 01:02:16 +00006215
6216 // Handle -fPIC et al -- the relocation-model affects the assembler
6217 // for some targets.
6218 llvm::Reloc::Model RelocationModel;
6219 unsigned PICLevel;
6220 bool IsPIE;
6221 std::tie(RelocationModel, PICLevel, IsPIE) =
6222 ParsePICArgs(getToolChain(), Args);
6223
6224 const char *RMName = RelocationModelName(RelocationModel);
6225 if (RMName) {
6226 CmdArgs.push_back("-mrelocation-model");
6227 CmdArgs.push_back(RMName);
6228 }
6229
6230 // Optionally embed the -cc1as level arguments into the debug info, for build
6231 // analysis.
6232 if (getToolChain().UseDwarfDebugFlags()) {
6233 ArgStringList OriginalArgs;
6234 for (const auto &Arg : Args)
6235 Arg->render(Args, OriginalArgs);
6236
6237 SmallString<256> Flags;
6238 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6239 Flags += Exec;
6240 for (const char *OriginalArg : OriginalArgs) {
6241 SmallString<128> EscapedArg;
6242 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6243 Flags += " ";
6244 Flags += EscapedArg;
6245 }
6246 CmdArgs.push_back("-dwarf-debug-flags");
6247 CmdArgs.push_back(Args.MakeArgString(Flags));
6248 }
6249
6250 // FIXME: Add -static support, once we have it.
6251
6252 // Add target specific flags.
6253 switch (getToolChain().getArch()) {
6254 default:
6255 break;
6256
6257 case llvm::Triple::mips:
6258 case llvm::Triple::mipsel:
6259 case llvm::Triple::mips64:
6260 case llvm::Triple::mips64el:
6261 AddMIPSTargetArgs(Args, CmdArgs);
6262 break;
6263
6264 case llvm::Triple::x86:
6265 case llvm::Triple::x86_64:
6266 AddX86TargetArgs(Args, CmdArgs);
6267 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006268
6269 case llvm::Triple::arm:
6270 case llvm::Triple::armeb:
6271 case llvm::Triple::thumb:
6272 case llvm::Triple::thumbeb:
6273 // This isn't in AddARMTargetArgs because we want to do this for assembly
6274 // only, not C/C++.
6275 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6276 options::OPT_mno_default_build_attributes, true)) {
6277 CmdArgs.push_back("-mllvm");
6278 CmdArgs.push_back("-arm-add-build-attributes");
6279 }
6280 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006281
6282 case llvm::Triple::riscv32:
6283 case llvm::Triple::riscv64:
6284 AddRISCVTargetArgs(Args, CmdArgs);
6285 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006286 }
6287
6288 // Consume all the warning flags. Usually this would be handled more
6289 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6290 // doesn't handle that so rather than warning about unused flags that are
6291 // actually used, we'll lie by omission instead.
6292 // FIXME: Stop lying and consume only the appropriate driver flags
6293 Args.ClaimAllArgs(options::OPT_W_Group);
6294
6295 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6296 getToolChain().getDriver());
6297
6298 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6299
6300 assert(Output.isFilename() && "Unexpected lipo output.");
6301 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006302 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006303
Petr Hosekd3265352018-10-15 21:30:32 +00006304 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006305 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006306 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6307 T.isOSBinFormatELF()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00006308 CmdArgs.push_back("-split-dwarf-output");
George Rimar36d71da2019-03-27 11:00:03 +00006309 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006310 }
6311
David L. Jonesf561aba2017-03-08 01:02:16 +00006312 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006313 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006314
6315 const char *Exec = getToolChain().getDriver().getClangProgramPath();
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006316 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006317}
6318
6319// Begin OffloadBundler
6320
6321void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6322 const InputInfo &Output,
6323 const InputInfoList &Inputs,
6324 const llvm::opt::ArgList &TCArgs,
6325 const char *LinkingOutput) const {
6326 // The version with only one output is expected to refer to a bundling job.
6327 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6328
6329 // The bundling command looks like this:
6330 // clang-offload-bundler -type=bc
6331 // -targets=host-triple,openmp-triple1,openmp-triple2
6332 // -outputs=input_file
6333 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6334
6335 ArgStringList CmdArgs;
6336
6337 // Get the type.
6338 CmdArgs.push_back(TCArgs.MakeArgString(
6339 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6340
6341 assert(JA.getInputs().size() == Inputs.size() &&
6342 "Not have inputs for all dependence actions??");
6343
6344 // Get the targets.
6345 SmallString<128> Triples;
6346 Triples += "-targets=";
6347 for (unsigned I = 0; I < Inputs.size(); ++I) {
6348 if (I)
6349 Triples += ',';
6350
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006351 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006352 Action::OffloadKind CurKind = Action::OFK_Host;
6353 const ToolChain *CurTC = &getToolChain();
6354 const Action *CurDep = JA.getInputs()[I];
6355
6356 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006357 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006358 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006359 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006360 CurKind = A->getOffloadingDeviceKind();
6361 CurTC = TC;
6362 });
6363 }
6364 Triples += Action::GetOffloadKindName(CurKind);
6365 Triples += '-';
6366 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006367 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6368 Triples += '-';
6369 Triples += CurDep->getOffloadingArch();
6370 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006371 }
6372 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6373
6374 // Get bundled file command.
6375 CmdArgs.push_back(
6376 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6377
6378 // Get unbundled files command.
6379 SmallString<128> UB;
6380 UB += "-inputs=";
6381 for (unsigned I = 0; I < Inputs.size(); ++I) {
6382 if (I)
6383 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006384
6385 // Find ToolChain for this input.
6386 const ToolChain *CurTC = &getToolChain();
6387 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6388 CurTC = nullptr;
6389 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6390 assert(CurTC == nullptr && "Expected one dependence!");
6391 CurTC = TC;
6392 });
6393 }
6394 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006395 }
6396 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6397
6398 // All the inputs are encoded as commands.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006399 C.addCommand(std::make_unique<Command>(
David L. Jonesf561aba2017-03-08 01:02:16 +00006400 JA, *this,
6401 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6402 CmdArgs, None));
6403}
6404
6405void OffloadBundler::ConstructJobMultipleOutputs(
6406 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6407 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6408 const char *LinkingOutput) const {
6409 // The version with multiple outputs is expected to refer to a unbundling job.
6410 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6411
6412 // The unbundling command looks like this:
6413 // clang-offload-bundler -type=bc
6414 // -targets=host-triple,openmp-triple1,openmp-triple2
6415 // -inputs=input_file
6416 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6417 // -unbundle
6418
6419 ArgStringList CmdArgs;
6420
6421 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6422 InputInfo Input = Inputs.front();
6423
6424 // Get the type.
6425 CmdArgs.push_back(TCArgs.MakeArgString(
6426 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6427
6428 // Get the targets.
6429 SmallString<128> Triples;
6430 Triples += "-targets=";
6431 auto DepInfo = UA.getDependentActionsInfo();
6432 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6433 if (I)
6434 Triples += ',';
6435
6436 auto &Dep = DepInfo[I];
6437 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6438 Triples += '-';
6439 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006440 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6441 !Dep.DependentBoundArch.empty()) {
6442 Triples += '-';
6443 Triples += Dep.DependentBoundArch;
6444 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006445 }
6446
6447 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6448
6449 // Get bundled file command.
6450 CmdArgs.push_back(
6451 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6452
6453 // Get unbundled files command.
6454 SmallString<128> UB;
6455 UB += "-outputs=";
6456 for (unsigned I = 0; I < Outputs.size(); ++I) {
6457 if (I)
6458 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006459 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006460 }
6461 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6462 CmdArgs.push_back("-unbundle");
6463
6464 // All the inputs are encoded as commands.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00006465 C.addCommand(std::make_unique<Command>(
David L. Jonesf561aba2017-03-08 01:02:16 +00006466 JA, *this,
6467 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6468 CmdArgs, None));
6469}