blob: 44663a4dbd7c901cb8dc3f114c433b4e3af22d35 [file] [log] [blame]
Fangrui Song524b3c12019-03-01 06:49:51 +00001//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
David L. Jonesf561aba2017-03-08 01:02:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
David L. Jonesf561aba2017-03-08 01:02:16 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
Alex Bradbury71f45452018-01-11 13:36:56 +000014#include "Arch/RISCV.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Arch/X86.h"
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +000018#include "AMDGPU.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000019#include "CommonArgs.h"
20#include "Hexagon.h"
Anton Korobeynikov93165d62019-01-15 19:44:05 +000021#include "MSP430.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000022#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
Yuanfang Chenff22ec32019-07-20 22:50:50 +000025#include "clang/Basic/CodeGenOptions.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/ObjCRuntime.h"
28#include "clang/Basic/Version.h"
Michal Gornydae01c32018-12-23 15:07:26 +000029#include "clang/Driver/Distro.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000030#include "clang/Driver/DriverDiagnostic.h"
31#include "clang/Driver/Options.h"
32#include "clang/Driver/SanitizerArgs.h"
Dean Michael Berris835832d2017-03-30 00:29:36 +000033#include "clang/Driver/XRayArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "llvm/ADT/StringExtras.h"
Nico Weberd637c052018-04-30 13:52:15 +000035#include "llvm/Config/llvm-config.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000036#include "llvm/Option/ArgList.h"
37#include "llvm/Support/CodeGen.h"
38#include "llvm/Support/Compression.h"
39#include "llvm/Support/FileSystem.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Process.h"
Eric Christopher53b2cb72017-06-30 00:03:56 +000042#include "llvm/Support/TargetParser.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000043#include "llvm/Support/YAMLParser.h"
44
45#ifdef LLVM_ON_UNIX
46#include <unistd.h> // For getuid().
47#endif
48
49using namespace clang::driver;
50using namespace clang::driver::tools;
51using namespace clang;
52using namespace llvm::opt;
53
54static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
55 if (Arg *A =
56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60 << A->getBaseArg().getAsString(Args)
61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
62 }
63 }
64}
65
66static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67 // In gcc, only ARM checks this, but it seems reasonable to check universally.
68 if (Args.hasArg(options::OPT_static))
69 if (const Arg *A =
70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
72 << "-static";
73}
74
75// Add backslashes to escape spaces and other backslashes.
76// This is used for the space-separated argument list specified with
77// the -dwarf-debug-flags option.
78static void EscapeSpacesAndBackslashes(const char *Arg,
79 SmallVectorImpl<char> &Res) {
80 for (; *Arg; ++Arg) {
81 switch (*Arg) {
82 default:
83 break;
84 case ' ':
85 case '\\':
86 Res.push_back('\\');
87 break;
88 }
89 Res.push_back(*Arg);
90 }
91}
92
93// Quote target names for inclusion in GNU Make dependency files.
94// Only the characters '$', '#', ' ', '\t' are quoted.
95static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
97 switch (Target[i]) {
98 case ' ':
99 case '\t':
100 // Escape the preceding backslashes
101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
102 Res.push_back('\\');
103
104 // Escape the space/tab
105 Res.push_back('\\');
106 break;
107 case '$':
108 Res.push_back('$');
109 break;
110 case '#':
111 Res.push_back('\\');
112 break;
113 default:
114 break;
115 }
116
117 Res.push_back(Target[i]);
118 }
119}
120
121/// Apply \a Work on the current tool chain \a RegularToolChain and any other
122/// offloading tool chain that is associated with the current action \a JA.
123static void
124forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125 const ToolChain &RegularToolChain,
126 llvm::function_ref<void(const ToolChain &)> Work) {
127 // Apply Work on the current/regular tool chain.
128 Work(RegularToolChain);
129
130 // Apply Work on all the offloading tool chains associated with the current
131 // action.
132 if (JA.isHostOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
Yaxun Liu398612b2018-05-08 21:02:12 +0000136 else if (JA.isHostOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138 else if (JA.isDeviceOffloading(Action::OFK_HIP))
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
David L. Jonesf561aba2017-03-08 01:02:16 +0000140
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +0000141 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
144 Work(*II->second);
145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
147
David L. Jonesf561aba2017-03-08 01:02:16 +0000148 //
149 // TODO: Add support for other offloading programming models here.
150 //
151}
152
153/// This is a helper function for validating the optional refinement step
154/// parameter in reciprocal argument strings. Return false if there is an error
155/// parsing the refinement step. Otherwise, return true and set the Position
156/// of the refinement step in the input string.
157static bool getRefinementStep(StringRef In, const Driver &D,
158 const Arg &A, size_t &Position) {
159 const char RefinementStepToken = ':';
160 Position = In.find(RefinementStepToken);
161 if (Position != StringRef::npos) {
162 StringRef Option = A.getOption().getName();
163 StringRef RefStep = In.substr(Position + 1);
164 // Allow exactly one numeric character for the additional refinement
165 // step parameter. This is reasonable for all currently-supported
166 // operations and architectures because we would expect that a larger value
167 // of refinement steps would cause the estimate "optimization" to
168 // under-perform the native operation. Also, if the estimate does not
169 // converge quickly, it probably will not ever converge, so further
170 // refinement steps will not produce a better answer.
171 if (RefStep.size() != 1) {
172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
173 return false;
174 }
175 char RefStepChar = RefStep[0];
176 if (RefStepChar < '0' || RefStepChar > '9') {
177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
178 return false;
179 }
180 }
181 return true;
182}
183
184/// The -mrecip flag requires processing of many optional parameters.
185static void ParseMRecip(const Driver &D, const ArgList &Args,
186 ArgStringList &OutStrings) {
187 StringRef DisabledPrefixIn = "!";
188 StringRef DisabledPrefixOut = "!";
189 StringRef EnabledPrefixOut = "";
190 StringRef Out = "-mrecip=";
191
192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
193 if (!A)
194 return;
195
196 unsigned NumOptions = A->getNumValues();
197 if (NumOptions == 0) {
198 // No option is the same as "all".
199 OutStrings.push_back(Args.MakeArgString(Out + "all"));
200 return;
201 }
202
203 // Pass through "all", "none", or "default" with an optional refinement step.
204 if (NumOptions == 1) {
205 StringRef Val = A->getValue(0);
206 size_t RefStepLoc;
207 if (!getRefinementStep(Val, D, *A, RefStepLoc))
208 return;
209 StringRef ValBase = Val.slice(0, RefStepLoc);
210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211 OutStrings.push_back(Args.MakeArgString(Out + Val));
212 return;
213 }
214 }
215
216 // Each reciprocal type may be enabled or disabled individually.
217 // Check each input value for validity, concatenate them all back together,
218 // and pass through.
219
220 llvm::StringMap<bool> OptionStrings;
221 OptionStrings.insert(std::make_pair("divd", false));
222 OptionStrings.insert(std::make_pair("divf", false));
223 OptionStrings.insert(std::make_pair("vec-divd", false));
224 OptionStrings.insert(std::make_pair("vec-divf", false));
225 OptionStrings.insert(std::make_pair("sqrtd", false));
226 OptionStrings.insert(std::make_pair("sqrtf", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
229
230 for (unsigned i = 0; i != NumOptions; ++i) {
231 StringRef Val = A->getValue(i);
232
233 bool IsDisabled = Val.startswith(DisabledPrefixIn);
234 // Ignore the disablement token for string matching.
235 if (IsDisabled)
236 Val = Val.substr(1);
237
238 size_t RefStep;
239 if (!getRefinementStep(Val, D, *A, RefStep))
240 return;
241
242 StringRef ValBase = Val.slice(0, RefStep);
243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244 if (OptionIter == OptionStrings.end()) {
245 // Try again specifying float suffix.
246 OptionIter = OptionStrings.find(ValBase.str() + 'f');
247 if (OptionIter == OptionStrings.end()) {
248 // The input name did not match any known option string.
249 D.Diag(diag::err_drv_unknown_argument) << Val;
250 return;
251 }
252 // The option was specified without a float or double suffix.
253 // Make sure that the double entry was not already specified.
254 // The float entry will be checked below.
255 if (OptionStrings[ValBase.str() + 'd']) {
256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
257 return;
258 }
259 }
260
261 if (OptionIter->second == true) {
262 // Duplicate option specified.
263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
264 return;
265 }
266
267 // Mark the matched option as found. Do not allow duplicate specifiers.
268 OptionIter->second = true;
269
270 // If the precision was not specified, also mark the double entry as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd')
272 OptionStrings[ValBase.str() + 'd'] = true;
273
274 // Build the output string.
275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276 Out = Args.MakeArgString(Out + Prefix + Val);
277 if (i != NumOptions - 1)
278 Out = Args.MakeArgString(Out + ",");
279 }
280
281 OutStrings.push_back(Args.MakeArgString(Out));
282}
283
Craig Topper9a724aa2017-12-11 21:09:19 +0000284/// The -mprefer-vector-width option accepts either a positive integer
285/// or the string "none".
286static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287 ArgStringList &CmdArgs) {
288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
289 if (!A)
290 return;
291
292 StringRef Value = A->getValue();
293 if (Value == "none") {
294 CmdArgs.push_back("-mprefer-vector-width=none");
295 } else {
296 unsigned Width;
297 if (Value.getAsInteger(10, Width)) {
298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
299 return;
300 }
301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302 }
303}
304
David L. Jonesf561aba2017-03-08 01:02:16 +0000305static void getWebAssemblyTargetFeatures(const ArgList &Args,
306 std::vector<StringRef> &Features) {
307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
308}
309
David L. Jonesf561aba2017-03-08 01:02:16 +0000310static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
311 const ArgList &Args, ArgStringList &CmdArgs,
312 bool ForAS) {
313 const Driver &D = TC.getDriver();
314 std::vector<StringRef> Features;
315 switch (Triple.getArch()) {
316 default:
317 break;
318 case llvm::Triple::mips:
319 case llvm::Triple::mipsel:
320 case llvm::Triple::mips64:
321 case llvm::Triple::mips64el:
322 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
323 break;
324
325 case llvm::Triple::arm:
326 case llvm::Triple::armeb:
327 case llvm::Triple::thumb:
328 case llvm::Triple::thumbeb:
329 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
330 break;
331
332 case llvm::Triple::ppc:
333 case llvm::Triple::ppc64:
334 case llvm::Triple::ppc64le:
335 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
336 break;
Alex Bradbury71f45452018-01-11 13:36:56 +0000337 case llvm::Triple::riscv32:
338 case llvm::Triple::riscv64:
339 riscv::getRISCVTargetFeatures(D, Args, Features);
340 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000341 case llvm::Triple::systemz:
342 systemz::getSystemZTargetFeatures(Args, Features);
343 break;
344 case llvm::Triple::aarch64:
345 case llvm::Triple::aarch64_be:
Alex Lorenz9b20a992018-12-17 19:30:46 +0000346 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000347 break;
348 case llvm::Triple::x86:
349 case llvm::Triple::x86_64:
350 x86::getX86TargetFeatures(D, Triple, Args, Features);
351 break;
352 case llvm::Triple::hexagon:
Sumanth Gundapaneni57098f52017-10-18 18:10:13 +0000353 hexagon::getHexagonTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000354 break;
355 case llvm::Triple::wasm32:
356 case llvm::Triple::wasm64:
357 getWebAssemblyTargetFeatures(Args, Features);
358 break;
359 case llvm::Triple::sparc:
360 case llvm::Triple::sparcel:
361 case llvm::Triple::sparcv9:
362 sparc::getSparcTargetFeatures(D, Args, Features);
363 break;
364 case llvm::Triple::r600:
365 case llvm::Triple::amdgcn:
Konstantin Zhuravlyov8914a6d2017-11-10 19:09:57 +0000366 amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000367 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +0000368 case llvm::Triple::msp430:
369 msp430::getMSP430TargetFeatures(D, Args, Features);
David L. Jonesf561aba2017-03-08 01:02:16 +0000370 }
371
372 // Find the last of each feature.
373 llvm::StringMap<unsigned> LastOpt;
374 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
375 StringRef Name = Features[I];
376 assert(Name[0] == '-' || Name[0] == '+');
377 LastOpt[Name.drop_front(1)] = I;
378 }
379
380 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
381 // If this feature was overridden, ignore it.
382 StringRef Name = Features[I];
383 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
384 assert(LastI != LastOpt.end());
385 unsigned Last = LastI->second;
386 if (Last != I)
387 continue;
388
389 CmdArgs.push_back("-target-feature");
390 CmdArgs.push_back(Name.data());
391 }
392}
393
394static bool
395shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
396 const llvm::Triple &Triple) {
397 // We use the zero-cost exception tables for Objective-C if the non-fragile
398 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
399 // later.
400 if (runtime.isNonFragile())
401 return true;
402
403 if (!Triple.isMacOSX())
404 return false;
405
406 return (!Triple.isMacOSXVersionLT(10, 5) &&
407 (Triple.getArch() == llvm::Triple::x86_64 ||
408 Triple.getArch() == llvm::Triple::arm));
409}
410
411/// Adds exception related arguments to the driver command arguments. There's a
412/// master flag, -fexceptions and also language specific flags to enable/disable
413/// C++ and Objective-C exceptions. This makes it possible to for example
414/// disable C++ exceptions but enable Objective-C exceptions.
415static void addExceptionArgs(const ArgList &Args, types::ID InputType,
416 const ToolChain &TC, bool KernelOrKext,
417 const ObjCRuntime &objcRuntime,
418 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000419 const llvm::Triple &Triple = TC.getTriple();
420
421 if (KernelOrKext) {
422 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
423 // arguments now to avoid warnings about unused arguments.
424 Args.ClaimAllArgs(options::OPT_fexceptions);
425 Args.ClaimAllArgs(options::OPT_fno_exceptions);
426 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
427 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
428 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
429 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
430 return;
431 }
432
433 // See if the user explicitly enabled exceptions.
434 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
435 false);
436
437 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
438 // is not necessarily sensible, but follows GCC.
439 if (types::isObjC(InputType) &&
440 Args.hasFlag(options::OPT_fobjc_exceptions,
441 options::OPT_fno_objc_exceptions, true)) {
442 CmdArgs.push_back("-fobjc-exceptions");
443
444 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
445 }
446
447 if (types::isCXX(InputType)) {
448 // Disable C++ EH by default on XCore and PS4.
449 bool CXXExceptionsEnabled =
450 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
451 Arg *ExceptionArg = Args.getLastArg(
452 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
453 options::OPT_fexceptions, options::OPT_fno_exceptions);
454 if (ExceptionArg)
455 CXXExceptionsEnabled =
456 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
457 ExceptionArg->getOption().matches(options::OPT_fexceptions);
458
459 if (CXXExceptionsEnabled) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000460 CmdArgs.push_back("-fcxx-exceptions");
461
462 EH = true;
463 }
464 }
465
466 if (EH)
467 CmdArgs.push_back("-fexceptions");
468}
469
470static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
471 bool Default = true;
472 if (TC.getTriple().isOSDarwin()) {
473 // The native darwin assembler doesn't support the linker_option directives,
474 // so we disable them if we think the .s file will be passed to it.
475 Default = TC.useIntegratedAs();
476 }
477 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
478 Default);
479}
480
481static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482 const ToolChain &TC) {
483 bool UseDwarfDirectory =
484 Args.hasFlag(options::OPT_fdwarf_directory_asm,
485 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486 return !UseDwarfDirectory;
487}
488
489// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490// to the corresponding DebugInfoKind.
491static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492 assert(A.getOption().matches(options::OPT_gN_Group) &&
493 "Not a -g option that specifies a debug-info level");
494 if (A.getOption().matches(options::OPT_g0) ||
495 A.getOption().matches(options::OPT_ggdb0))
496 return codegenoptions::NoDebugInfo;
497 if (A.getOption().matches(options::OPT_gline_tables_only) ||
498 A.getOption().matches(options::OPT_ggdb1))
499 return codegenoptions::DebugLineTablesOnly;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000500 if (A.getOption().matches(options::OPT_gline_directives_only))
501 return codegenoptions::DebugDirectivesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +0000502 return codegenoptions::LimitedDebugInfo;
503}
504
505static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506 switch (Triple.getArch()){
507 default:
508 return false;
509 case llvm::Triple::arm:
510 case llvm::Triple::thumb:
511 // ARM Darwin targets require a frame pointer to be always present to aid
512 // offline debugging via backtraces.
513 return Triple.isOSDarwin();
514 }
515}
516
517static bool useFramePointerForTargetByDefault(const ArgList &Args,
518 const llvm::Triple &Triple) {
Fangrui Songdc039662019-07-12 02:01:51 +0000519 if (Args.hasArg(options::OPT_pg))
520 return true;
521
David L. Jonesf561aba2017-03-08 01:02:16 +0000522 switch (Triple.getArch()) {
523 case llvm::Triple::xcore:
524 case llvm::Triple::wasm32:
525 case llvm::Triple::wasm64:
Anton Korobeynikovf1f897c2019-02-05 20:15:03 +0000526 case llvm::Triple::msp430:
David L. Jonesf561aba2017-03-08 01:02:16 +0000527 // XCore never wants frame pointers, regardless of OS.
528 // WebAssembly never wants frame pointers.
529 return false;
Fangrui Song8c0b58f2019-07-12 02:14:08 +0000530 case llvm::Triple::ppc:
531 case llvm::Triple::ppc64:
532 case llvm::Triple::ppc64le:
Mandeep Singh Grang0c5300a2018-04-12 19:31:37 +0000533 case llvm::Triple::riscv32:
534 case llvm::Triple::riscv64:
535 return !areOptimizationsEnabled(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +0000536 default:
537 break;
538 }
539
Michal Gorny5a409d02018-12-20 13:09:30 +0000540 if (Triple.isOSNetBSD()) {
Joerg Sonnenberger2ad82102018-07-17 12:38:57 +0000541 return !areOptimizationsEnabled(Args);
542 }
543
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000544 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
545 Triple.isOSHurd()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000546 switch (Triple.getArch()) {
547 // Don't use a frame pointer on linux if optimizing for certain targets.
548 case llvm::Triple::mips64:
549 case llvm::Triple::mips64el:
550 case llvm::Triple::mips:
551 case llvm::Triple::mipsel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000552 case llvm::Triple::systemz:
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 return !areOptimizationsEnabled(Args);
556 default:
557 return true;
558 }
559 }
560
561 if (Triple.isOSWindows()) {
562 switch (Triple.getArch()) {
563 case llvm::Triple::x86:
564 return !areOptimizationsEnabled(Args);
565 case llvm::Triple::x86_64:
566 return Triple.isOSBinFormatMachO();
567 case llvm::Triple::arm:
568 case llvm::Triple::thumb:
569 // Windows on ARM builds with FPO disabled to aid fast stack walking
570 return true;
571 default:
572 // All other supported Windows ISAs use xdata unwind information, so frame
573 // pointers are not generally useful.
574 return false;
575 }
576 }
577
578 return true;
579}
580
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000581static CodeGenOptions::FramePointerKind
582getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
Fangrui Songdc039662019-07-12 02:01:51 +0000583 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
584 options::OPT_fno_omit_frame_pointer);
585 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
586 bool NoOmitFP =
587 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
588 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
589 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
590 if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
591 options::OPT_mno_omit_leaf_frame_pointer,
592 Triple.isPS4CPU()))
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000593 return CodeGenOptions::FramePointerKind::NonLeaf;
594 return CodeGenOptions::FramePointerKind::All;
Fangrui Songdc039662019-07-12 02:01:51 +0000595 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000596 return CodeGenOptions::FramePointerKind::None;
David L. Jonesf561aba2017-03-08 01:02:16 +0000597}
598
599/// Add a CC1 option to specify the debug compilation directory.
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000600static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
601 const llvm::vfs::FileSystem &VFS) {
Nico Weber37b75332019-06-17 12:10:40 +0000602 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
603 CmdArgs.push_back("-fdebug-compilation-dir");
604 CmdArgs.push_back(A->getValue());
605 } else if (llvm::ErrorOr<std::string> CWD =
606 VFS.getCurrentWorkingDirectory()) {
David L. Jonesf561aba2017-03-08 01:02:16 +0000607 CmdArgs.push_back("-fdebug-compilation-dir");
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000608 CmdArgs.push_back(Args.MakeArgString(*CWD));
David L. Jonesf561aba2017-03-08 01:02:16 +0000609 }
610}
611
Paul Robinson9b292b42018-07-10 15:15:24 +0000612/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
613static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
614 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
615 StringRef Map = A->getValue();
616 if (Map.find('=') == StringRef::npos)
617 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
618 else
619 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
620 A->claim();
621 }
622}
623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000624/// Vectorize at all optimization levels greater than 1 except for -Oz.
Nico Weber37b75332019-06-17 12:10:40 +0000625/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
626/// enabled.
David L. Jonesf561aba2017-03-08 01:02:16 +0000627static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
628 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
629 if (A->getOption().matches(options::OPT_O4) ||
630 A->getOption().matches(options::OPT_Ofast))
631 return true;
632
633 if (A->getOption().matches(options::OPT_O0))
634 return false;
635
636 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
637
638 // Vectorize -Os.
639 StringRef S(A->getValue());
640 if (S == "s")
641 return true;
642
643 // Don't vectorize -Oz, unless it's the slp vectorizer.
644 if (S == "z")
645 return isSlpVec;
646
647 unsigned OptLevel = 0;
648 if (S.getAsInteger(10, OptLevel))
649 return false;
650
651 return OptLevel > 1;
652 }
653
654 return false;
655}
656
657/// Add -x lang to \p CmdArgs for \p Input.
658static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
659 ArgStringList &CmdArgs) {
660 // When using -verify-pch, we don't want to provide the type
661 // 'precompiled-header' if it was inferred from the file extension
662 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
663 return;
664
665 CmdArgs.push_back("-x");
666 if (Args.hasArg(options::OPT_rewrite_objc))
667 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
Richard Smith34e485f2017-04-18 21:55:37 +0000668 else {
669 // Map the driver type to the frontend type. This is mostly an identity
670 // mapping, except that the distinction between module interface units
671 // and other source files does not exist at the frontend layer.
672 const char *ClangType;
673 switch (Input.getType()) {
674 case types::TY_CXXModule:
675 ClangType = "c++";
676 break;
677 case types::TY_PP_CXXModule:
678 ClangType = "c++-cpp-output";
679 break;
680 default:
681 ClangType = types::getTypeName(Input.getType());
682 break;
683 }
684 CmdArgs.push_back(ClangType);
685 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000686}
687
688static void appendUserToPath(SmallVectorImpl<char> &Result) {
689#ifdef LLVM_ON_UNIX
690 const char *Username = getenv("LOGNAME");
691#else
692 const char *Username = getenv("USERNAME");
693#endif
694 if (Username) {
695 // Validate that LoginName can be used in a path, and get its length.
696 size_t Len = 0;
697 for (const char *P = Username; *P; ++P, ++Len) {
698 if (!clang::isAlphanumeric(*P) && *P != '_') {
699 Username = nullptr;
700 break;
701 }
702 }
703
704 if (Username && Len > 0) {
705 Result.append(Username, Username + Len);
706 return;
707 }
708 }
709
710// Fallback to user id.
711#ifdef LLVM_ON_UNIX
712 std::string UID = llvm::utostr(getuid());
713#else
714 // FIXME: Windows seems to have an 'SID' that might work.
715 std::string UID = "9999";
716#endif
717 Result.append(UID.begin(), UID.end());
718}
719
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000720static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
721 const Driver &D, const InputInfo &Output,
722 const ArgList &Args,
David L. Jonesf561aba2017-03-08 01:02:16 +0000723 ArgStringList &CmdArgs) {
724
725 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726 options::OPT_fprofile_generate_EQ,
727 options::OPT_fno_profile_generate);
728 if (PGOGenerateArg &&
729 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730 PGOGenerateArg = nullptr;
731
Rong Xua4a09b22019-03-04 20:21:31 +0000732 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
733 options::OPT_fcs_profile_generate_EQ,
734 options::OPT_fno_profile_generate);
735 if (CSPGOGenerateArg &&
736 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
737 CSPGOGenerateArg = nullptr;
738
David L. Jonesf561aba2017-03-08 01:02:16 +0000739 auto *ProfileGenerateArg = Args.getLastArg(
740 options::OPT_fprofile_instr_generate,
741 options::OPT_fprofile_instr_generate_EQ,
742 options::OPT_fno_profile_instr_generate);
743 if (ProfileGenerateArg &&
744 ProfileGenerateArg->getOption().matches(
745 options::OPT_fno_profile_instr_generate))
746 ProfileGenerateArg = nullptr;
747
748 if (PGOGenerateArg && ProfileGenerateArg)
749 D.Diag(diag::err_drv_argument_not_allowed_with)
750 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
751
752 auto *ProfileUseArg = getLastProfileUseArg(Args);
753
754 if (PGOGenerateArg && ProfileUseArg)
755 D.Diag(diag::err_drv_argument_not_allowed_with)
756 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
757
758 if (ProfileGenerateArg && ProfileUseArg)
759 D.Diag(diag::err_drv_argument_not_allowed_with)
760 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
761
Rong Xua4a09b22019-03-04 20:21:31 +0000762 if (CSPGOGenerateArg && PGOGenerateArg)
763 D.Diag(diag::err_drv_argument_not_allowed_with)
764 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
765
David L. Jonesf561aba2017-03-08 01:02:16 +0000766 if (ProfileGenerateArg) {
767 if (ProfileGenerateArg->getOption().matches(
768 options::OPT_fprofile_instr_generate_EQ))
769 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
770 ProfileGenerateArg->getValue()));
771 // The default is to use Clang Instrumentation.
772 CmdArgs.push_back("-fprofile-instrument=clang");
Russell Gallop7a9ccf82019-05-14 14:01:40 +0000773 if (TC.getTriple().isWindowsMSVCEnvironment()) {
774 // Add dependent lib for clang_rt.profile
775 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
776 TC.getCompilerRT(Args, "profile")));
777 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000778 }
779
Rong Xua4a09b22019-03-04 20:21:31 +0000780 Arg *PGOGenArg = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +0000781 if (PGOGenerateArg) {
Rong Xua4a09b22019-03-04 20:21:31 +0000782 assert(!CSPGOGenerateArg);
783 PGOGenArg = PGOGenerateArg;
David L. Jonesf561aba2017-03-08 01:02:16 +0000784 CmdArgs.push_back("-fprofile-instrument=llvm");
Rong Xua4a09b22019-03-04 20:21:31 +0000785 }
786 if (CSPGOGenerateArg) {
787 assert(!PGOGenerateArg);
788 PGOGenArg = CSPGOGenerateArg;
789 CmdArgs.push_back("-fprofile-instrument=csllvm");
790 }
791 if (PGOGenArg) {
Russell Gallop72fea1d2019-05-22 10:06:49 +0000792 if (TC.getTriple().isWindowsMSVCEnvironment()) {
793 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
794 TC.getCompilerRT(Args, "profile")));
795 }
Rong Xua4a09b22019-03-04 20:21:31 +0000796 if (PGOGenArg->getOption().matches(
797 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
798 : options::OPT_fcs_profile_generate_EQ)) {
799 SmallString<128> Path(PGOGenArg->getValue());
David L. Jonesf561aba2017-03-08 01:02:16 +0000800 llvm::sys::path::append(Path, "default_%m.profraw");
801 CmdArgs.push_back(
802 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
803 }
804 }
805
806 if (ProfileUseArg) {
807 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
808 CmdArgs.push_back(Args.MakeArgString(
809 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
810 else if ((ProfileUseArg->getOption().matches(
811 options::OPT_fprofile_use_EQ) ||
812 ProfileUseArg->getOption().matches(
813 options::OPT_fprofile_instr_use))) {
814 SmallString<128> Path(
815 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
816 if (Path.empty() || llvm::sys::fs::is_directory(Path))
817 llvm::sys::path::append(Path, "default.profdata");
818 CmdArgs.push_back(
819 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
820 }
821 }
822
823 if (Args.hasArg(options::OPT_ftest_coverage) ||
824 Args.hasArg(options::OPT_coverage))
825 CmdArgs.push_back("-femit-coverage-notes");
826 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
827 false) ||
828 Args.hasArg(options::OPT_coverage))
829 CmdArgs.push_back("-femit-coverage-data");
830
831 if (Args.hasFlag(options::OPT_fcoverage_mapping,
Vedant Kumar99b31292017-06-28 01:56:07 +0000832 options::OPT_fno_coverage_mapping, false)) {
833 if (!ProfileGenerateArg)
834 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
835 << "-fcoverage-mapping"
836 << "-fprofile-instr-generate";
David L. Jonesf561aba2017-03-08 01:02:16 +0000837
David L. Jonesf561aba2017-03-08 01:02:16 +0000838 CmdArgs.push_back("-fcoverage-mapping");
Vedant Kumar99b31292017-06-28 01:56:07 +0000839 }
David L. Jonesf561aba2017-03-08 01:02:16 +0000840
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000841 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
842 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
843 if (!Args.hasArg(options::OPT_coverage))
844 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
845 << "-fprofile-exclude-files="
846 << "--coverage";
847
848 StringRef v = Arg->getValue();
849 CmdArgs.push_back(
850 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
851 }
852
853 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
854 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
855 if (!Args.hasArg(options::OPT_coverage))
856 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
857 << "-fprofile-filter-files="
858 << "--coverage";
859
860 StringRef v = Arg->getValue();
861 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
862 }
863
David L. Jonesf561aba2017-03-08 01:02:16 +0000864 if (C.getArgs().hasArg(options::OPT_c) ||
865 C.getArgs().hasArg(options::OPT_S)) {
866 if (Output.isFilename()) {
867 CmdArgs.push_back("-coverage-notes-file");
868 SmallString<128> OutputFilename;
869 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
870 OutputFilename = FinalOutput->getValue();
871 else
872 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
873 SmallString<128> CoverageFilename = OutputFilename;
Michael J. Spencer7e48b402019-05-28 22:21:47 +0000874 if (llvm::sys::path::is_relative(CoverageFilename))
875 (void)D.getVFS().makeAbsolute(CoverageFilename);
David L. Jonesf561aba2017-03-08 01:02:16 +0000876 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
877 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
878
879 // Leave -fprofile-dir= an unused argument unless .gcda emission is
880 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
881 // the flag used. There is no -fno-profile-dir, so the user has no
882 // targeted way to suppress the warning.
883 if (Args.hasArg(options::OPT_fprofile_arcs) ||
884 Args.hasArg(options::OPT_coverage)) {
885 CmdArgs.push_back("-coverage-data-file");
886 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
887 CoverageFilename = FProfileDir->getValue();
888 llvm::sys::path::append(CoverageFilename, OutputFilename);
889 }
890 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
891 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
892 }
893 }
894 }
895}
896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000897/// Check whether the given input tree contains any compilation actions.
David L. Jonesf561aba2017-03-08 01:02:16 +0000898static bool ContainsCompileAction(const Action *A) {
899 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
900 return true;
901
902 for (const auto &AI : A->inputs())
903 if (ContainsCompileAction(AI))
904 return true;
905
906 return false;
907}
908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000909/// Check if -relax-all should be passed to the internal assembler.
David L. Jonesf561aba2017-03-08 01:02:16 +0000910/// This is done by default when compiling non-assembler source with -O0.
911static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
912 bool RelaxDefault = true;
913
914 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
915 RelaxDefault = A->getOption().matches(options::OPT_O0);
916
917 if (RelaxDefault) {
918 RelaxDefault = false;
919 for (const auto &Act : C.getActions()) {
920 if (ContainsCompileAction(Act)) {
921 RelaxDefault = true;
922 break;
923 }
924 }
925 }
926
927 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
928 RelaxDefault);
929}
930
931// Extract the integer N from a string spelled "-dwarf-N", returning 0
932// on mismatch. The StringRef input (rather than an Arg) allows
933// for use by the "-Xassembler" option parser.
934static unsigned DwarfVersionNum(StringRef ArgValue) {
935 return llvm::StringSwitch<unsigned>(ArgValue)
936 .Case("-gdwarf-2", 2)
937 .Case("-gdwarf-3", 3)
938 .Case("-gdwarf-4", 4)
939 .Case("-gdwarf-5", 5)
940 .Default(0);
941}
942
943static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
944 codegenoptions::DebugInfoKind DebugInfoKind,
945 unsigned DwarfVersion,
946 llvm::DebuggerKind DebuggerTuning) {
947 switch (DebugInfoKind) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000948 case codegenoptions::DebugDirectivesOnly:
949 CmdArgs.push_back("-debug-info-kind=line-directives-only");
950 break;
David L. Jonesf561aba2017-03-08 01:02:16 +0000951 case codegenoptions::DebugLineTablesOnly:
952 CmdArgs.push_back("-debug-info-kind=line-tables-only");
953 break;
954 case codegenoptions::LimitedDebugInfo:
955 CmdArgs.push_back("-debug-info-kind=limited");
956 break;
957 case codegenoptions::FullDebugInfo:
958 CmdArgs.push_back("-debug-info-kind=standalone");
959 break;
960 default:
961 break;
962 }
963 if (DwarfVersion > 0)
964 CmdArgs.push_back(
965 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
966 switch (DebuggerTuning) {
967 case llvm::DebuggerKind::GDB:
968 CmdArgs.push_back("-debugger-tuning=gdb");
969 break;
970 case llvm::DebuggerKind::LLDB:
971 CmdArgs.push_back("-debugger-tuning=lldb");
972 break;
973 case llvm::DebuggerKind::SCE:
974 CmdArgs.push_back("-debugger-tuning=sce");
975 break;
976 default:
977 break;
978 }
979}
980
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000981static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
982 const Driver &D, const ToolChain &TC) {
983 assert(A && "Expected non-nullptr argument.");
984 if (TC.supportsDebugInfoOption(A))
985 return true;
986 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
987 << A->getAsString(Args) << TC.getTripleString();
988 return false;
989}
990
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000991static void RenderDebugInfoCompressionArgs(const ArgList &Args,
992 ArgStringList &CmdArgs,
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000993 const Driver &D,
994 const ToolChain &TC) {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000995 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
996 if (!A)
997 return;
Alexey Bataevb83b4e42018-07-27 19:45:14 +0000998 if (checkDebugInfoOption(A, Args, D, TC)) {
999 if (A->getOption().getID() == options::OPT_gz) {
1000 if (llvm::zlib::isAvailable())
Fangrui Songbaabc872019-05-11 01:14:50 +00001001 CmdArgs.push_back("--compress-debug-sections");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001002 else
1003 D.Diag(diag::warn_debug_compression_unavailable);
1004 return;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001005 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001006
1007 StringRef Value = A->getValue();
1008 if (Value == "none") {
Fangrui Songbaabc872019-05-11 01:14:50 +00001009 CmdArgs.push_back("--compress-debug-sections=none");
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001010 } else if (Value == "zlib" || Value == "zlib-gnu") {
1011 if (llvm::zlib::isAvailable()) {
1012 CmdArgs.push_back(
Fangrui Songbaabc872019-05-11 01:14:50 +00001013 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
Alexey Bataevb83b4e42018-07-27 19:45:14 +00001014 } else {
1015 D.Diag(diag::warn_debug_compression_unavailable);
1016 }
1017 } else {
1018 D.Diag(diag::err_drv_unsupported_option_argument)
1019 << A->getOption().getName() << Value;
1020 }
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001021 }
1022}
1023
David L. Jonesf561aba2017-03-08 01:02:16 +00001024static const char *RelocationModelName(llvm::Reloc::Model Model) {
1025 switch (Model) {
1026 case llvm::Reloc::Static:
1027 return "static";
1028 case llvm::Reloc::PIC_:
1029 return "pic";
1030 case llvm::Reloc::DynamicNoPIC:
1031 return "dynamic-no-pic";
1032 case llvm::Reloc::ROPI:
1033 return "ropi";
1034 case llvm::Reloc::RWPI:
1035 return "rwpi";
1036 case llvm::Reloc::ROPI_RWPI:
1037 return "ropi-rwpi";
1038 }
1039 llvm_unreachable("Unknown Reloc::Model kind");
1040}
1041
1042void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1043 const Driver &D, const ArgList &Args,
1044 ArgStringList &CmdArgs,
1045 const InputInfo &Output,
1046 const InputInfoList &Inputs) const {
1047 Arg *A;
1048 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1049
1050 CheckPreprocessingOptions(D, Args);
1051
1052 Args.AddLastArg(CmdArgs, options::OPT_C);
1053 Args.AddLastArg(CmdArgs, options::OPT_CC);
1054
1055 // Handle dependency file generation.
1056 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1057 (A = Args.getLastArg(options::OPT_MD)) ||
1058 (A = Args.getLastArg(options::OPT_MMD))) {
1059 // Determine the output location.
1060 const char *DepFile;
1061 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1062 DepFile = MF->getValue();
1063 C.addFailureResultFile(DepFile, &JA);
1064 } else if (Output.getType() == types::TY_Dependencies) {
1065 DepFile = Output.getFilename();
1066 } else if (A->getOption().matches(options::OPT_M) ||
1067 A->getOption().matches(options::OPT_MM)) {
1068 DepFile = "-";
1069 } else {
1070 DepFile = getDependencyFileName(Args, Inputs);
1071 C.addFailureResultFile(DepFile, &JA);
1072 }
1073 CmdArgs.push_back("-dependency-file");
1074 CmdArgs.push_back(DepFile);
1075
1076 // Add a default target if one wasn't specified.
1077 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1078 const char *DepTarget;
1079
1080 // If user provided -o, that is the dependency target, except
1081 // when we are only generating a dependency file.
1082 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1083 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1084 DepTarget = OutputOpt->getValue();
1085 } else {
1086 // Otherwise derive from the base input.
1087 //
1088 // FIXME: This should use the computed output file location.
1089 SmallString<128> P(Inputs[0].getBaseInput());
1090 llvm::sys::path::replace_extension(P, "o");
1091 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1092 }
1093
Yuka Takahashicdb53482017-06-16 16:01:13 +00001094 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1095 CmdArgs.push_back("-w");
1096 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001097 CmdArgs.push_back("-MT");
1098 SmallString<128> Quoted;
1099 QuoteTarget(DepTarget, Quoted);
1100 CmdArgs.push_back(Args.MakeArgString(Quoted));
1101 }
1102
1103 if (A->getOption().matches(options::OPT_M) ||
1104 A->getOption().matches(options::OPT_MD))
1105 CmdArgs.push_back("-sys-header-deps");
1106 if ((isa<PrecompileJobAction>(JA) &&
1107 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1108 Args.hasArg(options::OPT_fmodule_file_deps))
1109 CmdArgs.push_back("-module-file-deps");
1110 }
1111
1112 if (Args.hasArg(options::OPT_MG)) {
1113 if (!A || A->getOption().matches(options::OPT_MD) ||
1114 A->getOption().matches(options::OPT_MMD))
1115 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1116 CmdArgs.push_back("-MG");
1117 }
1118
1119 Args.AddLastArg(CmdArgs, options::OPT_MP);
1120 Args.AddLastArg(CmdArgs, options::OPT_MV);
1121
1122 // Convert all -MQ <target> args to -MT <quoted target>
1123 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1124 A->claim();
1125
1126 if (A->getOption().matches(options::OPT_MQ)) {
1127 CmdArgs.push_back("-MT");
1128 SmallString<128> Quoted;
1129 QuoteTarget(A->getValue(), Quoted);
1130 CmdArgs.push_back(Args.MakeArgString(Quoted));
1131
1132 // -MT flag - no change
1133 } else {
1134 A->render(Args, CmdArgs);
1135 }
1136 }
1137
1138 // Add offload include arguments specific for CUDA. This must happen before
1139 // we -I or -include anything else, because we must pick up the CUDA headers
1140 // from the particular CUDA installation, rather than from e.g.
1141 // /usr/local/include.
1142 if (JA.isOffloading(Action::OFK_Cuda))
1143 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1144
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001145 // If we are offloading to a target via OpenMP we need to include the
1146 // openmp_wrappers folder which contains alternative system headers.
1147 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1148 getToolChain().getTriple().isNVPTX()){
1149 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1150 // Add openmp_wrappers/* to our system include path. This lets us wrap
1151 // standard library headers.
1152 SmallString<128> P(D.ResourceDir);
1153 llvm::sys::path::append(P, "include");
1154 llvm::sys::path::append(P, "openmp_wrappers");
1155 CmdArgs.push_back("-internal-isystem");
1156 CmdArgs.push_back(Args.MakeArgString(P));
1157 }
1158
1159 CmdArgs.push_back("-include");
Gheorghe-Teodor Bercea94695712019-05-13 22:11:44 +00001160 CmdArgs.push_back("__clang_openmp_math_declares.h");
Gheorghe-Teodor Berceae62c6932019-05-08 15:52:33 +00001161 }
1162
David L. Jonesf561aba2017-03-08 01:02:16 +00001163 // Add -i* options, and automatically translate to
1164 // -include-pch/-include-pth for transparent PCH support. It's
1165 // wonky, but we include looking for .gch so we can support seamless
1166 // replacement into a build system already set up to be generating
1167 // .gch files.
Erich Keane76675de2018-07-05 17:22:13 +00001168
1169 if (getToolChain().getDriver().IsCLMode()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001170 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1171 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Erich Keane76675de2018-07-05 17:22:13 +00001172 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1173 JA.getKind() <= Action::AssembleJobClass) {
1174 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001175 }
Erich Keane76675de2018-07-05 17:22:13 +00001176 if (YcArg || YuArg) {
1177 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1178 if (!isa<PrecompileJobAction>(JA)) {
1179 CmdArgs.push_back("-include-pch");
Mike Rice58df1af2018-09-11 17:10:44 +00001180 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1181 C, !ThroughHeader.empty()
1182 ? ThroughHeader
1183 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
Erich Keane76675de2018-07-05 17:22:13 +00001184 }
Mike Rice58df1af2018-09-11 17:10:44 +00001185
1186 if (ThroughHeader.empty()) {
1187 CmdArgs.push_back(Args.MakeArgString(
1188 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1189 } else {
1190 CmdArgs.push_back(
1191 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1192 }
Erich Keane76675de2018-07-05 17:22:13 +00001193 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001194 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001195
1196 bool RenderedImplicitInclude = false;
David L. Jonesf561aba2017-03-08 01:02:16 +00001197 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
Erich Keane76675de2018-07-05 17:22:13 +00001198 if (A->getOption().matches(options::OPT_include)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001199 // Handling of gcc-style gch precompiled headers.
1200 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1201 RenderedImplicitInclude = true;
1202
David L. Jonesf561aba2017-03-08 01:02:16 +00001203 bool FoundPCH = false;
1204 SmallString<128> P(A->getValue());
1205 // We want the files to have a name like foo.h.pch. Add a dummy extension
1206 // so that replace_extension does the right thing.
1207 P += ".dummy";
Erich Keane0a6b5b62018-12-04 14:34:09 +00001208 llvm::sys::path::replace_extension(P, "pch");
1209 if (llvm::sys::fs::exists(P))
1210 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001211
1212 if (!FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001213 llvm::sys::path::replace_extension(P, "gch");
1214 if (llvm::sys::fs::exists(P)) {
Erich Keane0a6b5b62018-12-04 14:34:09 +00001215 FoundPCH = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001216 }
1217 }
1218
Erich Keane0a6b5b62018-12-04 14:34:09 +00001219 if (FoundPCH) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001220 if (IsFirstImplicitInclude) {
1221 A->claim();
Erich Keane0a6b5b62018-12-04 14:34:09 +00001222 CmdArgs.push_back("-include-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00001223 CmdArgs.push_back(Args.MakeArgString(P));
1224 continue;
1225 } else {
1226 // Ignore the PCH if not first on command line and emit warning.
1227 D.Diag(diag::warn_drv_pch_not_first_include) << P
1228 << A->getAsString(Args);
1229 }
1230 }
1231 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1232 // Handling of paths which must come late. These entries are handled by
1233 // the toolchain itself after the resource dir is inserted in the right
1234 // search order.
1235 // Do not claim the argument so that the use of the argument does not
1236 // silently go unnoticed on toolchains which do not honour the option.
1237 continue;
1238 }
1239
1240 // Not translated, render as usual.
1241 A->claim();
1242 A->render(Args, CmdArgs);
1243 }
1244
1245 Args.AddAllArgs(CmdArgs,
1246 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1247 options::OPT_F, options::OPT_index_header_map});
1248
1249 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1250
1251 // FIXME: There is a very unfortunate problem here, some troubled
1252 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1253 // really support that we would have to parse and then translate
1254 // those options. :(
1255 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1256 options::OPT_Xpreprocessor);
1257
1258 // -I- is a deprecated GCC feature, reject it.
1259 if (Arg *A = Args.getLastArg(options::OPT_I_))
1260 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1261
1262 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1263 // -isysroot to the CC1 invocation.
1264 StringRef sysroot = C.getSysRoot();
1265 if (sysroot != "") {
1266 if (!Args.hasArg(options::OPT_isysroot)) {
1267 CmdArgs.push_back("-isysroot");
1268 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1269 }
1270 }
1271
1272 // Parse additional include paths from environment variables.
1273 // FIXME: We should probably sink the logic for handling these from the
1274 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1275 // CPATH - included following the user specified includes (but prior to
1276 // builtin and standard includes).
1277 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1278 // C_INCLUDE_PATH - system includes enabled when compiling C.
1279 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1280 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1281 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1282 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1283 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1284 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1285 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1286
1287 // While adding the include arguments, we also attempt to retrieve the
1288 // arguments of related offloading toolchains or arguments that are specific
1289 // of an offloading programming model.
1290
1291 // Add C++ include arguments, if needed.
1292 if (types::isCXX(Inputs[0].getType()))
1293 forAllAssociatedToolChains(C, JA, getToolChain(),
1294 [&Args, &CmdArgs](const ToolChain &TC) {
1295 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1296 });
1297
1298 // Add system include arguments for all targets but IAMCU.
1299 if (!IsIAMCU)
1300 forAllAssociatedToolChains(C, JA, getToolChain(),
1301 [&Args, &CmdArgs](const ToolChain &TC) {
1302 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1303 });
1304 else {
1305 // For IAMCU add special include arguments.
1306 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1307 }
1308}
1309
1310// FIXME: Move to target hook.
1311static bool isSignedCharDefault(const llvm::Triple &Triple) {
1312 switch (Triple.getArch()) {
1313 default:
1314 return true;
1315
1316 case llvm::Triple::aarch64:
1317 case llvm::Triple::aarch64_be:
1318 case llvm::Triple::arm:
1319 case llvm::Triple::armeb:
1320 case llvm::Triple::thumb:
1321 case llvm::Triple::thumbeb:
1322 if (Triple.isOSDarwin() || Triple.isOSWindows())
1323 return true;
1324 return false;
1325
1326 case llvm::Triple::ppc:
1327 case llvm::Triple::ppc64:
1328 if (Triple.isOSDarwin())
1329 return true;
1330 return false;
1331
1332 case llvm::Triple::hexagon:
1333 case llvm::Triple::ppc64le:
Alex Bradbury71f45452018-01-11 13:36:56 +00001334 case llvm::Triple::riscv32:
1335 case llvm::Triple::riscv64:
David L. Jonesf561aba2017-03-08 01:02:16 +00001336 case llvm::Triple::systemz:
1337 case llvm::Triple::xcore:
1338 return false;
1339 }
1340}
1341
1342static bool isNoCommonDefault(const llvm::Triple &Triple) {
1343 switch (Triple.getArch()) {
1344 default:
Petr Hosekbf45ece2018-02-23 20:10:14 +00001345 if (Triple.isOSFuchsia())
1346 return true;
David L. Jonesf561aba2017-03-08 01:02:16 +00001347 return false;
1348
1349 case llvm::Triple::xcore:
1350 case llvm::Triple::wasm32:
1351 case llvm::Triple::wasm64:
1352 return true;
1353 }
1354}
1355
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001356namespace {
1357void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1358 ArgStringList &CmdArgs) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001359 // Select the ABI to use.
1360 // FIXME: Support -meabi.
1361 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1362 const char *ABIName = nullptr;
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001363 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001364 ABIName = A->getValue();
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001365 } else {
Daniel Jasperd27538a2017-06-30 08:02:37 +00001366 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
Eric Christopher53b2cb72017-06-30 00:03:56 +00001367 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
David L. Jonesf561aba2017-03-08 01:02:16 +00001368 }
Eric Christopher53b2cb72017-06-30 00:03:56 +00001369
David L. Jonesf561aba2017-03-08 01:02:16 +00001370 CmdArgs.push_back("-target-abi");
1371 CmdArgs.push_back(ABIName);
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001372}
1373}
1374
1375void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1376 ArgStringList &CmdArgs, bool KernelOrKext) const {
1377 RenderARMABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001378
1379 // Determine floating point ABI from the options & target defaults.
1380 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1381 if (ABI == arm::FloatABI::Soft) {
1382 // Floating point operations and argument passing are soft.
1383 // FIXME: This changes CPP defines, we need -target-soft-float.
1384 CmdArgs.push_back("-msoft-float");
1385 CmdArgs.push_back("-mfloat-abi");
1386 CmdArgs.push_back("soft");
1387 } else if (ABI == arm::FloatABI::SoftFP) {
1388 // Floating point operations are hard, but argument passing is soft.
1389 CmdArgs.push_back("-mfloat-abi");
1390 CmdArgs.push_back("soft");
1391 } else {
1392 // Floating point operations and argument passing are hard.
1393 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1394 CmdArgs.push_back("-mfloat-abi");
1395 CmdArgs.push_back("hard");
1396 }
1397
1398 // Forward the -mglobal-merge option for explicit control over the pass.
1399 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1400 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001401 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001402 if (A->getOption().matches(options::OPT_mno_global_merge))
1403 CmdArgs.push_back("-arm-global-merge=false");
1404 else
1405 CmdArgs.push_back("-arm-global-merge=true");
1406 }
1407
1408 if (!Args.hasFlag(options::OPT_mimplicit_float,
1409 options::OPT_mno_implicit_float, true))
1410 CmdArgs.push_back("-no-implicit-float");
Javed Absar603a2ba2019-05-21 14:21:26 +00001411
1412 if (Args.getLastArg(options::OPT_mcmse))
1413 CmdArgs.push_back("-mcmse");
David L. Jonesf561aba2017-03-08 01:02:16 +00001414}
1415
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001416void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1417 const ArgList &Args, bool KernelOrKext,
1418 ArgStringList &CmdArgs) const {
1419 const ToolChain &TC = getToolChain();
1420
1421 // Add the target features
1422 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1423
1424 // Add target specific flags.
1425 switch (TC.getArch()) {
1426 default:
1427 break;
1428
1429 case llvm::Triple::arm:
1430 case llvm::Triple::armeb:
1431 case llvm::Triple::thumb:
1432 case llvm::Triple::thumbeb:
1433 // Use the effective triple, which takes into account the deployment target.
1434 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1435 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1436 break;
1437
1438 case llvm::Triple::aarch64:
1439 case llvm::Triple::aarch64_be:
1440 AddAArch64TargetArgs(Args, CmdArgs);
1441 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1442 break;
1443
1444 case llvm::Triple::mips:
1445 case llvm::Triple::mipsel:
1446 case llvm::Triple::mips64:
1447 case llvm::Triple::mips64el:
1448 AddMIPSTargetArgs(Args, CmdArgs);
1449 break;
1450
1451 case llvm::Triple::ppc:
1452 case llvm::Triple::ppc64:
1453 case llvm::Triple::ppc64le:
1454 AddPPCTargetArgs(Args, CmdArgs);
1455 break;
1456
Alex Bradbury71f45452018-01-11 13:36:56 +00001457 case llvm::Triple::riscv32:
1458 case llvm::Triple::riscv64:
1459 AddRISCVTargetArgs(Args, CmdArgs);
1460 break;
1461
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00001462 case llvm::Triple::sparc:
1463 case llvm::Triple::sparcel:
1464 case llvm::Triple::sparcv9:
1465 AddSparcTargetArgs(Args, CmdArgs);
1466 break;
1467
1468 case llvm::Triple::systemz:
1469 AddSystemZTargetArgs(Args, CmdArgs);
1470 break;
1471
1472 case llvm::Triple::x86:
1473 case llvm::Triple::x86_64:
1474 AddX86TargetArgs(Args, CmdArgs);
1475 break;
1476
1477 case llvm::Triple::lanai:
1478 AddLanaiTargetArgs(Args, CmdArgs);
1479 break;
1480
1481 case llvm::Triple::hexagon:
1482 AddHexagonTargetArgs(Args, CmdArgs);
1483 break;
1484
1485 case llvm::Triple::wasm32:
1486 case llvm::Triple::wasm64:
1487 AddWebAssemblyTargetArgs(Args, CmdArgs);
1488 break;
1489 }
1490}
1491
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001492// Parse -mbranch-protection=<protection>[+<protection>]* where
1493// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1494// Returns a triple of (return address signing Scope, signing key, require
1495// landing pads)
1496static std::tuple<StringRef, StringRef, bool>
1497ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1498 const Arg *A) {
1499 StringRef Scope = "none";
1500 StringRef Key = "a_key";
1501 bool IndirectBranches = false;
1502
1503 StringRef Value = A->getValue();
1504 // This maps onto -mbranch-protection=<scope>+<key>
1505
1506 if (Value.equals("standard")) {
1507 Scope = "non-leaf";
1508 Key = "a_key";
1509 IndirectBranches = true;
1510
1511 } else if (!Value.equals("none")) {
1512 SmallVector<StringRef, 4> BranchProtection;
1513 StringRef(A->getValue()).split(BranchProtection, '+');
1514
1515 auto Protection = BranchProtection.begin();
1516 while (Protection != BranchProtection.end()) {
1517 if (Protection->equals("bti"))
1518 IndirectBranches = true;
1519 else if (Protection->equals("pac-ret")) {
1520 Scope = "non-leaf";
1521 while (++Protection != BranchProtection.end()) {
1522 // Inner loop as "leaf" and "b-key" options must only appear attached
1523 // to pac-ret.
1524 if (Protection->equals("leaf"))
1525 Scope = "all";
1526 else if (Protection->equals("b-key"))
1527 Key = "b_key";
1528 else
1529 break;
1530 }
1531 Protection--;
1532 } else
1533 D.Diag(diag::err_invalid_branch_protection)
1534 << *Protection << A->getAsString(Args);
1535 Protection++;
1536 }
1537 }
1538
1539 return std::make_tuple(Scope, Key, IndirectBranches);
1540}
1541
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001542namespace {
1543void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1544 ArgStringList &CmdArgs) {
1545 const char *ABIName = nullptr;
1546 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1547 ABIName = A->getValue();
1548 else if (Triple.isOSDarwin())
1549 ABIName = "darwinpcs";
1550 else
1551 ABIName = "aapcs";
1552
1553 CmdArgs.push_back("-target-abi");
1554 CmdArgs.push_back(ABIName);
1555}
1556}
1557
David L. Jonesf561aba2017-03-08 01:02:16 +00001558void Clang::AddAArch64TargetArgs(const ArgList &Args,
1559 ArgStringList &CmdArgs) const {
1560 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1561
1562 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1563 Args.hasArg(options::OPT_mkernel) ||
1564 Args.hasArg(options::OPT_fapple_kext))
1565 CmdArgs.push_back("-disable-red-zone");
1566
1567 if (!Args.hasFlag(options::OPT_mimplicit_float,
1568 options::OPT_mno_implicit_float, true))
1569 CmdArgs.push_back("-no-implicit-float");
1570
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00001571 RenderAArch64ABI(Triple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00001572
1573 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1574 options::OPT_mno_fix_cortex_a53_835769)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001575 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001576 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1577 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1578 else
1579 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1580 } else if (Triple.isAndroid()) {
1581 // Enabled A53 errata (835769) workaround by default on android
Eli Friedman01d349b2018-04-12 22:21:36 +00001582 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001583 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1584 }
1585
1586 // Forward the -mglobal-merge option for explicit control over the pass.
1587 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1588 options::OPT_mno_global_merge)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00001589 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00001590 if (A->getOption().matches(options::OPT_mno_global_merge))
1591 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1592 else
1593 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1594 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001595
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001596 // Enable/disable return address signing and indirect branch targets.
1597 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1598 options::OPT_mbranch_protection_EQ)) {
1599
1600 const Driver &D = getToolChain().getDriver();
1601
1602 StringRef Scope, Key;
1603 bool IndirectBranches;
1604
1605 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1606 Scope = A->getValue();
1607 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1608 !Scope.equals("all"))
1609 D.Diag(diag::err_invalid_branch_protection)
1610 << Scope << A->getAsString(Args);
1611 Key = "a_key";
1612 IndirectBranches = false;
1613 } else
1614 std::tie(Scope, Key, IndirectBranches) =
1615 ParseAArch64BranchProtection(D, Args, A);
1616
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001617 CmdArgs.push_back(
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001618 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1619 CmdArgs.push_back(
1620 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1621 if (IndirectBranches)
1622 CmdArgs.push_back("-mbranch-target-enforce");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001623 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001624}
1625
1626void Clang::AddMIPSTargetArgs(const ArgList &Args,
1627 ArgStringList &CmdArgs) const {
1628 const Driver &D = getToolChain().getDriver();
1629 StringRef CPUName;
1630 StringRef ABIName;
1631 const llvm::Triple &Triple = getToolChain().getTriple();
1632 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1633
1634 CmdArgs.push_back("-target-abi");
1635 CmdArgs.push_back(ABIName.data());
1636
1637 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1638 if (ABI == mips::FloatABI::Soft) {
1639 // Floating point operations and argument passing are soft.
1640 CmdArgs.push_back("-msoft-float");
1641 CmdArgs.push_back("-mfloat-abi");
1642 CmdArgs.push_back("soft");
1643 } else {
1644 // Floating point operations and argument passing are hard.
1645 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1646 CmdArgs.push_back("-mfloat-abi");
1647 CmdArgs.push_back("hard");
1648 }
1649
1650 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1651 if (A->getOption().matches(options::OPT_mxgot)) {
1652 CmdArgs.push_back("-mllvm");
1653 CmdArgs.push_back("-mxgot");
1654 }
1655 }
1656
1657 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1658 options::OPT_mno_ldc1_sdc1)) {
1659 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1660 CmdArgs.push_back("-mllvm");
1661 CmdArgs.push_back("-mno-ldc1-sdc1");
1662 }
1663 }
1664
1665 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1666 options::OPT_mno_check_zero_division)) {
1667 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1668 CmdArgs.push_back("-mllvm");
1669 CmdArgs.push_back("-mno-check-zero-division");
1670 }
1671 }
1672
1673 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1674 StringRef v = A->getValue();
1675 CmdArgs.push_back("-mllvm");
1676 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1677 A->claim();
1678 }
1679
Simon Dardis31636a12017-07-20 14:04:12 +00001680 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1681 Arg *ABICalls =
1682 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1683
1684 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1685 // -mgpopt is the default for static, -fno-pic environments but these two
1686 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1687 // the only case where -mllvm -mgpopt is passed.
1688 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1689 // passed explicitly when compiling something with -mabicalls
1690 // (implictly) in affect. Currently the warning is in the backend.
Simon Dardisad9d05d2017-08-11 15:01:34 +00001691 //
1692 // When the ABI in use is N64, we also need to determine the PIC mode that
1693 // is in use, as -fno-pic for N64 implies -mno-abicalls.
Simon Dardis31636a12017-07-20 14:04:12 +00001694 bool NoABICalls =
1695 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
Simon Dardisad9d05d2017-08-11 15:01:34 +00001696
1697 llvm::Reloc::Model RelocationModel;
1698 unsigned PICLevel;
1699 bool IsPIE;
1700 std::tie(RelocationModel, PICLevel, IsPIE) =
1701 ParsePICArgs(getToolChain(), Args);
1702
1703 NoABICalls = NoABICalls ||
1704 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1705
Simon Dardis31636a12017-07-20 14:04:12 +00001706 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1707 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1708 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1709 CmdArgs.push_back("-mllvm");
1710 CmdArgs.push_back("-mgpopt");
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001711
1712 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1713 options::OPT_mno_local_sdata);
Simon Dardis7d318782017-07-24 14:02:09 +00001714 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
Simon Dardiseeed0002017-08-03 13:04:29 +00001715 options::OPT_mno_extern_sdata);
1716 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1717 options::OPT_mno_embedded_data);
Simon Dardis9f1d5d82017-07-20 22:23:21 +00001718 if (LocalSData) {
1719 CmdArgs.push_back("-mllvm");
1720 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1721 CmdArgs.push_back("-mlocal-sdata=1");
1722 } else {
1723 CmdArgs.push_back("-mlocal-sdata=0");
1724 }
1725 LocalSData->claim();
1726 }
1727
Simon Dardis7d318782017-07-24 14:02:09 +00001728 if (ExternSData) {
1729 CmdArgs.push_back("-mllvm");
1730 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1731 CmdArgs.push_back("-mextern-sdata=1");
1732 } else {
1733 CmdArgs.push_back("-mextern-sdata=0");
1734 }
1735 ExternSData->claim();
1736 }
Simon Dardiseeed0002017-08-03 13:04:29 +00001737
1738 if (EmbeddedData) {
1739 CmdArgs.push_back("-mllvm");
1740 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1741 CmdArgs.push_back("-membedded-data=1");
1742 } else {
1743 CmdArgs.push_back("-membedded-data=0");
1744 }
1745 EmbeddedData->claim();
1746 }
1747
Simon Dardis31636a12017-07-20 14:04:12 +00001748 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1749 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1750
1751 if (GPOpt)
1752 GPOpt->claim();
1753
David L. Jonesf561aba2017-03-08 01:02:16 +00001754 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1755 StringRef Val = StringRef(A->getValue());
1756 if (mips::hasCompactBranches(CPUName)) {
1757 if (Val == "never" || Val == "always" || Val == "optimal") {
1758 CmdArgs.push_back("-mllvm");
1759 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1760 } else
1761 D.Diag(diag::err_drv_unsupported_option_argument)
1762 << A->getOption().getName() << Val;
1763 } else
1764 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1765 }
Vladimir Stefanovic99113a02019-01-18 19:54:51 +00001766
1767 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1768 options::OPT_mno_relax_pic_calls)) {
1769 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1770 CmdArgs.push_back("-mllvm");
1771 CmdArgs.push_back("-mips-jalr-reloc=0");
1772 }
1773 }
David L. Jonesf561aba2017-03-08 01:02:16 +00001774}
1775
1776void Clang::AddPPCTargetArgs(const ArgList &Args,
1777 ArgStringList &CmdArgs) const {
1778 // Select the ABI to use.
1779 const char *ABIName = nullptr;
1780 if (getToolChain().getTriple().isOSLinux())
1781 switch (getToolChain().getArch()) {
1782 case llvm::Triple::ppc64: {
1783 // When targeting a processor that supports QPX, or if QPX is
1784 // specifically enabled, default to using the ABI that supports QPX (so
1785 // long as it is not specifically disabled).
1786 bool HasQPX = false;
1787 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1788 HasQPX = A->getValue() == StringRef("a2q");
1789 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1790 if (HasQPX) {
1791 ABIName = "elfv1-qpx";
1792 break;
1793 }
1794
1795 ABIName = "elfv1";
1796 break;
1797 }
1798 case llvm::Triple::ppc64le:
1799 ABIName = "elfv2";
1800 break;
1801 default:
1802 break;
1803 }
1804
Fangrui Song6bd02a42019-07-15 07:25:11 +00001805 bool IEEELongDouble = false;
1806 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1807 StringRef V = A->getValue();
1808 if (V == "ieeelongdouble")
1809 IEEELongDouble = true;
1810 else if (V == "ibmlongdouble")
1811 IEEELongDouble = false;
1812 else if (V != "altivec")
1813 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1814 // the option if given as we don't have backend support for any targets
1815 // that don't use the altivec abi.
David L. Jonesf561aba2017-03-08 01:02:16 +00001816 ABIName = A->getValue();
Fangrui Song6bd02a42019-07-15 07:25:11 +00001817 }
1818 if (IEEELongDouble)
1819 CmdArgs.push_back("-mabi=ieeelongdouble");
David L. Jonesf561aba2017-03-08 01:02:16 +00001820
1821 ppc::FloatABI FloatABI =
1822 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1823
1824 if (FloatABI == ppc::FloatABI::Soft) {
1825 // Floating point operations and argument passing are soft.
1826 CmdArgs.push_back("-msoft-float");
1827 CmdArgs.push_back("-mfloat-abi");
1828 CmdArgs.push_back("soft");
1829 } else {
1830 // Floating point operations and argument passing are hard.
1831 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1832 CmdArgs.push_back("-mfloat-abi");
1833 CmdArgs.push_back("hard");
1834 }
1835
1836 if (ABIName) {
1837 CmdArgs.push_back("-target-abi");
1838 CmdArgs.push_back(ABIName);
1839 }
1840}
1841
Alex Bradbury71f45452018-01-11 13:36:56 +00001842void Clang::AddRISCVTargetArgs(const ArgList &Args,
1843 ArgStringList &CmdArgs) const {
1844 // FIXME: currently defaults to the soft-float ABIs. Will need to be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001845 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
Alex Bradbury71f45452018-01-11 13:36:56 +00001846 const char *ABIName = nullptr;
1847 const llvm::Triple &Triple = getToolChain().getTriple();
1848 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1849 ABIName = A->getValue();
1850 else if (Triple.getArch() == llvm::Triple::riscv32)
1851 ABIName = "ilp32";
1852 else if (Triple.getArch() == llvm::Triple::riscv64)
1853 ABIName = "lp64";
1854 else
1855 llvm_unreachable("Unexpected triple!");
1856
1857 CmdArgs.push_back("-target-abi");
1858 CmdArgs.push_back(ABIName);
1859}
1860
David L. Jonesf561aba2017-03-08 01:02:16 +00001861void Clang::AddSparcTargetArgs(const ArgList &Args,
1862 ArgStringList &CmdArgs) const {
1863 sparc::FloatABI FloatABI =
1864 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1865
1866 if (FloatABI == sparc::FloatABI::Soft) {
1867 // Floating point operations and argument passing are soft.
1868 CmdArgs.push_back("-msoft-float");
1869 CmdArgs.push_back("-mfloat-abi");
1870 CmdArgs.push_back("soft");
1871 } else {
1872 // Floating point operations and argument passing are hard.
1873 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1874 CmdArgs.push_back("-mfloat-abi");
1875 CmdArgs.push_back("hard");
1876 }
1877}
1878
1879void Clang::AddSystemZTargetArgs(const ArgList &Args,
1880 ArgStringList &CmdArgs) const {
1881 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1882 CmdArgs.push_back("-mbackchain");
1883}
1884
1885void Clang::AddX86TargetArgs(const ArgList &Args,
1886 ArgStringList &CmdArgs) const {
1887 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1888 Args.hasArg(options::OPT_mkernel) ||
1889 Args.hasArg(options::OPT_fapple_kext))
1890 CmdArgs.push_back("-disable-red-zone");
1891
Kristina Brooks7f569b72018-10-18 14:07:02 +00001892 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1893 options::OPT_mno_tls_direct_seg_refs, true))
1894 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1895
David L. Jonesf561aba2017-03-08 01:02:16 +00001896 // Default to avoid implicit floating-point for kernel/kext code, but allow
1897 // that to be overridden with -mno-soft-float.
1898 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1899 Args.hasArg(options::OPT_fapple_kext));
1900 if (Arg *A = Args.getLastArg(
1901 options::OPT_msoft_float, options::OPT_mno_soft_float,
1902 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1903 const Option &O = A->getOption();
1904 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1905 O.matches(options::OPT_msoft_float));
1906 }
1907 if (NoImplicitFloat)
1908 CmdArgs.push_back("-no-implicit-float");
1909
1910 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1911 StringRef Value = A->getValue();
1912 if (Value == "intel" || Value == "att") {
1913 CmdArgs.push_back("-mllvm");
1914 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1915 } else {
1916 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1917 << A->getOption().getName() << Value;
1918 }
Nico Webere3712cf2018-01-17 13:34:20 +00001919 } else if (getToolChain().getDriver().IsCLMode()) {
1920 CmdArgs.push_back("-mllvm");
1921 CmdArgs.push_back("-x86-asm-syntax=intel");
David L. Jonesf561aba2017-03-08 01:02:16 +00001922 }
1923
1924 // Set flags to support MCU ABI.
1925 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1926 CmdArgs.push_back("-mfloat-abi");
1927 CmdArgs.push_back("soft");
1928 CmdArgs.push_back("-mstack-alignment=4");
1929 }
1930}
1931
1932void Clang::AddHexagonTargetArgs(const ArgList &Args,
1933 ArgStringList &CmdArgs) const {
1934 CmdArgs.push_back("-mqdsp6-compat");
1935 CmdArgs.push_back("-Wreturn-type");
1936
1937 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00001938 CmdArgs.push_back("-mllvm");
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001939 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1940 Twine(G.getValue())));
David L. Jonesf561aba2017-03-08 01:02:16 +00001941 }
1942
1943 if (!Args.hasArg(options::OPT_fno_short_enums))
1944 CmdArgs.push_back("-fshort-enums");
1945 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1946 CmdArgs.push_back("-mllvm");
1947 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1948 }
1949 CmdArgs.push_back("-mllvm");
1950 CmdArgs.push_back("-machine-sink-split=0");
1951}
1952
1953void Clang::AddLanaiTargetArgs(const ArgList &Args,
1954 ArgStringList &CmdArgs) const {
1955 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1956 StringRef CPUName = A->getValue();
1957
1958 CmdArgs.push_back("-target-cpu");
1959 CmdArgs.push_back(Args.MakeArgString(CPUName));
1960 }
1961 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1962 StringRef Value = A->getValue();
1963 // Only support mregparm=4 to support old usage. Report error for all other
1964 // cases.
1965 int Mregparm;
1966 if (Value.getAsInteger(10, Mregparm)) {
1967 if (Mregparm != 4) {
1968 getToolChain().getDriver().Diag(
1969 diag::err_drv_unsupported_option_argument)
1970 << A->getOption().getName() << Value;
1971 }
1972 }
1973 }
1974}
1975
1976void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1977 ArgStringList &CmdArgs) const {
1978 // Default to "hidden" visibility.
1979 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1980 options::OPT_fvisibility_ms_compat)) {
1981 CmdArgs.push_back("-fvisibility");
1982 CmdArgs.push_back("hidden");
1983 }
1984}
1985
1986void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1987 StringRef Target, const InputInfo &Output,
1988 const InputInfo &Input, const ArgList &Args) const {
1989 // If this is a dry run, do not create the compilation database file.
1990 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1991 return;
1992
1993 using llvm::yaml::escape;
1994 const Driver &D = getToolChain().getDriver();
1995
1996 if (!CompilationDatabase) {
1997 std::error_code EC;
1998 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1999 if (EC) {
2000 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2001 << EC.message();
2002 return;
2003 }
2004 CompilationDatabase = std::move(File);
2005 }
2006 auto &CDB = *CompilationDatabase;
2007 SmallString<128> Buf;
2008 if (llvm::sys::fs::current_path(Buf))
2009 Buf = ".";
2010 CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
2011 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2012 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2013 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2014 Buf = "-x";
2015 Buf += types::getTypeName(Input.getType());
2016 CDB << ", \"" << escape(Buf) << "\"";
2017 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2018 Buf = "--sysroot=";
2019 Buf += D.SysRoot;
2020 CDB << ", \"" << escape(Buf) << "\"";
2021 }
2022 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2023 for (auto &A: Args) {
2024 auto &O = A->getOption();
2025 // Skip language selection, which is positional.
2026 if (O.getID() == options::OPT_x)
2027 continue;
2028 // Skip writing dependency output and the compilation database itself.
2029 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2030 continue;
2031 // Skip inputs.
2032 if (O.getKind() == Option::InputClass)
2033 continue;
2034 // All other arguments are quoted and appended.
2035 ArgStringList ASL;
2036 A->render(Args, ASL);
2037 for (auto &it: ASL)
2038 CDB << ", \"" << escape(it) << "\"";
2039 }
2040 Buf = "--target=";
2041 Buf += Target;
2042 CDB << ", \"" << escape(Buf) << "\"]},\n";
2043}
2044
2045static void CollectArgsForIntegratedAssembler(Compilation &C,
2046 const ArgList &Args,
2047 ArgStringList &CmdArgs,
2048 const Driver &D) {
2049 if (UseRelaxAll(C, Args))
2050 CmdArgs.push_back("-mrelax-all");
2051
2052 // Only default to -mincremental-linker-compatible if we think we are
2053 // targeting the MSVC linker.
2054 bool DefaultIncrementalLinkerCompatible =
2055 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2056 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2057 options::OPT_mno_incremental_linker_compatible,
2058 DefaultIncrementalLinkerCompatible))
2059 CmdArgs.push_back("-mincremental-linker-compatible");
2060
2061 switch (C.getDefaultToolChain().getArch()) {
2062 case llvm::Triple::arm:
2063 case llvm::Triple::armeb:
2064 case llvm::Triple::thumb:
2065 case llvm::Triple::thumbeb:
2066 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2067 StringRef Value = A->getValue();
2068 if (Value == "always" || Value == "never" || Value == "arm" ||
2069 Value == "thumb") {
2070 CmdArgs.push_back("-mllvm");
2071 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2072 } else {
2073 D.Diag(diag::err_drv_unsupported_option_argument)
2074 << A->getOption().getName() << Value;
2075 }
2076 }
2077 break;
2078 default:
2079 break;
2080 }
2081
2082 // When passing -I arguments to the assembler we sometimes need to
2083 // unconditionally take the next argument. For example, when parsing
2084 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2085 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2086 // arg after parsing the '-I' arg.
2087 bool TakeNextArg = false;
2088
Petr Hosek5668d832017-11-22 01:38:31 +00002089 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
Dan Albert2715b282019-03-28 18:08:28 +00002090 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00002091 const char *MipsTargetFeature = nullptr;
2092 for (const Arg *A :
2093 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2094 A->claim();
2095
2096 for (StringRef Value : A->getValues()) {
2097 if (TakeNextArg) {
2098 CmdArgs.push_back(Value.data());
2099 TakeNextArg = false;
2100 continue;
2101 }
2102
2103 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2104 Value == "-mbig-obj")
2105 continue; // LLVM handles bigobj automatically
2106
2107 switch (C.getDefaultToolChain().getArch()) {
2108 default:
2109 break;
Peter Smith3947cb32017-11-20 13:43:55 +00002110 case llvm::Triple::thumb:
2111 case llvm::Triple::thumbeb:
2112 case llvm::Triple::arm:
2113 case llvm::Triple::armeb:
2114 if (Value == "-mthumb")
2115 // -mthumb has already been processed in ComputeLLVMTriple()
2116 // recognize but skip over here.
2117 continue;
Peter Smith931c9fa2017-11-20 13:53:55 +00002118 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00002119 case llvm::Triple::mips:
2120 case llvm::Triple::mipsel:
2121 case llvm::Triple::mips64:
2122 case llvm::Triple::mips64el:
2123 if (Value == "--trap") {
2124 CmdArgs.push_back("-target-feature");
2125 CmdArgs.push_back("+use-tcc-in-div");
2126 continue;
2127 }
2128 if (Value == "--break") {
2129 CmdArgs.push_back("-target-feature");
2130 CmdArgs.push_back("-use-tcc-in-div");
2131 continue;
2132 }
2133 if (Value.startswith("-msoft-float")) {
2134 CmdArgs.push_back("-target-feature");
2135 CmdArgs.push_back("+soft-float");
2136 continue;
2137 }
2138 if (Value.startswith("-mhard-float")) {
2139 CmdArgs.push_back("-target-feature");
2140 CmdArgs.push_back("-soft-float");
2141 continue;
2142 }
2143
2144 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2145 .Case("-mips1", "+mips1")
2146 .Case("-mips2", "+mips2")
2147 .Case("-mips3", "+mips3")
2148 .Case("-mips4", "+mips4")
2149 .Case("-mips5", "+mips5")
2150 .Case("-mips32", "+mips32")
2151 .Case("-mips32r2", "+mips32r2")
2152 .Case("-mips32r3", "+mips32r3")
2153 .Case("-mips32r5", "+mips32r5")
2154 .Case("-mips32r6", "+mips32r6")
2155 .Case("-mips64", "+mips64")
2156 .Case("-mips64r2", "+mips64r2")
2157 .Case("-mips64r3", "+mips64r3")
2158 .Case("-mips64r5", "+mips64r5")
2159 .Case("-mips64r6", "+mips64r6")
2160 .Default(nullptr);
2161 if (MipsTargetFeature)
2162 continue;
2163 }
2164
2165 if (Value == "-force_cpusubtype_ALL") {
2166 // Do nothing, this is the default and we don't support anything else.
2167 } else if (Value == "-L") {
2168 CmdArgs.push_back("-msave-temp-labels");
2169 } else if (Value == "--fatal-warnings") {
2170 CmdArgs.push_back("-massembler-fatal-warnings");
2171 } else if (Value == "--noexecstack") {
Dan Albert2715b282019-03-28 18:08:28 +00002172 UseNoExecStack = true;
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002173 } else if (Value.startswith("-compress-debug-sections") ||
2174 Value.startswith("--compress-debug-sections") ||
2175 Value == "-nocompress-debug-sections" ||
David L. Jonesf561aba2017-03-08 01:02:16 +00002176 Value == "--nocompress-debug-sections") {
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00002177 CmdArgs.push_back(Value.data());
David L. Jonesf561aba2017-03-08 01:02:16 +00002178 } else if (Value == "-mrelax-relocations=yes" ||
2179 Value == "--mrelax-relocations=yes") {
2180 UseRelaxRelocations = true;
2181 } else if (Value == "-mrelax-relocations=no" ||
2182 Value == "--mrelax-relocations=no") {
2183 UseRelaxRelocations = false;
2184 } else if (Value.startswith("-I")) {
2185 CmdArgs.push_back(Value.data());
2186 // We need to consume the next argument if the current arg is a plain
2187 // -I. The next arg will be the include directory.
2188 if (Value == "-I")
2189 TakeNextArg = true;
2190 } else if (Value.startswith("-gdwarf-")) {
2191 // "-gdwarf-N" options are not cc1as options.
2192 unsigned DwarfVersion = DwarfVersionNum(Value);
2193 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2194 CmdArgs.push_back(Value.data());
2195 } else {
2196 RenderDebugEnablingArgs(Args, CmdArgs,
2197 codegenoptions::LimitedDebugInfo,
2198 DwarfVersion, llvm::DebuggerKind::Default);
2199 }
2200 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2201 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2202 // Do nothing, we'll validate it later.
2203 } else if (Value == "-defsym") {
2204 if (A->getNumValues() != 2) {
2205 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2206 break;
2207 }
2208 const char *S = A->getValue(1);
2209 auto Pair = StringRef(S).split('=');
2210 auto Sym = Pair.first;
2211 auto SVal = Pair.second;
2212
2213 if (Sym.empty() || SVal.empty()) {
2214 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2215 break;
2216 }
2217 int64_t IVal;
2218 if (SVal.getAsInteger(0, IVal)) {
2219 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2220 break;
2221 }
2222 CmdArgs.push_back(Value.data());
2223 TakeNextArg = true;
Nico Weber4c9fa4a2018-12-06 18:50:39 +00002224 } else if (Value == "-fdebug-compilation-dir") {
2225 CmdArgs.push_back("-fdebug-compilation-dir");
2226 TakeNextArg = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00002227 } else {
2228 D.Diag(diag::err_drv_unsupported_option_argument)
2229 << A->getOption().getName() << Value;
2230 }
2231 }
2232 }
David L. Jonesf561aba2017-03-08 01:02:16 +00002233 if (UseRelaxRelocations)
2234 CmdArgs.push_back("--mrelax-relocations");
Dan Albert2715b282019-03-28 18:08:28 +00002235 if (UseNoExecStack)
2236 CmdArgs.push_back("-mnoexecstack");
David L. Jonesf561aba2017-03-08 01:02:16 +00002237 if (MipsTargetFeature != nullptr) {
2238 CmdArgs.push_back("-target-feature");
2239 CmdArgs.push_back(MipsTargetFeature);
2240 }
Steven Wu098742f2018-12-12 17:30:16 +00002241
2242 // forward -fembed-bitcode to assmebler
2243 if (C.getDriver().embedBitcodeEnabled() ||
2244 C.getDriver().embedBitcodeMarkerOnly())
2245 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00002246}
2247
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002248static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2249 bool OFastEnabled, const ArgList &Args,
2250 ArgStringList &CmdArgs) {
2251 // Handle various floating point optimization flags, mapping them to the
2252 // appropriate LLVM code generation flags. This is complicated by several
2253 // "umbrella" flags, so we do this by stepping through the flags incrementally
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002254 // adjusting what we think is enabled/disabled, then at the end setting the
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002255 // LLVM flags based on the final state.
2256 bool HonorINFs = true;
2257 bool HonorNaNs = true;
2258 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2259 bool MathErrno = TC.IsMathErrnoDefault();
2260 bool AssociativeMath = false;
2261 bool ReciprocalMath = false;
2262 bool SignedZeros = true;
2263 bool TrappingMath = true;
2264 StringRef DenormalFPMath = "";
2265 StringRef FPContract = "";
2266
Saleem Abdulrasool258e4f62018-09-18 21:12:39 +00002267 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2268 CmdArgs.push_back("-mlimit-float-precision");
2269 CmdArgs.push_back(A->getValue());
2270 }
2271
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002272 for (const Arg *A : Args) {
2273 switch (A->getOption().getID()) {
2274 // If this isn't an FP option skip the claim below
2275 default: continue;
2276
2277 // Options controlling individual features
2278 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2279 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2280 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2281 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2282 case options::OPT_fmath_errno: MathErrno = true; break;
2283 case options::OPT_fno_math_errno: MathErrno = false; break;
2284 case options::OPT_fassociative_math: AssociativeMath = true; break;
2285 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2286 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2287 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2288 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2289 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2290 case options::OPT_ftrapping_math: TrappingMath = true; break;
2291 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2292
2293 case options::OPT_fdenormal_fp_math_EQ:
2294 DenormalFPMath = A->getValue();
2295 break;
2296
2297 // Validate and pass through -fp-contract option.
2298 case options::OPT_ffp_contract: {
2299 StringRef Val = A->getValue();
2300 if (Val == "fast" || Val == "on" || Val == "off")
2301 FPContract = Val;
2302 else
2303 D.Diag(diag::err_drv_unsupported_option_argument)
2304 << A->getOption().getName() << Val;
2305 break;
2306 }
2307
2308 case options::OPT_ffinite_math_only:
2309 HonorINFs = false;
2310 HonorNaNs = false;
2311 break;
2312 case options::OPT_fno_finite_math_only:
2313 HonorINFs = true;
2314 HonorNaNs = true;
2315 break;
2316
2317 case options::OPT_funsafe_math_optimizations:
2318 AssociativeMath = true;
2319 ReciprocalMath = true;
2320 SignedZeros = false;
2321 TrappingMath = false;
2322 break;
2323 case options::OPT_fno_unsafe_math_optimizations:
2324 AssociativeMath = false;
2325 ReciprocalMath = false;
2326 SignedZeros = true;
2327 TrappingMath = true;
2328 // -fno_unsafe_math_optimizations restores default denormal handling
2329 DenormalFPMath = "";
2330 break;
2331
2332 case options::OPT_Ofast:
2333 // If -Ofast is the optimization level, then -ffast-math should be enabled
2334 if (!OFastEnabled)
2335 continue;
2336 LLVM_FALLTHROUGH;
2337 case options::OPT_ffast_math:
2338 HonorINFs = false;
2339 HonorNaNs = false;
2340 MathErrno = false;
2341 AssociativeMath = true;
2342 ReciprocalMath = true;
2343 SignedZeros = false;
2344 TrappingMath = false;
2345 // If fast-math is set then set the fp-contract mode to fast.
2346 FPContract = "fast";
2347 break;
2348 case options::OPT_fno_fast_math:
2349 HonorINFs = true;
2350 HonorNaNs = true;
2351 // Turning on -ffast-math (with either flag) removes the need for
2352 // MathErrno. However, turning *off* -ffast-math merely restores the
2353 // toolchain default (which may be false).
2354 MathErrno = TC.IsMathErrnoDefault();
2355 AssociativeMath = false;
2356 ReciprocalMath = false;
2357 SignedZeros = true;
2358 TrappingMath = true;
2359 // -fno_fast_math restores default denormal and fpcontract handling
2360 DenormalFPMath = "";
2361 FPContract = "";
2362 break;
2363 }
2364
2365 // If we handled this option claim it
2366 A->claim();
2367 }
2368
2369 if (!HonorINFs)
2370 CmdArgs.push_back("-menable-no-infs");
2371
2372 if (!HonorNaNs)
2373 CmdArgs.push_back("-menable-no-nans");
2374
2375 if (MathErrno)
2376 CmdArgs.push_back("-fmath-errno");
2377
2378 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2379 !TrappingMath)
2380 CmdArgs.push_back("-menable-unsafe-fp-math");
2381
2382 if (!SignedZeros)
2383 CmdArgs.push_back("-fno-signed-zeros");
2384
Sanjay Patelcb8c0092017-12-16 16:11:17 +00002385 if (AssociativeMath && !SignedZeros && !TrappingMath)
2386 CmdArgs.push_back("-mreassociate");
2387
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002388 if (ReciprocalMath)
2389 CmdArgs.push_back("-freciprocal-math");
2390
2391 if (!TrappingMath)
2392 CmdArgs.push_back("-fno-trapping-math");
2393
2394 if (!DenormalFPMath.empty())
2395 CmdArgs.push_back(
2396 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2397
2398 if (!FPContract.empty())
2399 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2400
2401 ParseMRecip(D, Args, CmdArgs);
2402
2403 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2404 // individual features enabled by -ffast-math instead of the option itself as
2405 // that's consistent with gcc's behaviour.
2406 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2407 ReciprocalMath && !SignedZeros && !TrappingMath)
2408 CmdArgs.push_back("-ffast-math");
2409
2410 // Handle __FINITE_MATH_ONLY__ similarly.
2411 if (!HonorINFs && !HonorNaNs)
2412 CmdArgs.push_back("-ffinite-math-only");
Saleem Abdulrasoolfb302ca2017-09-03 04:46:57 +00002413
2414 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2415 CmdArgs.push_back("-mfpmath");
2416 CmdArgs.push_back(A->getValue());
2417 }
Sanjay Pateld1754762018-04-27 14:22:48 +00002418
2419 // Disable a codegen optimization for floating-point casts.
Sanjay Patelc81450e2018-04-30 18:19:03 +00002420 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2421 options::OPT_fstrict_float_cast_overflow, false))
2422 CmdArgs.push_back("-fno-strict-float-cast-overflow");
Saleem Abdulrasoole6d219d2017-09-01 22:04:24 +00002423}
2424
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002425static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2426 const llvm::Triple &Triple,
2427 const InputInfo &Input) {
2428 // Enable region store model by default.
2429 CmdArgs.push_back("-analyzer-store=region");
2430
2431 // Treat blocks as analysis entry points.
2432 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2433
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00002434 // Add default argument set.
2435 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2436 CmdArgs.push_back("-analyzer-checker=core");
2437 CmdArgs.push_back("-analyzer-checker=apiModeling");
2438
2439 if (!Triple.isWindowsMSVCEnvironment()) {
2440 CmdArgs.push_back("-analyzer-checker=unix");
2441 } else {
2442 // Enable "unix" checkers that also work on Windows.
2443 CmdArgs.push_back("-analyzer-checker=unix.API");
2444 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2445 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2446 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2447 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2448 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2449 }
2450
2451 // Disable some unix checkers for PS4.
2452 if (Triple.isPS4CPU()) {
2453 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2454 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2455 }
2456
2457 if (Triple.isOSDarwin())
2458 CmdArgs.push_back("-analyzer-checker=osx");
2459
2460 CmdArgs.push_back("-analyzer-checker=deadcode");
2461
2462 if (types::isCXX(Input.getType()))
2463 CmdArgs.push_back("-analyzer-checker=cplusplus");
2464
2465 if (!Triple.isPS4CPU()) {
2466 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2467 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2468 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2469 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2470 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2471 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2472 }
2473
2474 // Default nullability checks.
2475 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2476 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2477 }
2478
2479 // Set the output format. The default is plist, for (lame) historical reasons.
2480 CmdArgs.push_back("-analyzer-output");
2481 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2482 CmdArgs.push_back(A->getValue());
2483 else
2484 CmdArgs.push_back("plist");
2485
2486 // Disable the presentation of standard compiler warnings when using
2487 // --analyze. We only want to show static analyzer diagnostics or frontend
2488 // errors.
2489 CmdArgs.push_back("-w");
2490
2491 // Add -Xanalyzer arguments when running as analyzer.
2492 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2493}
2494
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002495static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
Saleem Abdulrasoolc2320ad2017-09-06 04:56:23 +00002496 ArgStringList &CmdArgs, bool KernelOrKext) {
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002497 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2498
2499 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2500 // doesn't even have a stack!
2501 if (EffectiveTriple.isNVPTX())
2502 return;
2503
2504 // -stack-protector=0 is default.
2505 unsigned StackProtectorLevel = 0;
2506 unsigned DefaultStackProtectorLevel =
2507 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2508
2509 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2510 options::OPT_fstack_protector_all,
2511 options::OPT_fstack_protector_strong,
2512 options::OPT_fstack_protector)) {
2513 if (A->getOption().matches(options::OPT_fstack_protector))
2514 StackProtectorLevel =
2515 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2516 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2517 StackProtectorLevel = LangOptions::SSPStrong;
2518 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2519 StackProtectorLevel = LangOptions::SSPReq;
2520 } else {
Bruno Cardoso Lopesbad2c4a2017-09-06 00:44:10 +00002521 StackProtectorLevel = DefaultStackProtectorLevel;
Saleem Abdulrasoold5ba5452017-08-29 23:59:08 +00002522 }
2523
2524 if (StackProtectorLevel) {
2525 CmdArgs.push_back("-stack-protector");
2526 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2527 }
2528
2529 // --param ssp-buffer-size=
2530 for (const Arg *A : Args.filtered(options::OPT__param)) {
2531 StringRef Str(A->getValue());
2532 if (Str.startswith("ssp-buffer-size=")) {
2533 if (StackProtectorLevel) {
2534 CmdArgs.push_back("-stack-protector-buffer-size");
2535 // FIXME: Verify the argument is a valid integer.
2536 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2537 }
2538 A->claim();
2539 }
2540 }
2541}
2542
JF Bastien14daa202018-12-18 05:12:21 +00002543static void RenderTrivialAutoVarInitOptions(const Driver &D,
2544 const ToolChain &TC,
2545 const ArgList &Args,
2546 ArgStringList &CmdArgs) {
2547 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2548 StringRef TrivialAutoVarInit = "";
2549
2550 for (const Arg *A : Args) {
2551 switch (A->getOption().getID()) {
2552 default:
2553 continue;
2554 case options::OPT_ftrivial_auto_var_init: {
2555 A->claim();
2556 StringRef Val = A->getValue();
2557 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2558 TrivialAutoVarInit = Val;
2559 else
2560 D.Diag(diag::err_drv_unsupported_option_argument)
2561 << A->getOption().getName() << Val;
2562 break;
2563 }
2564 }
2565 }
2566
2567 if (TrivialAutoVarInit.empty())
2568 switch (DefaultTrivialAutoVarInit) {
2569 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2570 break;
2571 case LangOptions::TrivialAutoVarInitKind::Pattern:
2572 TrivialAutoVarInit = "pattern";
2573 break;
2574 case LangOptions::TrivialAutoVarInitKind::Zero:
2575 TrivialAutoVarInit = "zero";
2576 break;
2577 }
2578
2579 if (!TrivialAutoVarInit.empty()) {
2580 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2581 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2582 CmdArgs.push_back(
2583 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2584 }
2585}
2586
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002587static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2588 const unsigned ForwardedArguments[] = {
2589 options::OPT_cl_opt_disable,
2590 options::OPT_cl_strict_aliasing,
2591 options::OPT_cl_single_precision_constant,
2592 options::OPT_cl_finite_math_only,
2593 options::OPT_cl_kernel_arg_info,
2594 options::OPT_cl_unsafe_math_optimizations,
2595 options::OPT_cl_fast_relaxed_math,
2596 options::OPT_cl_mad_enable,
2597 options::OPT_cl_no_signed_zeros,
2598 options::OPT_cl_denorms_are_zero,
2599 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
Alexey Sotkin20f65922018-02-22 11:54:14 +00002600 options::OPT_cl_uniform_work_group_size
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00002601 };
2602
2603 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2604 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2605 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2606 }
2607
2608 for (const auto &Arg : ForwardedArguments)
2609 if (const auto *A = Args.getLastArg(Arg))
2610 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2611}
2612
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00002613static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2614 ArgStringList &CmdArgs) {
2615 bool ARCMTEnabled = false;
2616 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2617 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2618 options::OPT_ccc_arcmt_modify,
2619 options::OPT_ccc_arcmt_migrate)) {
2620 ARCMTEnabled = true;
2621 switch (A->getOption().getID()) {
2622 default: llvm_unreachable("missed a case");
2623 case options::OPT_ccc_arcmt_check:
2624 CmdArgs.push_back("-arcmt-check");
2625 break;
2626 case options::OPT_ccc_arcmt_modify:
2627 CmdArgs.push_back("-arcmt-modify");
2628 break;
2629 case options::OPT_ccc_arcmt_migrate:
2630 CmdArgs.push_back("-arcmt-migrate");
2631 CmdArgs.push_back("-mt-migrate-directory");
2632 CmdArgs.push_back(A->getValue());
2633
2634 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2635 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2636 break;
2637 }
2638 }
2639 } else {
2640 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2641 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2642 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2643 }
2644
2645 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2646 if (ARCMTEnabled)
2647 D.Diag(diag::err_drv_argument_not_allowed_with)
2648 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2649
2650 CmdArgs.push_back("-mt-migrate-directory");
2651 CmdArgs.push_back(A->getValue());
2652
2653 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2654 options::OPT_objcmt_migrate_subscripting,
2655 options::OPT_objcmt_migrate_property)) {
2656 // None specified, means enable them all.
2657 CmdArgs.push_back("-objcmt-migrate-literals");
2658 CmdArgs.push_back("-objcmt-migrate-subscripting");
2659 CmdArgs.push_back("-objcmt-migrate-property");
2660 } else {
2661 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2662 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2663 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2664 }
2665 } else {
2666 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2667 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2668 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2669 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2670 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2671 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2672 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2673 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2674 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2675 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2676 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2677 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2678 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2679 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2680 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2681 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2682 }
2683}
2684
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002685static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2686 const ArgList &Args, ArgStringList &CmdArgs) {
2687 // -fbuiltin is default unless -mkernel is used.
2688 bool UseBuiltins =
2689 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2690 !Args.hasArg(options::OPT_mkernel));
2691 if (!UseBuiltins)
2692 CmdArgs.push_back("-fno-builtin");
2693
2694 // -ffreestanding implies -fno-builtin.
2695 if (Args.hasArg(options::OPT_ffreestanding))
2696 UseBuiltins = false;
2697
2698 // Process the -fno-builtin-* options.
2699 for (const auto &Arg : Args) {
2700 const Option &O = Arg->getOption();
2701 if (!O.matches(options::OPT_fno_builtin_))
2702 continue;
2703
2704 Arg->claim();
2705
2706 // If -fno-builtin is specified, then there's no need to pass the option to
2707 // the frontend.
2708 if (!UseBuiltins)
2709 continue;
2710
2711 StringRef FuncName = Arg->getValue();
2712 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2713 }
2714
2715 // le32-specific flags:
2716 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2717 // by default.
2718 if (TC.getArch() == llvm::Triple::le32)
2719 CmdArgs.push_back("-fno-math-builtin");
Saleem Abdulrasool99f4ead2017-09-01 23:44:01 +00002720}
2721
Adrian Prantl70599032018-02-09 18:43:10 +00002722void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2723 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2724 llvm::sys::path::append(Result, "org.llvm.clang.");
2725 appendUserToPath(Result);
2726 llvm::sys::path::append(Result, "ModuleCache");
2727}
2728
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002729static void RenderModulesOptions(Compilation &C, const Driver &D,
2730 const ArgList &Args, const InputInfo &Input,
2731 const InputInfo &Output,
2732 ArgStringList &CmdArgs, bool &HaveModules) {
2733 // -fmodules enables the use of precompiled modules (off by default).
2734 // Users can pass -fno-cxx-modules to turn off modules support for
2735 // C++/Objective-C++ programs.
2736 bool HaveClangModules = false;
2737 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2738 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2739 options::OPT_fno_cxx_modules, true);
2740 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2741 CmdArgs.push_back("-fmodules");
2742 HaveClangModules = true;
2743 }
2744 }
2745
Richard Smithb1b580e2019-04-14 11:11:37 +00002746 HaveModules |= HaveClangModules;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002747 if (Args.hasArg(options::OPT_fmodules_ts)) {
2748 CmdArgs.push_back("-fmodules-ts");
2749 HaveModules = true;
2750 }
2751
2752 // -fmodule-maps enables implicit reading of module map files. By default,
2753 // this is enabled if we are using Clang's flavor of precompiled modules.
2754 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2755 options::OPT_fno_implicit_module_maps, HaveClangModules))
2756 CmdArgs.push_back("-fimplicit-module-maps");
2757
2758 // -fmodules-decluse checks that modules used are declared so (off by default)
2759 if (Args.hasFlag(options::OPT_fmodules_decluse,
2760 options::OPT_fno_modules_decluse, false))
2761 CmdArgs.push_back("-fmodules-decluse");
2762
2763 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2764 // all #included headers are part of modules.
2765 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2766 options::OPT_fno_modules_strict_decluse, false))
2767 CmdArgs.push_back("-fmodules-strict-decluse");
2768
2769 // -fno-implicit-modules turns off implicitly compiling modules on demand.
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002770 bool ImplicitModules = false;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002771 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2772 options::OPT_fno_implicit_modules, HaveClangModules)) {
2773 if (HaveModules)
2774 CmdArgs.push_back("-fno-implicit-modules");
2775 } else if (HaveModules) {
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002776 ImplicitModules = true;
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002777 // -fmodule-cache-path specifies where our implicitly-built module files
2778 // should be written.
2779 SmallString<128> Path;
2780 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2781 Path = A->getValue();
2782
2783 if (C.isForDiagnostics()) {
2784 // When generating crash reports, we want to emit the modules along with
2785 // the reproduction sources, so we ignore any provided module path.
2786 Path = Output.getFilename();
2787 llvm::sys::path::replace_extension(Path, ".cache");
2788 llvm::sys::path::append(Path, "modules");
2789 } else if (Path.empty()) {
2790 // No module path was provided: use the default.
Adrian Prantl70599032018-02-09 18:43:10 +00002791 Driver::getDefaultModuleCachePath(Path);
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002792 }
2793
2794 const char Arg[] = "-fmodules-cache-path=";
2795 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2796 CmdArgs.push_back(Args.MakeArgString(Path));
2797 }
2798
2799 if (HaveModules) {
2800 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2801 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2802 CmdArgs.push_back(Args.MakeArgString(
2803 std::string("-fprebuilt-module-path=") + A->getValue()));
2804 A->claim();
2805 }
2806 }
2807
2808 // -fmodule-name specifies the module that is currently being built (or
2809 // used for header checking by -fmodule-maps).
2810 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2811
2812 // -fmodule-map-file can be used to specify files containing module
2813 // definitions.
2814 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2815
2816 // -fbuiltin-module-map can be used to load the clang
2817 // builtin headers modulemap file.
2818 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2819 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2820 llvm::sys::path::append(BuiltinModuleMap, "include");
2821 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2822 if (llvm::sys::fs::exists(BuiltinModuleMap))
2823 CmdArgs.push_back(
2824 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2825 }
2826
2827 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2828 // names to precompiled module files (the module is loaded only if used).
2829 // The -fmodule-file=<file> form can be used to unconditionally load
2830 // precompiled module files (whether used or not).
2831 if (HaveModules)
2832 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2833 else
2834 Args.ClaimAllArgs(options::OPT_fmodule_file);
2835
2836 // When building modules and generating crashdumps, we need to dump a module
2837 // dependency VFS alongside the output.
2838 if (HaveClangModules && C.isForDiagnostics()) {
2839 SmallString<128> VFSDir(Output.getFilename());
2840 llvm::sys::path::replace_extension(VFSDir, ".cache");
2841 // Add the cache directory as a temp so the crash diagnostics pick it up.
2842 C.addTempFile(Args.MakeArgString(VFSDir));
2843
2844 llvm::sys::path::append(VFSDir, "vfs");
2845 CmdArgs.push_back("-module-dependency-dir");
2846 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2847 }
2848
2849 if (HaveClangModules)
2850 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2851
2852 // Pass through all -fmodules-ignore-macro arguments.
2853 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2854 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2855 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2856
2857 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2858
2859 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2860 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2861 D.Diag(diag::err_drv_argument_not_allowed_with)
2862 << A->getAsString(Args) << "-fbuild-session-timestamp";
2863
2864 llvm::sys::fs::file_status Status;
2865 if (llvm::sys::fs::status(A->getValue(), Status))
2866 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2867 CmdArgs.push_back(
2868 Args.MakeArgString("-fbuild-session-timestamp=" +
2869 Twine((uint64_t)Status.getLastModificationTime()
2870 .time_since_epoch()
2871 .count())));
2872 }
2873
2874 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2875 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2876 options::OPT_fbuild_session_file))
2877 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2878
2879 Args.AddLastArg(CmdArgs,
2880 options::OPT_fmodules_validate_once_per_build_session);
2881 }
2882
Bruno Cardoso Lopes89b9fdb2018-04-18 06:07:49 +00002883 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2884 options::OPT_fno_modules_validate_system_headers,
2885 ImplicitModules))
2886 CmdArgs.push_back("-fmodules-validate-system-headers");
2887
Saleem Abdulrasoole196e942017-09-01 15:25:17 +00002888 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2889}
2890
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002891static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2892 ArgStringList &CmdArgs) {
2893 // -fsigned-char is default.
2894 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2895 options::OPT_fno_signed_char,
2896 options::OPT_funsigned_char,
2897 options::OPT_fno_unsigned_char)) {
2898 if (A->getOption().matches(options::OPT_funsigned_char) ||
2899 A->getOption().matches(options::OPT_fno_signed_char)) {
2900 CmdArgs.push_back("-fno-signed-char");
2901 }
2902 } else if (!isSignedCharDefault(T)) {
2903 CmdArgs.push_back("-fno-signed-char");
2904 }
2905
Richard Smith28ddb912018-11-14 21:04:34 +00002906 // The default depends on the language standard.
Nico Weber908b6972019-06-26 17:51:47 +00002907 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
Richard Smith3a8244d2018-05-01 05:02:45 +00002908
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002909 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2910 options::OPT_fno_short_wchar)) {
2911 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2912 CmdArgs.push_back("-fwchar-type=short");
2913 CmdArgs.push_back("-fno-signed-wchar");
2914 } else {
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002915 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002916 CmdArgs.push_back("-fwchar-type=int");
Michal Gorny5a409d02018-12-20 13:09:30 +00002917 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2918 T.isOSOpenBSD()))
Saleem Abdulrasool8ba8b022017-10-29 06:01:14 +00002919 CmdArgs.push_back("-fno-signed-wchar");
2920 else
2921 CmdArgs.push_back("-fsigned-wchar");
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002922 }
2923 }
2924}
2925
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002926static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2927 const llvm::Triple &T, const ArgList &Args,
2928 ObjCRuntime &Runtime, bool InferCovariantReturns,
2929 const InputInfo &Input, ArgStringList &CmdArgs) {
2930 const llvm::Triple::ArchType Arch = TC.getArch();
2931
2932 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2933 // is the default. Except for deployment target of 10.5, next runtime is
2934 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2935 if (Runtime.isNonFragile()) {
2936 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2937 options::OPT_fno_objc_legacy_dispatch,
2938 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2939 if (TC.UseObjCMixedDispatch())
2940 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2941 else
2942 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2943 }
2944 }
2945
2946 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2947 // to do Array/Dictionary subscripting by default.
2948 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002949 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2950 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2951
2952 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2953 // NOTE: This logic is duplicated in ToolChains.cpp.
2954 if (isObjCAutoRefCount(Args)) {
2955 TC.CheckObjCARC();
2956
2957 CmdArgs.push_back("-fobjc-arc");
2958
2959 // FIXME: It seems like this entire block, and several around it should be
2960 // wrapped in isObjC, but for now we just use it here as this is where it
2961 // was being used previously.
2962 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2963 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2964 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2965 else
2966 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2967 }
2968
2969 // Allow the user to enable full exceptions code emission.
2970 // We default off for Objective-C, on for Objective-C++.
2971 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2972 options::OPT_fno_objc_arc_exceptions,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002973 /*Default=*/types::isCXX(Input.getType())))
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002974 CmdArgs.push_back("-fobjc-arc-exceptions");
2975 }
2976
2977 // Silence warning for full exception code emission options when explicitly
2978 // set to use no ARC.
2979 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2980 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2981 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2982 }
2983
Pete Coopere3886802018-12-08 05:13:50 +00002984 // Allow the user to control whether messages can be converted to runtime
2985 // functions.
2986 if (types::isObjC(Input.getType())) {
2987 auto *Arg = Args.getLastArg(
2988 options::OPT_fobjc_convert_messages_to_runtime_calls,
2989 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2990 if (Arg &&
2991 Arg->getOption().matches(
2992 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2993 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2994 }
2995
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00002996 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2997 // rewriter.
2998 if (InferCovariantReturns)
2999 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3000
3001 // Pass down -fobjc-weak or -fno-objc-weak if present.
3002 if (types::isObjC(Input.getType())) {
3003 auto WeakArg =
3004 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3005 if (!WeakArg) {
3006 // nothing to do
3007 } else if (!Runtime.allowsWeak()) {
3008 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3009 D.Diag(diag::err_objc_weak_unsupported);
3010 } else {
3011 WeakArg->render(Args, CmdArgs);
3012 }
3013 }
3014}
3015
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00003016static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3017 ArgStringList &CmdArgs) {
3018 bool CaretDefault = true;
3019 bool ColumnDefault = true;
3020
3021 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3022 options::OPT__SLASH_diagnostics_column,
3023 options::OPT__SLASH_diagnostics_caret)) {
3024 switch (A->getOption().getID()) {
3025 case options::OPT__SLASH_diagnostics_caret:
3026 CaretDefault = true;
3027 ColumnDefault = true;
3028 break;
3029 case options::OPT__SLASH_diagnostics_column:
3030 CaretDefault = false;
3031 ColumnDefault = true;
3032 break;
3033 case options::OPT__SLASH_diagnostics_classic:
3034 CaretDefault = false;
3035 ColumnDefault = false;
3036 break;
3037 }
3038 }
3039
3040 // -fcaret-diagnostics is default.
3041 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3042 options::OPT_fno_caret_diagnostics, CaretDefault))
3043 CmdArgs.push_back("-fno-caret-diagnostics");
3044
3045 // -fdiagnostics-fixit-info is default, only pass non-default.
3046 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3047 options::OPT_fno_diagnostics_fixit_info))
3048 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3049
3050 // Enable -fdiagnostics-show-option by default.
3051 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3052 options::OPT_fno_diagnostics_show_option))
3053 CmdArgs.push_back("-fdiagnostics-show-option");
3054
3055 if (const Arg *A =
3056 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3057 CmdArgs.push_back("-fdiagnostics-show-category");
3058 CmdArgs.push_back(A->getValue());
3059 }
3060
3061 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3062 options::OPT_fno_diagnostics_show_hotness, false))
3063 CmdArgs.push_back("-fdiagnostics-show-hotness");
3064
3065 if (const Arg *A =
3066 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3067 std::string Opt =
3068 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3069 CmdArgs.push_back(Args.MakeArgString(Opt));
3070 }
3071
3072 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3073 CmdArgs.push_back("-fdiagnostics-format");
3074 CmdArgs.push_back(A->getValue());
3075 }
3076
3077 if (const Arg *A = Args.getLastArg(
3078 options::OPT_fdiagnostics_show_note_include_stack,
3079 options::OPT_fno_diagnostics_show_note_include_stack)) {
3080 const Option &O = A->getOption();
3081 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3082 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3083 else
3084 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3085 }
3086
3087 // Color diagnostics are parsed by the driver directly from argv and later
3088 // re-parsed to construct this job; claim any possible color diagnostic here
3089 // to avoid warn_drv_unused_argument and diagnose bad
3090 // OPT_fdiagnostics_color_EQ values.
3091 for (const Arg *A : Args) {
3092 const Option &O = A->getOption();
3093 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3094 !O.matches(options::OPT_fdiagnostics_color) &&
3095 !O.matches(options::OPT_fno_color_diagnostics) &&
3096 !O.matches(options::OPT_fno_diagnostics_color) &&
3097 !O.matches(options::OPT_fdiagnostics_color_EQ))
3098 continue;
3099
3100 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3101 StringRef Value(A->getValue());
3102 if (Value != "always" && Value != "never" && Value != "auto")
3103 D.Diag(diag::err_drv_clang_unsupported)
3104 << ("-fdiagnostics-color=" + Value).str();
3105 }
3106 A->claim();
3107 }
3108
3109 if (D.getDiags().getDiagnosticOptions().ShowColors)
3110 CmdArgs.push_back("-fcolor-diagnostics");
3111
3112 if (Args.hasArg(options::OPT_fansi_escape_codes))
3113 CmdArgs.push_back("-fansi-escape-codes");
3114
3115 if (!Args.hasFlag(options::OPT_fshow_source_location,
3116 options::OPT_fno_show_source_location))
3117 CmdArgs.push_back("-fno-show-source-location");
3118
3119 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3120 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3121
3122 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3123 ColumnDefault))
3124 CmdArgs.push_back("-fno-show-column");
3125
3126 if (!Args.hasFlag(options::OPT_fspell_checking,
3127 options::OPT_fno_spell_checking))
3128 CmdArgs.push_back("-fno-spell-checking");
3129}
3130
George Rimar91829ee2018-11-14 09:22:16 +00003131enum class DwarfFissionKind { None, Split, Single };
3132
3133static DwarfFissionKind getDebugFissionKind(const Driver &D,
3134 const ArgList &Args, Arg *&Arg) {
3135 Arg =
3136 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3137 if (!Arg)
3138 return DwarfFissionKind::None;
3139
3140 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3141 return DwarfFissionKind::Split;
3142
3143 StringRef Value = Arg->getValue();
3144 if (Value == "split")
3145 return DwarfFissionKind::Split;
3146 if (Value == "single")
3147 return DwarfFissionKind::Single;
3148
3149 D.Diag(diag::err_drv_unsupported_option_argument)
3150 << Arg->getOption().getName() << Arg->getValue();
3151 return DwarfFissionKind::None;
3152}
3153
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003154static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3155 const llvm::Triple &T, const ArgList &Args,
3156 bool EmitCodeView, bool IsWindowsMSVC,
3157 ArgStringList &CmdArgs,
3158 codegenoptions::DebugInfoKind &DebugInfoKind,
George Rimar91829ee2018-11-14 09:22:16 +00003159 DwarfFissionKind &DwarfFission) {
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003160 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003161 options::OPT_fno_debug_info_for_profiling, false) &&
3162 checkDebugInfoOption(
3163 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003164 CmdArgs.push_back("-fdebug-info-for-profiling");
3165
3166 // The 'g' groups options involve a somewhat intricate sequence of decisions
3167 // about what to pass from the driver to the frontend, but by the time they
3168 // reach cc1 they've been factored into three well-defined orthogonal choices:
3169 // * what level of debug info to generate
3170 // * what dwarf version to write
3171 // * what debugger tuning to use
3172 // This avoids having to monkey around further in cc1 other than to disable
3173 // codeview if not running in a Windows environment. Perhaps even that
3174 // decision should be made in the driver as well though.
3175 unsigned DWARFVersion = 0;
3176 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3177
3178 bool SplitDWARFInlining =
3179 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3180 options::OPT_fno_split_dwarf_inlining, true);
3181
3182 Args.ClaimAllArgs(options::OPT_g_Group);
3183
George Rimar91829ee2018-11-14 09:22:16 +00003184 Arg* SplitDWARFArg;
3185 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003186
George Rimar91829ee2018-11-14 09:22:16 +00003187 if (DwarfFission != DwarfFissionKind::None &&
3188 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3189 DwarfFission = DwarfFissionKind::None;
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003190 SplitDWARFInlining = false;
3191 }
3192
Fangrui Songe3576b02019-04-17 01:46:27 +00003193 if (const Arg *A =
3194 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3195 options::OPT_gsplit_dwarf_EQ)) {
3196 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3197
3198 // If the last option explicitly specified a debug-info level, use it.
3199 if (checkDebugInfoOption(A, Args, D, TC) &&
3200 A->getOption().matches(options::OPT_gN_Group)) {
3201 DebugInfoKind = DebugLevelToInfoKind(*A);
3202 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3203 // complicated if you've disabled inline info in the skeleton CUs
3204 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3205 // line-tables-only, so let those compose naturally in that case.
3206 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3207 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3208 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3209 SplitDWARFInlining))
3210 DwarfFission = DwarfFissionKind::None;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003211 }
3212 }
3213
3214 // If a debugger tuning argument appeared, remember it.
3215 if (const Arg *A =
3216 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003217 if (checkDebugInfoOption(A, Args, D, TC)) {
3218 if (A->getOption().matches(options::OPT_glldb))
3219 DebuggerTuning = llvm::DebuggerKind::LLDB;
3220 else if (A->getOption().matches(options::OPT_gsce))
3221 DebuggerTuning = llvm::DebuggerKind::SCE;
3222 else
3223 DebuggerTuning = llvm::DebuggerKind::GDB;
3224 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003225 }
3226
3227 // If a -gdwarf argument appeared, remember it.
3228 if (const Arg *A =
3229 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3230 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003231 if (checkDebugInfoOption(A, Args, D, TC))
3232 DWARFVersion = DwarfVersionNum(A->getSpelling());
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003233
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003234 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3235 if (checkDebugInfoOption(A, Args, D, TC))
3236 EmitCodeView = true;
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003237 }
3238
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003239 // If the user asked for debug info but did not explicitly specify -gcodeview
3240 // or -gdwarf, ask the toolchain for the default format.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003241 if (!EmitCodeView && DWARFVersion == 0 &&
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003242 DebugInfoKind != codegenoptions::NoDebugInfo) {
3243 switch (TC.getDefaultDebugFormat()) {
3244 case codegenoptions::DIF_CodeView:
3245 EmitCodeView = true;
3246 break;
3247 case codegenoptions::DIF_DWARF:
3248 DWARFVersion = TC.GetDefaultDwarfVersion();
3249 break;
3250 }
3251 }
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003252
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003253 // -gline-directives-only supported only for the DWARF debug info.
3254 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3255 DebugInfoKind = codegenoptions::NoDebugInfo;
3256
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003257 // We ignore flag -gstrict-dwarf for now.
3258 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3259 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3260
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003261 // Column info is included by default for everything except SCE and
3262 // CodeView. Clang doesn't track end columns, just starting columns, which,
3263 // in theory, is fine for CodeView (and PDB). In practice, however, the
3264 // Microsoft debuggers don't handle missing end columns well, so it's better
3265 // not to include any column info.
3266 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3267 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003268 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
Martin Storsjof9fa17b2018-05-08 20:55:23 +00003269 /*Default=*/!EmitCodeView &&
Paul Robinsona8280812017-09-29 21:25:07 +00003270 DebuggerTuning != llvm::DebuggerKind::SCE))
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003271 CmdArgs.push_back("-dwarf-column-info");
3272
3273 // FIXME: Move backend command line options to the module.
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003274 // If -gline-tables-only or -gline-directives-only is the last option it wins.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003275 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3276 if (checkDebugInfoOption(A, Args, D, TC)) {
Alexey Bataev80e1b5e2018-08-31 13:56:14 +00003277 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3278 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003279 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3280 CmdArgs.push_back("-dwarf-ext-refs");
3281 CmdArgs.push_back("-fmodule-format=obj");
3282 }
3283 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003284
Aaron Puchertb207bae2019-06-26 21:36:35 +00003285 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3286 CmdArgs.push_back("-fno-split-dwarf-inlining");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003287
3288 // After we've dealt with all combinations of things that could
3289 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3290 // figure out if we need to "upgrade" it to standalone debug info.
3291 // We parse these two '-f' options whether or not they will be used,
3292 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
David Blaikieb068f922019-04-16 00:16:29 +00003293 bool NeedFullDebug = Args.hasFlag(
3294 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3295 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3296 TC.GetDefaultStandaloneDebug());
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003297 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3298 (void)checkDebugInfoOption(A, Args, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003299 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3300 DebugInfoKind = codegenoptions::FullDebugInfo;
3301
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003302 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3303 false)) {
Scott Lindera2fbcef2018-02-26 17:32:31 +00003304 // Source embedding is a vendor extension to DWARF v5. By now we have
3305 // checked if a DWARF version was stated explicitly, and have otherwise
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003306 // fallen back to the target default, so if this is still not at least 5
3307 // we emit an error.
3308 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
Scott Lindera2fbcef2018-02-26 17:32:31 +00003309 if (DWARFVersion < 5)
3310 D.Diag(diag::err_drv_argument_only_allowed_with)
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003311 << A->getAsString(Args) << "-gdwarf-5";
3312 else if (checkDebugInfoOption(A, Args, D, TC))
3313 CmdArgs.push_back("-gembed-source");
Scott Lindera2fbcef2018-02-26 17:32:31 +00003314 }
3315
Reid Kleckner75557712018-11-16 18:47:41 +00003316 if (EmitCodeView) {
Reid Kleckner7b7b1142018-11-14 22:59:27 +00003317 CmdArgs.push_back("-gcodeview");
3318
Reid Kleckner75557712018-11-16 18:47:41 +00003319 // Emit codeview type hashes if requested.
3320 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3321 options::OPT_gno_codeview_ghash, false)) {
3322 CmdArgs.push_back("-gcodeview-ghash");
3323 }
3324 }
3325
Alexey Bataevc92fc3c2018-12-12 14:52:27 +00003326 // Adjust the debug info kind for the given toolchain.
3327 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3328
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003329 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3330 DebuggerTuning);
3331
3332 // -fdebug-macro turns on macro debug info generation.
3333 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3334 false))
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003335 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3336 D, TC))
3337 CmdArgs.push_back("-debug-info-macro");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003338
3339 // -ggnu-pubnames turns on gnu style pubnames in the backend.
David Blaikie65864522018-08-20 20:14:08 +00003340 const auto *PubnamesArg =
3341 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3342 options::OPT_gpubnames, options::OPT_gno_pubnames);
George Rimar91829ee2018-11-14 09:22:16 +00003343 if (DwarfFission != DwarfFissionKind::None ||
3344 DebuggerTuning == llvm::DebuggerKind::LLDB ||
David Blaikie65864522018-08-20 20:14:08 +00003345 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3346 if (!PubnamesArg ||
3347 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3348 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3349 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3350 options::OPT_gpubnames)
3351 ? "-gpubnames"
3352 : "-ggnu-pubnames");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003353
David Blaikie27692de2018-11-13 20:08:13 +00003354 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3355 options::OPT_fno_debug_ranges_base_address, false)) {
3356 CmdArgs.push_back("-fdebug-ranges-base-address");
3357 }
3358
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003359 // -gdwarf-aranges turns on the emission of the aranges section in the
3360 // backend.
Paul Robinsona8280812017-09-29 21:25:07 +00003361 // Always enabled for SCE tuning.
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003362 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3363 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3364 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3365 if (NeedAranges) {
Eli Friedman01d349b2018-04-12 22:21:36 +00003366 CmdArgs.push_back("-mllvm");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003367 CmdArgs.push_back("-generate-arange-section");
3368 }
3369
3370 if (Args.hasFlag(options::OPT_fdebug_types_section,
3371 options::OPT_fno_debug_types_section, false)) {
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003372 if (!T.isOSBinFormatELF()) {
Jonas Devlieghere488bd012018-07-23 17:50:15 +00003373 D.Diag(diag::err_drv_unsupported_opt_for_target)
3374 << Args.getLastArg(options::OPT_fdebug_types_section)
3375 ->getAsString(Args)
3376 << T.getTriple();
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003377 } else if (checkDebugInfoOption(
3378 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3379 TC)) {
3380 CmdArgs.push_back("-mllvm");
3381 CmdArgs.push_back("-generate-type-units");
3382 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003383 }
3384
Paul Robinson1787f812017-09-28 18:37:02 +00003385 // Decide how to render forward declarations of template instantiations.
3386 // SCE wants full descriptions, others just get them in the name.
3387 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3388 CmdArgs.push_back("-debug-forward-template-params");
3389
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003390 // Do we need to explicitly import anonymous namespaces into the parent
3391 // scope?
Paul Robinsona8280812017-09-29 21:25:07 +00003392 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3393 CmdArgs.push_back("-dwarf-explicit-import");
3394
Alexey Bataevb83b4e42018-07-27 19:45:14 +00003395 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00003396}
3397
David L. Jonesf561aba2017-03-08 01:02:16 +00003398void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3399 const InputInfo &Output, const InputInfoList &Inputs,
3400 const ArgList &Args, const char *LinkingOutput) const {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003401 const auto &TC = getToolChain();
3402 const llvm::Triple &RawTriple = TC.getTriple();
3403 const llvm::Triple &Triple = TC.getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00003404 const std::string &TripleStr = Triple.getTriple();
3405
3406 bool KernelOrKext =
3407 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003408 const Driver &D = TC.getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00003409 ArgStringList CmdArgs;
3410
3411 // Check number of inputs for sanity. We need at least one input.
3412 assert(Inputs.size() >= 1 && "Must have at least one input.");
Yaxun Liu398612b2018-05-08 21:02:12 +00003413 // CUDA/HIP compilation may have multiple inputs (source file + results of
David L. Jonesf561aba2017-03-08 01:02:16 +00003414 // device-side compilations). OpenMP device jobs also take the host IR as a
Richard Smithcd35eff2018-09-15 01:21:16 +00003415 // second input. Module precompilation accepts a list of header files to
3416 // include as part of the module. All other jobs are expected to have exactly
3417 // one input.
David L. Jonesf561aba2017-03-08 01:02:16 +00003418 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
Yaxun Liu398612b2018-05-08 21:02:12 +00003419 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
David L. Jonesf561aba2017-03-08 01:02:16 +00003420 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
Richard Smithcd35eff2018-09-15 01:21:16 +00003421 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3422
3423 // A header module compilation doesn't have a main input file, so invent a
3424 // fake one as a placeholder.
Richard Smithcd35eff2018-09-15 01:21:16 +00003425 const char *ModuleName = [&]{
3426 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3427 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3428 }();
Benjamin Kramer5904c412018-11-05 12:46:02 +00003429 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
Richard Smithcd35eff2018-09-15 01:21:16 +00003430
3431 const InputInfo &Input =
3432 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3433
3434 InputInfoList ModuleHeaderInputs;
3435 const InputInfo *CudaDeviceInput = nullptr;
3436 const InputInfo *OpenMPDeviceInput = nullptr;
3437 for (const InputInfo &I : Inputs) {
3438 if (&I == &Input) {
3439 // This is the primary input.
Benjamin Kramer5904c412018-11-05 12:46:02 +00003440 } else if (IsHeaderModulePrecompile &&
Richard Smithcd35eff2018-09-15 01:21:16 +00003441 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
Benjamin Kramer5904c412018-11-05 12:46:02 +00003442 types::ID Expected = HeaderModuleInput.getType();
Richard Smithcd35eff2018-09-15 01:21:16 +00003443 if (I.getType() != Expected) {
3444 D.Diag(diag::err_drv_module_header_wrong_kind)
3445 << I.getFilename() << types::getTypeName(I.getType())
3446 << types::getTypeName(Expected);
3447 }
3448 ModuleHeaderInputs.push_back(I);
3449 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3450 CudaDeviceInput = &I;
3451 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3452 OpenMPDeviceInput = &I;
3453 } else {
3454 llvm_unreachable("unexpectedly given multiple inputs");
3455 }
3456 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003457
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003458 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003459 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003460 bool IsIAMCU = RawTriple.isOSIAMCU();
David L. Jonesf561aba2017-03-08 01:02:16 +00003461
Yaxun Liu398612b2018-05-08 21:02:12 +00003462 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3463 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3464 // Windows), we need to pass Windows-specific flags to cc1.
Fangrui Songe6e09562019-07-12 13:21:58 +00003465 if (IsCuda || IsHIP)
David L. Jonesf561aba2017-03-08 01:02:16 +00003466 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
David L. Jonesf561aba2017-03-08 01:02:16 +00003467
3468 // C++ is not supported for IAMCU.
3469 if (IsIAMCU && types::isCXX(Input.getType()))
3470 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3471
3472 // Invoke ourselves in -cc1 mode.
3473 //
3474 // FIXME: Implement custom jobs for internal actions.
3475 CmdArgs.push_back("-cc1");
3476
3477 // Add the "effective" target triple.
3478 CmdArgs.push_back("-triple");
3479 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3480
3481 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3482 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3483 Args.ClaimAllArgs(options::OPT_MJ);
3484 }
3485
Yaxun Liu398612b2018-05-08 21:02:12 +00003486 if (IsCuda || IsHIP) {
3487 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3488 // and vice-versa.
David L. Jonesf561aba2017-03-08 01:02:16 +00003489 std::string NormalizedTriple;
Yaxun Liu398612b2018-05-08 21:02:12 +00003490 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3491 JA.isDeviceOffloading(Action::OFK_HIP))
David L. Jonesf561aba2017-03-08 01:02:16 +00003492 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3493 ->getTriple()
3494 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003495 else {
3496 // Host-side compilation.
Yaxun Liu398612b2018-05-08 21:02:12 +00003497 NormalizedTriple =
3498 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3499 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3500 ->getTriple()
3501 .normalize();
Artem Belevich8fa28a02019-01-31 21:32:24 +00003502 if (IsCuda) {
3503 // We need to figure out which CUDA version we're compiling for, as that
3504 // determines how we load and launch GPU kernels.
3505 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3506 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3507 assert(CTC && "Expected valid CUDA Toolchain.");
3508 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3509 CmdArgs.push_back(Args.MakeArgString(
3510 Twine("-target-sdk-version=") +
3511 CudaVersionToString(CTC->CudaInstallation.version())));
3512 }
3513 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003514 CmdArgs.push_back("-aux-triple");
3515 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3516 }
3517
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003518 if (IsOpenMPDevice) {
3519 // We have to pass the triple of the host if compiling for an OpenMP device.
3520 std::string NormalizedTriple =
3521 C.getSingleOffloadToolChain<Action::OFK_Host>()
3522 ->getTriple()
3523 .normalize();
3524 CmdArgs.push_back("-aux-triple");
3525 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3526 }
3527
David L. Jonesf561aba2017-03-08 01:02:16 +00003528 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3529 Triple.getArch() == llvm::Triple::thumb)) {
3530 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3531 unsigned Version;
3532 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3533 if (Version < 7)
3534 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3535 << TripleStr;
3536 }
3537
3538 // Push all default warning arguments that are specific to
3539 // the given target. These come before user provided warning options
3540 // are provided.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003541 TC.addClangWarningOptions(CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00003542
3543 // Select the appropriate action.
3544 RewriteKind rewriteKind = RK_None;
3545
3546 if (isa<AnalyzeJobAction>(JA)) {
3547 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3548 CmdArgs.push_back("-analyze");
3549 } else if (isa<MigrateJobAction>(JA)) {
3550 CmdArgs.push_back("-migrate");
3551 } else if (isa<PreprocessJobAction>(JA)) {
3552 if (Output.getType() == types::TY_Dependencies)
3553 CmdArgs.push_back("-Eonly");
3554 else {
3555 CmdArgs.push_back("-E");
3556 if (Args.hasArg(options::OPT_rewrite_objc) &&
3557 !Args.hasArg(options::OPT_g_Group))
3558 CmdArgs.push_back("-P");
3559 }
3560 } else if (isa<AssembleJobAction>(JA)) {
3561 CmdArgs.push_back("-emit-obj");
3562
3563 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3564
3565 // Also ignore explicit -force_cpusubtype_ALL option.
3566 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3567 } else if (isa<PrecompileJobAction>(JA)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003568 if (JA.getType() == types::TY_Nothing)
3569 CmdArgs.push_back("-fsyntax-only");
3570 else if (JA.getType() == types::TY_ModuleFile)
Richard Smithcd35eff2018-09-15 01:21:16 +00003571 CmdArgs.push_back(IsHeaderModulePrecompile
3572 ? "-emit-header-module"
3573 : "-emit-module-interface");
David L. Jonesf561aba2017-03-08 01:02:16 +00003574 else
Erich Keane0a6b5b62018-12-04 14:34:09 +00003575 CmdArgs.push_back("-emit-pch");
David L. Jonesf561aba2017-03-08 01:02:16 +00003576 } else if (isa<VerifyPCHJobAction>(JA)) {
3577 CmdArgs.push_back("-verify-pch");
3578 } else {
3579 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3580 "Invalid action for clang tool.");
3581 if (JA.getType() == types::TY_Nothing) {
3582 CmdArgs.push_back("-fsyntax-only");
3583 } else if (JA.getType() == types::TY_LLVM_IR ||
3584 JA.getType() == types::TY_LTO_IR) {
3585 CmdArgs.push_back("-emit-llvm");
3586 } else if (JA.getType() == types::TY_LLVM_BC ||
3587 JA.getType() == types::TY_LTO_BC) {
3588 CmdArgs.push_back("-emit-llvm-bc");
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003589 } else if (JA.getType() == types::TY_IFS) {
3590 StringRef StubFormat =
3591 llvm::StringSwitch<StringRef>(
3592 Args.hasArg(options::OPT_iterface_stub_version_EQ)
3593 ? Args.getLastArgValue(options::OPT_iterface_stub_version_EQ)
3594 : "")
3595 .Case("experimental-yaml-elf-v1", "experimental-yaml-elf-v1")
3596 .Case("experimental-tapi-elf-v1", "experimental-tapi-elf-v1")
3597 .Default("");
3598
3599 if (StubFormat.empty())
3600 D.Diag(diag::err_drv_invalid_value)
3601 << "Must specify a valid interface stub format type using "
3602 << "-interface-stub-version=<experimental-tapi-elf-v1 | "
3603 "experimental-yaml-elf-v1>";
3604
3605 CmdArgs.push_back("-emit-interface-stubs");
3606 CmdArgs.push_back(
3607 Args.MakeArgString(Twine("-interface-stub-version=") + StubFormat));
David L. Jonesf561aba2017-03-08 01:02:16 +00003608 } else if (JA.getType() == types::TY_PP_Asm) {
3609 CmdArgs.push_back("-S");
3610 } else if (JA.getType() == types::TY_AST) {
3611 CmdArgs.push_back("-emit-pch");
3612 } else if (JA.getType() == types::TY_ModuleFile) {
3613 CmdArgs.push_back("-module-file-info");
3614 } else if (JA.getType() == types::TY_RewrittenObjC) {
3615 CmdArgs.push_back("-rewrite-objc");
3616 rewriteKind = RK_NonFragile;
3617 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3618 CmdArgs.push_back("-rewrite-objc");
3619 rewriteKind = RK_Fragile;
3620 } else {
3621 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3622 }
3623
3624 // Preserve use-list order by default when emitting bitcode, so that
3625 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3626 // same result as running passes here. For LTO, we don't need to preserve
3627 // the use-list order, since serialization to bitcode is part of the flow.
3628 if (JA.getType() == types::TY_LLVM_BC)
3629 CmdArgs.push_back("-emit-llvm-uselists");
3630
Artem Belevichecb178b2018-03-21 22:22:59 +00003631 // Device-side jobs do not support LTO.
3632 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3633 JA.isDeviceOffloading(Action::OFK_Host));
3634
3635 if (D.isUsingLTO() && !isDeviceOffloadAction) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003636 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3637
Paul Robinsond23f2a82017-07-13 21:25:47 +00003638 // The Darwin and PS4 linkers currently use the legacy LTO API, which
3639 // does not support LTO unit features (CFI, whole program vtable opt)
3640 // under ThinLTO.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003641 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00003642 D.getLTOMode() == LTOK_Full)
3643 CmdArgs.push_back("-flto-unit");
3644 }
3645 }
3646
3647 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3648 if (!types::isLLVMIR(Input.getType()))
Bob Haarman79434642019-07-15 20:51:44 +00003649 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003650 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3651 }
3652
Teresa Johnson6e5cec22018-04-17 20:21:53 +00003653 if (Args.getLastArg(options::OPT_save_temps_EQ))
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003654 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3655
David L. Jonesf561aba2017-03-08 01:02:16 +00003656 // Embed-bitcode option.
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003657 // Only white-listed flags below are allowed to be embedded.
David L. Jonesf561aba2017-03-08 01:02:16 +00003658 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3659 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3660 // Add flags implied by -fembed-bitcode.
3661 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3662 // Disable all llvm IR level optimizations.
3663 CmdArgs.push_back("-disable-llvm-passes");
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003664
Fangrui Song2632ebb2019-05-30 02:30:04 +00003665 // Render target options such as -fuse-init-array on modern ELF platforms.
3666 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3667
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003668 // reject options that shouldn't be supported in bitcode
3669 // also reject kernel/kext
3670 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3671 options::OPT_mkernel,
3672 options::OPT_fapple_kext,
3673 options::OPT_ffunction_sections,
3674 options::OPT_fno_function_sections,
3675 options::OPT_fdata_sections,
3676 options::OPT_fno_data_sections,
3677 options::OPT_funique_section_names,
3678 options::OPT_fno_unique_section_names,
3679 options::OPT_mrestrict_it,
3680 options::OPT_mno_restrict_it,
3681 options::OPT_mstackrealign,
3682 options::OPT_mno_stackrealign,
3683 options::OPT_mstack_alignment,
3684 options::OPT_mcmodel_EQ,
3685 options::OPT_mlong_calls,
3686 options::OPT_mno_long_calls,
3687 options::OPT_ggnu_pubnames,
3688 options::OPT_gdwarf_aranges,
3689 options::OPT_fdebug_types_section,
3690 options::OPT_fno_debug_types_section,
3691 options::OPT_fdwarf_directory_asm,
3692 options::OPT_fno_dwarf_directory_asm,
3693 options::OPT_mrelax_all,
3694 options::OPT_mno_relax_all,
3695 options::OPT_ftrap_function_EQ,
3696 options::OPT_ffixed_r9,
3697 options::OPT_mfix_cortex_a53_835769,
3698 options::OPT_mno_fix_cortex_a53_835769,
3699 options::OPT_ffixed_x18,
3700 options::OPT_mglobal_merge,
3701 options::OPT_mno_global_merge,
3702 options::OPT_mred_zone,
3703 options::OPT_mno_red_zone,
3704 options::OPT_Wa_COMMA,
3705 options::OPT_Xassembler,
3706 options::OPT_mllvm,
3707 };
3708 for (const auto &A : Args)
Fangrui Song75e74e02019-03-31 08:48:19 +00003709 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003710 std::end(kBitcodeOptionBlacklist))
3711 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3712
3713 // Render the CodeGen options that need to be passed.
3714 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3715 options::OPT_fno_optimize_sibling_calls))
3716 CmdArgs.push_back("-mdisable-tail-calls");
3717
3718 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3719 CmdArgs);
3720
3721 // Render ABI arguments
3722 switch (TC.getArch()) {
3723 default: break;
3724 case llvm::Triple::arm:
3725 case llvm::Triple::armeb:
3726 case llvm::Triple::thumbeb:
3727 RenderARMABI(Triple, Args, CmdArgs);
3728 break;
3729 case llvm::Triple::aarch64:
3730 case llvm::Triple::aarch64_be:
3731 RenderAArch64ABI(Triple, Args, CmdArgs);
3732 break;
3733 }
3734
3735 // Optimization level for CodeGen.
3736 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3737 if (A->getOption().matches(options::OPT_O4)) {
3738 CmdArgs.push_back("-O3");
3739 D.Diag(diag::warn_O4_is_O3);
3740 } else {
3741 A->render(Args, CmdArgs);
3742 }
3743 }
3744
3745 // Input/Output file.
3746 if (Output.getType() == types::TY_Dependencies) {
3747 // Handled with other dependency code.
3748 } else if (Output.isFilename()) {
3749 CmdArgs.push_back("-o");
3750 CmdArgs.push_back(Output.getFilename());
3751 } else {
3752 assert(Output.isNothing() && "Input output.");
3753 }
3754
3755 for (const auto &II : Inputs) {
3756 addDashXForInput(Args, II, CmdArgs);
3757 if (II.isFilename())
Martin Storsjob547ef22018-10-26 08:33:29 +00003758 CmdArgs.push_back(II.getFilename());
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003759 else
3760 II.getInputArg().renderAsInput(Args, CmdArgs);
3761 }
3762
3763 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3764 CmdArgs, Inputs));
3765 return;
David L. Jonesf561aba2017-03-08 01:02:16 +00003766 }
Saleem Abdulrasool51313bc2018-09-24 23:50:02 +00003767
David L. Jonesf561aba2017-03-08 01:02:16 +00003768 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3769 CmdArgs.push_back("-fembed-bitcode=marker");
3770
3771 // We normally speed up the clang process a bit by skipping destructors at
3772 // exit, but when we're generating diagnostics we can rely on some of the
3773 // cleanup.
3774 if (!C.isForDiagnostics())
3775 CmdArgs.push_back("-disable-free");
3776
David L. Jonesf561aba2017-03-08 01:02:16 +00003777#ifdef NDEBUG
Eric Fiselier123c7492018-02-07 18:36:51 +00003778 const bool IsAssertBuild = false;
3779#else
3780 const bool IsAssertBuild = true;
David L. Jonesf561aba2017-03-08 01:02:16 +00003781#endif
3782
Eric Fiselier123c7492018-02-07 18:36:51 +00003783 // Disable the verification pass in -asserts builds.
3784 if (!IsAssertBuild)
Eric Fiseliercca7ddd2018-02-07 19:17:03 +00003785 CmdArgs.push_back("-disable-llvm-verifier");
Eric Fiselier123c7492018-02-07 18:36:51 +00003786
3787 // Discard value names in assert builds unless otherwise specified.
Eric Fiseliera06ca4b2018-02-14 20:56:52 +00003788 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3789 options::OPT_fno_discard_value_names, !IsAssertBuild))
Eric Fiselier123c7492018-02-07 18:36:51 +00003790 CmdArgs.push_back("-discard-value-names");
3791
David L. Jonesf561aba2017-03-08 01:02:16 +00003792 // Set the main file name, so that debug info works even with
3793 // -save-temps.
3794 CmdArgs.push_back("-main-file-name");
3795 CmdArgs.push_back(getBaseInputName(Args, Input));
3796
3797 // Some flags which affect the language (via preprocessor
3798 // defines).
3799 if (Args.hasArg(options::OPT_static))
3800 CmdArgs.push_back("-static-define");
3801
Martin Storsjo434ef832018-08-06 19:48:44 +00003802 if (Args.hasArg(options::OPT_municode))
3803 CmdArgs.push_back("-DUNICODE");
3804
Saleem Abdulrasool24aafa52017-08-30 14:18:08 +00003805 if (isa<AnalyzeJobAction>(JA))
3806 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
David L. Jonesf561aba2017-03-08 01:02:16 +00003807
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003808 // Enable compatilibily mode to avoid analyzer-config related errors.
3809 // Since we can't access frontend flags through hasArg, let's manually iterate
3810 // through them.
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003811 bool FoundAnalyzerConfig = false;
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003812 for (auto Arg : Args.filtered(options::OPT_Xclang))
Artem Dergachev0ec95c82018-12-21 01:11:21 +00003813 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3814 FoundAnalyzerConfig = true;
3815 break;
3816 }
3817 if (!FoundAnalyzerConfig)
3818 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3819 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3820 FoundAnalyzerConfig = true;
3821 break;
3822 }
3823 if (FoundAnalyzerConfig)
3824 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
George Karpenkov6d45b1f2018-12-21 00:26:19 +00003825
David L. Jonesf561aba2017-03-08 01:02:16 +00003826 CheckCodeGenerationOptions(D, Args);
3827
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003828 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003829 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3830 if (FunctionAlignment) {
3831 CmdArgs.push_back("-function-alignment");
3832 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3833 }
3834
David L. Jonesf561aba2017-03-08 01:02:16 +00003835 llvm::Reloc::Model RelocationModel;
3836 unsigned PICLevel;
3837 bool IsPIE;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003838 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003839
3840 const char *RMName = RelocationModelName(RelocationModel);
3841
3842 if ((RelocationModel == llvm::Reloc::ROPI ||
3843 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3844 types::isCXX(Input.getType()) &&
3845 !Args.hasArg(options::OPT_fallow_unsupported))
3846 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3847
3848 if (RMName) {
3849 CmdArgs.push_back("-mrelocation-model");
3850 CmdArgs.push_back(RMName);
3851 }
3852 if (PICLevel > 0) {
3853 CmdArgs.push_back("-pic-level");
3854 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3855 if (IsPIE)
3856 CmdArgs.push_back("-pic-is-pie");
3857 }
3858
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00003859 if (RelocationModel == llvm::Reloc::ROPI ||
3860 RelocationModel == llvm::Reloc::ROPI_RWPI)
3861 CmdArgs.push_back("-fropi");
3862 if (RelocationModel == llvm::Reloc::RWPI ||
3863 RelocationModel == llvm::Reloc::ROPI_RWPI)
3864 CmdArgs.push_back("-frwpi");
3865
David L. Jonesf561aba2017-03-08 01:02:16 +00003866 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3867 CmdArgs.push_back("-meabi");
3868 CmdArgs.push_back(A->getValue());
3869 }
3870
3871 CmdArgs.push_back("-mthread-model");
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003872 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003873 if (!TC.isThreadModelSupported(A->getValue()))
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003874 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3875 << A->getValue() << A->getAsString(Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00003876 CmdArgs.push_back(A->getValue());
Jonathan Roelofs6fbb9e02017-09-07 22:01:25 +00003877 }
David L. Jonesf561aba2017-03-08 01:02:16 +00003878 else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00003879 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
David L. Jonesf561aba2017-03-08 01:02:16 +00003880
3881 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3882
Manoj Gupta4b3eefa2018-04-05 15:29:52 +00003883 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3884 options::OPT_fno_merge_all_constants, false))
3885 CmdArgs.push_back("-fmerge-all-constants");
David L. Jonesf561aba2017-03-08 01:02:16 +00003886
Manoj Guptada08f6a2018-07-19 00:44:52 +00003887 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3888 options::OPT_fdelete_null_pointer_checks, false))
3889 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3890
David L. Jonesf561aba2017-03-08 01:02:16 +00003891 // LLVM Code Generator Options.
3892
3893 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3894 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3895 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3896 options::OPT_frewrite_map_file_EQ)) {
3897 StringRef Map = A->getValue();
3898 if (!llvm::sys::fs::exists(Map)) {
3899 D.Diag(diag::err_drv_no_such_file) << Map;
3900 } else {
3901 CmdArgs.push_back("-frewrite-map-file");
3902 CmdArgs.push_back(A->getValue());
3903 A->claim();
3904 }
3905 }
3906 }
3907
3908 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3909 StringRef v = A->getValue();
3910 CmdArgs.push_back("-mllvm");
3911 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3912 A->claim();
3913 }
3914
3915 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3916 true))
3917 CmdArgs.push_back("-fno-jump-tables");
3918
Dehao Chen5e97f232017-08-24 21:37:33 +00003919 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3920 options::OPT_fno_profile_sample_accurate, false))
3921 CmdArgs.push_back("-fprofile-sample-accurate");
3922
David L. Jonesf561aba2017-03-08 01:02:16 +00003923 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3924 options::OPT_fno_preserve_as_comments, true))
3925 CmdArgs.push_back("-fno-preserve-as-comments");
3926
3927 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3928 CmdArgs.push_back("-mregparm");
3929 CmdArgs.push_back(A->getValue());
3930 }
3931
3932 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3933 options::OPT_freg_struct_return)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00003934 if (TC.getArch() != llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00003935 D.Diag(diag::err_drv_unsupported_opt_for_target)
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00003936 << A->getSpelling() << RawTriple.str();
David L. Jonesf561aba2017-03-08 01:02:16 +00003937 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3938 CmdArgs.push_back("-fpcc-struct-return");
3939 } else {
3940 assert(A->getOption().matches(options::OPT_freg_struct_return));
3941 CmdArgs.push_back("-freg-struct-return");
3942 }
3943 }
3944
3945 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3946 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3947
Yuanfang Chenff22ec32019-07-20 22:50:50 +00003948 CodeGenOptions::FramePointerKind FPKeepKind =
3949 getFramePointerKind(Args, RawTriple);
3950 const char *FPKeepKindStr = nullptr;
3951 switch (FPKeepKind) {
3952 case CodeGenOptions::FramePointerKind::None:
3953 FPKeepKindStr = "-mframe-pointer=none";
3954 break;
3955 case CodeGenOptions::FramePointerKind::NonLeaf:
3956 FPKeepKindStr = "-mframe-pointer=non-leaf";
3957 break;
3958 case CodeGenOptions::FramePointerKind::All:
3959 FPKeepKindStr = "-mframe-pointer=all";
3960 break;
Fangrui Songdc039662019-07-12 02:01:51 +00003961 }
Yuanfang Chenff22ec32019-07-20 22:50:50 +00003962 assert(FPKeepKindStr && "unknown FramePointerKind");
3963 CmdArgs.push_back(FPKeepKindStr);
3964
David L. Jonesf561aba2017-03-08 01:02:16 +00003965 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3966 options::OPT_fno_zero_initialized_in_bss))
3967 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3968
3969 bool OFastEnabled = isOptimizationLevelFast(Args);
3970 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3971 // enabled. This alias option is being used to simplify the hasFlag logic.
3972 OptSpecifier StrictAliasingAliasOption =
3973 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3974 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3975 // doesn't do any TBAA.
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00003976 bool TBAAOnByDefault = !D.IsCLMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00003977 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3978 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3979 CmdArgs.push_back("-relaxed-aliasing");
3980 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3981 options::OPT_fno_struct_path_tbaa))
3982 CmdArgs.push_back("-no-struct-path-tbaa");
3983 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3984 false))
3985 CmdArgs.push_back("-fstrict-enums");
3986 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3987 true))
3988 CmdArgs.push_back("-fno-strict-return");
Alex Lorenz1be800c52017-04-19 08:58:56 +00003989 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3990 options::OPT_fno_allow_editor_placeholders, false))
3991 CmdArgs.push_back("-fallow-editor-placeholders");
David L. Jonesf561aba2017-03-08 01:02:16 +00003992 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3993 options::OPT_fno_strict_vtable_pointers,
3994 false))
3995 CmdArgs.push_back("-fstrict-vtable-pointers");
Piotr Padlewskie368de32018-06-13 13:55:42 +00003996 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3997 options::OPT_fno_force_emit_vtables,
3998 false))
3999 CmdArgs.push_back("-fforce-emit-vtables");
David L. Jonesf561aba2017-03-08 01:02:16 +00004000 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4001 options::OPT_fno_optimize_sibling_calls))
4002 CmdArgs.push_back("-mdisable-tail-calls");
Akira Hatanaka627586b2018-03-02 01:53:15 +00004003 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
Akira Hatanaka9f9d7662018-03-10 05:55:21 +00004004 options::OPT_fescaping_block_tail_calls, false))
Akira Hatanaka627586b2018-03-02 01:53:15 +00004005 CmdArgs.push_back("-fno-escaping-block-tail-calls");
David L. Jonesf561aba2017-03-08 01:02:16 +00004006
Wei Mi9b3d6272017-10-16 16:50:27 +00004007 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4008 options::OPT_fno_fine_grained_bitfield_accesses);
4009
David L. Jonesf561aba2017-03-08 01:02:16 +00004010 // Handle segmented stacks.
4011 if (Args.hasArg(options::OPT_fsplit_stack))
4012 CmdArgs.push_back("-split-stacks");
4013
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004014 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004015
Fangrui Songc46d78d2019-07-12 02:32:15 +00004016 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_64,
4017 options::OPT_mlong_double_128)) {
Fangrui Song11cb39c2019-07-09 00:27:43 +00004018 if (TC.getArch() == llvm::Triple::x86 ||
4019 TC.getArch() == llvm::Triple::x86_64 ||
Fangrui Songc46d78d2019-07-12 02:32:15 +00004020 TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64())
4021 A->render(Args, CmdArgs);
4022 else
Fangrui Song11cb39c2019-07-09 00:27:43 +00004023 D.Diag(diag::err_drv_unsupported_opt_for_target)
4024 << A->getAsString(Args) << TripleStr;
Fangrui Song11cb39c2019-07-09 00:27:43 +00004025 }
4026
David L. Jonesf561aba2017-03-08 01:02:16 +00004027 // Decide whether to use verbose asm. Verbose assembly is the default on
4028 // toolchains which have the integrated assembler on by default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004029 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
David L. Jonesf561aba2017-03-08 01:02:16 +00004030 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4031 IsIntegratedAssemblerDefault) ||
4032 Args.hasArg(options::OPT_dA))
4033 CmdArgs.push_back("-masm-verbose");
4034
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004035 if (!TC.useIntegratedAs())
David L. Jonesf561aba2017-03-08 01:02:16 +00004036 CmdArgs.push_back("-no-integrated-as");
4037
4038 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4039 CmdArgs.push_back("-mdebug-pass");
4040 CmdArgs.push_back("Structure");
4041 }
4042 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4043 CmdArgs.push_back("-mdebug-pass");
4044 CmdArgs.push_back("Arguments");
4045 }
4046
4047 // Enable -mconstructor-aliases except on darwin, where we have to work around
4048 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4049 // aliases aren't supported.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004050 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
David L. Jonesf561aba2017-03-08 01:02:16 +00004051 CmdArgs.push_back("-mconstructor-aliases");
4052
4053 // Darwin's kernel doesn't support guard variables; just die if we
4054 // try to use them.
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004055 if (KernelOrKext && RawTriple.isOSDarwin())
David L. Jonesf561aba2017-03-08 01:02:16 +00004056 CmdArgs.push_back("-fforbid-guard-variables");
4057
4058 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4059 false)) {
4060 CmdArgs.push_back("-mms-bitfields");
4061 }
4062
4063 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4064 options::OPT_mno_pie_copy_relocations,
4065 false)) {
4066 CmdArgs.push_back("-mpie-copy-relocations");
4067 }
4068
Sriraman Tallam5c651482017-11-07 19:37:51 +00004069 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4070 CmdArgs.push_back("-fno-plt");
4071 }
4072
Vedant Kumardf502592017-09-12 22:51:53 +00004073 // -fhosted is default.
4074 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4075 // use Freestanding.
4076 bool Freestanding =
4077 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4078 KernelOrKext;
4079 if (Freestanding)
4080 CmdArgs.push_back("-ffreestanding");
4081
David L. Jonesf561aba2017-03-08 01:02:16 +00004082 // This is a coarse approximation of what llvm-gcc actually does, both
4083 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4084 // complicated ways.
4085 bool AsynchronousUnwindTables =
4086 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4087 options::OPT_fno_asynchronous_unwind_tables,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004088 (TC.IsUnwindTablesDefault(Args) ||
4089 TC.getSanitizerArgs().needsUnwindTables()) &&
Vedant Kumardf502592017-09-12 22:51:53 +00004090 !Freestanding);
David L. Jonesf561aba2017-03-08 01:02:16 +00004091 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4092 AsynchronousUnwindTables))
4093 CmdArgs.push_back("-munwind-tables");
4094
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004095 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
David L. Jonesf561aba2017-03-08 01:02:16 +00004096
David L. Jonesf561aba2017-03-08 01:02:16 +00004097 // FIXME: Handle -mtune=.
4098 (void)Args.hasArg(options::OPT_mtune_EQ);
4099
4100 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4101 CmdArgs.push_back("-mcode-model");
4102 CmdArgs.push_back(A->getValue());
4103 }
4104
4105 // Add the target cpu
4106 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4107 if (!CPU.empty()) {
4108 CmdArgs.push_back("-target-cpu");
4109 CmdArgs.push_back(Args.MakeArgString(CPU));
4110 }
4111
Saleem Abdulrasool6c3ed7b2017-09-03 04:47:00 +00004112 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004113
David L. Jonesf561aba2017-03-08 01:02:16 +00004114 // These two are potentially updated by AddClangCLArgs.
4115 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4116 bool EmitCodeView = false;
4117
4118 // Add clang-cl arguments.
4119 types::ID InputType = Input.getType();
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004120 if (D.IsCLMode())
David L. Jonesf561aba2017-03-08 01:02:16 +00004121 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4122
George Rimar91829ee2018-11-14 09:22:16 +00004123 DwarfFissionKind DwarfFission;
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004124 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
George Rimar91829ee2018-11-14 09:22:16 +00004125 CmdArgs, DebugInfoKind, DwarfFission);
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004126
4127 // Add the split debug info name to the command lines here so we
4128 // can propagate it to the backend.
George Rimar91829ee2018-11-14 09:22:16 +00004129 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
Fangrui Songee957e02019-03-28 08:24:00 +00004130 TC.getTriple().isOSBinFormatELF() &&
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004131 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4132 isa<BackendJobAction>(JA));
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004133 if (SplitDWARF) {
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004134 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4135 CmdArgs.push_back("-split-dwarf-file");
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004136 CmdArgs.push_back(SplitDWARFOut);
Aaron Pucherte1dc4952019-06-15 15:38:51 +00004137 if (DwarfFission == DwarfFissionKind::Split) {
4138 CmdArgs.push_back("-split-dwarf-output");
4139 CmdArgs.push_back(SplitDWARFOut);
4140 }
Saleem Abdulrasool9934eab2017-09-03 04:46:59 +00004141 }
4142
David L. Jonesf561aba2017-03-08 01:02:16 +00004143 // Pass the linker version in use.
4144 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4145 CmdArgs.push_back("-target-linker-version");
4146 CmdArgs.push_back(A->getValue());
4147 }
4148
David L. Jonesf561aba2017-03-08 01:02:16 +00004149 // Explicitly error on some things we know we don't support and can't just
4150 // ignore.
4151 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4152 Arg *Unsupported;
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004153 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004154 TC.getArch() == llvm::Triple::x86) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004155 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4156 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4157 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4158 << Unsupported->getOption().getName();
4159 }
Eric Christopher758aad72017-03-21 22:06:18 +00004160 // The faltivec option has been superseded by the maltivec option.
4161 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4162 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4163 << Unsupported->getOption().getName()
4164 << "please use -maltivec and include altivec.h explicitly";
4165 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4166 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4167 << Unsupported->getOption().getName() << "please use -mno-altivec";
David L. Jonesf561aba2017-03-08 01:02:16 +00004168 }
4169
4170 Args.AddAllArgs(CmdArgs, options::OPT_v);
4171 Args.AddLastArg(CmdArgs, options::OPT_H);
4172 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4173 CmdArgs.push_back("-header-include-file");
4174 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4175 : "-");
4176 }
4177 Args.AddLastArg(CmdArgs, options::OPT_P);
4178 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4179
4180 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4181 CmdArgs.push_back("-diagnostic-log-file");
4182 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4183 : "-");
4184 }
4185
David L. Jonesf561aba2017-03-08 01:02:16 +00004186 bool UseSeparateSections = isUseSeparateSections(Triple);
4187
4188 if (Args.hasFlag(options::OPT_ffunction_sections,
4189 options::OPT_fno_function_sections, UseSeparateSections)) {
4190 CmdArgs.push_back("-ffunction-sections");
4191 }
4192
4193 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4194 UseSeparateSections)) {
4195 CmdArgs.push_back("-fdata-sections");
4196 }
4197
4198 if (!Args.hasFlag(options::OPT_funique_section_names,
4199 options::OPT_fno_unique_section_names, true))
4200 CmdArgs.push_back("-fno-unique-section-names");
4201
Nico Weber908b6972019-06-26 17:51:47 +00004202 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4203 options::OPT_finstrument_functions_after_inlining,
4204 options::OPT_finstrument_function_entry_bare);
David L. Jonesf561aba2017-03-08 01:02:16 +00004205
Artem Belevichc30bcad2018-01-24 17:41:02 +00004206 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4207 // sampling, overhead of call arc collection is way too high and there's no
4208 // way to collect the output.
4209 if (!Triple.isNVPTX())
Russell Gallop7a9ccf82019-05-14 14:01:40 +00004210 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004211
Nico Weber908b6972019-06-26 17:51:47 +00004212 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
Richard Smithf667ad52017-08-26 01:04:35 +00004213
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004214 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
Pierre Gousseau53b5cfb2018-12-18 17:03:35 +00004215 if (RawTriple.isPS4CPU() &&
4216 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004217 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4218 PS4cpu::addSanitizerArgs(TC, CmdArgs);
Pierre Gousseau1abf9432018-06-06 14:04:15 +00004219 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004220
4221 // Pass options for controlling the default header search paths.
4222 if (Args.hasArg(options::OPT_nostdinc)) {
4223 CmdArgs.push_back("-nostdsysteminc");
4224 CmdArgs.push_back("-nobuiltininc");
4225 } else {
4226 if (Args.hasArg(options::OPT_nostdlibinc))
4227 CmdArgs.push_back("-nostdsysteminc");
4228 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4229 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4230 }
4231
4232 // Pass the path to compiler resource files.
4233 CmdArgs.push_back("-resource-dir");
4234 CmdArgs.push_back(D.ResourceDir.c_str());
4235
4236 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4237
Saleem Abdulrasool0a322c62017-08-31 15:35:01 +00004238 RenderARCMigrateToolOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004239
4240 // Add preprocessing options like -I, -D, etc. if we are using the
4241 // preprocessor.
4242 //
4243 // FIXME: Support -fpreprocessed
4244 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4245 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4246
4247 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4248 // that "The compiler can only warn and ignore the option if not recognized".
4249 // When building with ccache, it will pass -D options to clang even on
4250 // preprocessed inputs and configure concludes that -fPIC is not supported.
4251 Args.ClaimAllArgs(options::OPT_D);
4252
4253 // Manually translate -O4 to -O3; let clang reject others.
4254 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4255 if (A->getOption().matches(options::OPT_O4)) {
4256 CmdArgs.push_back("-O3");
4257 D.Diag(diag::warn_O4_is_O3);
4258 } else {
4259 A->render(Args, CmdArgs);
4260 }
4261 }
4262
4263 // Warn about ignored options to clang.
4264 for (const Arg *A :
4265 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4266 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4267 A->claim();
4268 }
4269
Joerg Sonnenbergerc9199682017-07-01 21:36:21 +00004270 for (const Arg *A :
4271 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4272 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4273 A->claim();
4274 }
4275
David L. Jonesf561aba2017-03-08 01:02:16 +00004276 claimNoWarnArgs(Args);
4277
4278 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4279
4280 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4281 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4282 CmdArgs.push_back("-pedantic");
4283 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4284 Args.AddLastArg(CmdArgs, options::OPT_w);
4285
Leonard Chanf921d852018-06-04 16:07:52 +00004286 // Fixed point flags
4287 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4288 /*Default=*/false))
4289 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4290
David L. Jonesf561aba2017-03-08 01:02:16 +00004291 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4292 // (-ansi is equivalent to -std=c89 or -std=c++98).
4293 //
4294 // If a std is supplied, only add -trigraphs if it follows the
4295 // option.
4296 bool ImplyVCPPCXXVer = false;
Richard Smithb1b580e2019-04-14 11:11:37 +00004297 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4298 if (Std) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004299 if (Std->getOption().matches(options::OPT_ansi))
4300 if (types::isCXX(InputType))
4301 CmdArgs.push_back("-std=c++98");
4302 else
4303 CmdArgs.push_back("-std=c89");
4304 else
4305 Std->render(Args, CmdArgs);
4306
4307 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4308 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4309 options::OPT_ftrigraphs,
4310 options::OPT_fno_trigraphs))
4311 if (A != Std)
4312 A->render(Args, CmdArgs);
4313 } else {
4314 // Honor -std-default.
4315 //
4316 // FIXME: Clang doesn't correctly handle -std= when the input language
4317 // doesn't match. For the time being just ignore this for C++ inputs;
4318 // eventually we want to do all the standard defaulting here instead of
4319 // splitting it between the driver and clang -cc1.
4320 if (!types::isCXX(InputType))
4321 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4322 /*Joined=*/true);
4323 else if (IsWindowsMSVC)
4324 ImplyVCPPCXXVer = true;
4325
4326 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4327 options::OPT_fno_trigraphs);
4328 }
4329
4330 // GCC's behavior for -Wwrite-strings is a bit strange:
4331 // * In C, this "warning flag" changes the types of string literals from
4332 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4333 // for the discarded qualifier.
4334 // * In C++, this is just a normal warning flag.
4335 //
4336 // Implementing this warning correctly in C is hard, so we follow GCC's
4337 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4338 // a non-const char* in C, rather than using this crude hack.
4339 if (!types::isCXX(InputType)) {
4340 // FIXME: This should behave just like a warning flag, and thus should also
4341 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4342 Arg *WriteStrings =
4343 Args.getLastArg(options::OPT_Wwrite_strings,
4344 options::OPT_Wno_write_strings, options::OPT_w);
4345 if (WriteStrings &&
4346 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4347 CmdArgs.push_back("-fconst-strings");
4348 }
4349
4350 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4351 // during C++ compilation, which it is by default. GCC keeps this define even
4352 // in the presence of '-w', match this behavior bug-for-bug.
4353 if (types::isCXX(InputType) &&
4354 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4355 true)) {
4356 CmdArgs.push_back("-fdeprecated-macro");
4357 }
4358
4359 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4360 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4361 if (Asm->getOption().matches(options::OPT_fasm))
4362 CmdArgs.push_back("-fgnu-keywords");
4363 else
4364 CmdArgs.push_back("-fno-gnu-keywords");
4365 }
4366
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004367 if (ShouldDisableDwarfDirectory(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004368 CmdArgs.push_back("-fno-dwarf-directory-asm");
4369
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004370 if (ShouldDisableAutolink(Args, TC))
David L. Jonesf561aba2017-03-08 01:02:16 +00004371 CmdArgs.push_back("-fno-autolink");
4372
4373 // Add in -fdebug-compilation-dir if necessary.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00004374 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00004375
Paul Robinson9b292b42018-07-10 15:15:24 +00004376 addDebugPrefixMapArg(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004377
4378 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4379 options::OPT_ftemplate_depth_EQ)) {
4380 CmdArgs.push_back("-ftemplate-depth");
4381 CmdArgs.push_back(A->getValue());
4382 }
4383
4384 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4385 CmdArgs.push_back("-foperator-arrow-depth");
4386 CmdArgs.push_back(A->getValue());
4387 }
4388
4389 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4390 CmdArgs.push_back("-fconstexpr-depth");
4391 CmdArgs.push_back(A->getValue());
4392 }
4393
4394 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4395 CmdArgs.push_back("-fconstexpr-steps");
4396 CmdArgs.push_back(A->getValue());
4397 }
4398
4399 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4400 CmdArgs.push_back("-fbracket-depth");
4401 CmdArgs.push_back(A->getValue());
4402 }
4403
4404 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4405 options::OPT_Wlarge_by_value_copy_def)) {
4406 if (A->getNumValues()) {
4407 StringRef bytes = A->getValue();
4408 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4409 } else
4410 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4411 }
4412
4413 if (Args.hasArg(options::OPT_relocatable_pch))
4414 CmdArgs.push_back("-relocatable-pch");
4415
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004416 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4417 static const char *kCFABIs[] = {
4418 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4419 };
4420
4421 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4422 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4423 else
4424 A->render(Args, CmdArgs);
4425 }
4426
David L. Jonesf561aba2017-03-08 01:02:16 +00004427 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4428 CmdArgs.push_back("-fconstant-string-class");
4429 CmdArgs.push_back(A->getValue());
4430 }
4431
4432 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4433 CmdArgs.push_back("-ftabstop");
4434 CmdArgs.push_back(A->getValue());
4435 }
4436
Sean Eveson5110d4f2018-01-08 13:42:26 +00004437 if (Args.hasFlag(options::OPT_fstack_size_section,
4438 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4439 CmdArgs.push_back("-fstack-size-section");
4440
David L. Jonesf561aba2017-03-08 01:02:16 +00004441 CmdArgs.push_back("-ferror-limit");
4442 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4443 CmdArgs.push_back(A->getValue());
4444 else
4445 CmdArgs.push_back("19");
4446
4447 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4448 CmdArgs.push_back("-fmacro-backtrace-limit");
4449 CmdArgs.push_back(A->getValue());
4450 }
4451
4452 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4453 CmdArgs.push_back("-ftemplate-backtrace-limit");
4454 CmdArgs.push_back(A->getValue());
4455 }
4456
4457 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4458 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4459 CmdArgs.push_back(A->getValue());
4460 }
4461
4462 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4463 CmdArgs.push_back("-fspell-checking-limit");
4464 CmdArgs.push_back(A->getValue());
4465 }
4466
4467 // Pass -fmessage-length=.
4468 CmdArgs.push_back("-fmessage-length");
4469 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4470 CmdArgs.push_back(A->getValue());
4471 } else {
4472 // If -fmessage-length=N was not specified, determine whether this is a
4473 // terminal and, if so, implicitly define -fmessage-length appropriately.
4474 unsigned N = llvm::sys::Process::StandardErrColumns();
4475 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4476 }
4477
4478 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4479 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4480 options::OPT_fvisibility_ms_compat)) {
4481 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4482 CmdArgs.push_back("-fvisibility");
4483 CmdArgs.push_back(A->getValue());
4484 } else {
4485 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4486 CmdArgs.push_back("-fvisibility");
4487 CmdArgs.push_back("hidden");
4488 CmdArgs.push_back("-ftype-visibility");
4489 CmdArgs.push_back("default");
4490 }
4491 }
4492
4493 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
Petr Hosek821b38f2018-12-04 03:25:25 +00004494 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
David L. Jonesf561aba2017-03-08 01:02:16 +00004495
4496 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4497
David L. Jonesf561aba2017-03-08 01:02:16 +00004498 // Forward -f (flag) options which we can pass directly.
4499 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4500 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00004501 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004502 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004503 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4504 options::OPT_fno_emulated_tls);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00004505 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00004506
David L. Jonesf561aba2017-03-08 01:02:16 +00004507 // AltiVec-like language extensions aren't relevant for assembling.
Eric Christopher758aad72017-03-21 22:06:18 +00004508 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
David L. Jonesf561aba2017-03-08 01:02:16 +00004509 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
Eric Christopher758aad72017-03-21 22:06:18 +00004510
David L. Jonesf561aba2017-03-08 01:02:16 +00004511 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4512 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4513
4514 // Forward flags for OpenMP. We don't do this if the current action is an
4515 // device offloading action other than OpenMP.
4516 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4517 options::OPT_fno_openmp, false) &&
4518 (JA.isDeviceOffloading(Action::OFK_None) ||
4519 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00004520 switch (D.getOpenMPRuntime(Args)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004521 case Driver::OMPRT_OMP:
4522 case Driver::OMPRT_IOMP5:
4523 // Clang can generate useful OpenMP code for these two runtime libraries.
4524 CmdArgs.push_back("-fopenmp");
4525
4526 // If no option regarding the use of TLS in OpenMP codegeneration is
4527 // given, decide a default based on the target. Otherwise rely on the
4528 // options and pass the right information to the frontend.
4529 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4530 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4531 CmdArgs.push_back("-fnoopenmp-use-tls");
Alexey Bataev66f95772018-05-21 16:40:32 +00004532 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4533 options::OPT_fno_openmp_simd);
David L. Jonesf561aba2017-03-08 01:02:16 +00004534 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
Alexey Bataeve4090182018-11-02 14:54:07 +00004535 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4536 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004537 Args.AddAllArgs(CmdArgs,
4538 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004539 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4540 options::OPT_fno_openmp_optimistic_collapse,
4541 /*Default=*/false))
4542 CmdArgs.push_back("-fopenmp-optimistic-collapse");
Carlo Bertolli79712092018-02-28 20:48:35 +00004543
4544 // When in OpenMP offloading mode with NVPTX target, forward
4545 // cuda-mode flag
Alexey Bataev80a9a612018-08-30 14:45:24 +00004546 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4547 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4548 CmdArgs.push_back("-fopenmp-cuda-mode");
4549
4550 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4551 // is required.
4552 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4553 options::OPT_fno_openmp_cuda_force_full_runtime,
4554 /*Default=*/false))
4555 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
David L. Jonesf561aba2017-03-08 01:02:16 +00004556 break;
4557 default:
4558 // By default, if Clang doesn't know how to generate useful OpenMP code
4559 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4560 // down to the actual compilation.
4561 // FIXME: It would be better to have a mode which *only* omits IR
4562 // generation based on the OpenMP support so that we get consistent
4563 // semantic analysis, etc.
4564 break;
4565 }
Alexey Bataeve927ca72017-12-29 17:36:15 +00004566 } else {
4567 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4568 options::OPT_fno_openmp_simd);
4569 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004570 }
4571
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004572 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4573 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
David L. Jonesf561aba2017-03-08 01:02:16 +00004574
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004575 const XRayArgs &XRay = TC.getXRayArgs();
4576 XRay.addArgs(TC, Args, CmdArgs, InputType);
Dean Michael Berris835832d2017-03-30 00:29:36 +00004577
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004578 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004579 Args.AddLastArg(CmdArgs, options::OPT_pg);
4580
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004581 if (TC.SupportsProfiling())
David L. Jonesf561aba2017-03-08 01:02:16 +00004582 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4583
4584 // -flax-vector-conversions is default.
4585 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4586 options::OPT_fno_lax_vector_conversions))
4587 CmdArgs.push_back("-fno-lax-vector-conversions");
4588
4589 if (Args.getLastArg(options::OPT_fapple_kext) ||
4590 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4591 CmdArgs.push_back("-fapple-kext");
4592
4593 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4594 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4595 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4596 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
Anton Afanasyevd880de22019-03-30 08:42:48 +00004597 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00004598 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004599 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
Craig Topper3205dbb2019-03-21 20:07:24 +00004600 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
David L. Jonesf561aba2017-03-08 01:02:16 +00004601
4602 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4603 CmdArgs.push_back("-ftrapv-handler");
4604 CmdArgs.push_back(A->getValue());
4605 }
4606
4607 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4608
4609 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4610 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4611 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4612 if (A->getOption().matches(options::OPT_fwrapv))
4613 CmdArgs.push_back("-fwrapv");
4614 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4615 options::OPT_fno_strict_overflow)) {
4616 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4617 CmdArgs.push_back("-fwrapv");
4618 }
4619
4620 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4621 options::OPT_fno_reroll_loops))
4622 if (A->getOption().matches(options::OPT_freroll_loops))
4623 CmdArgs.push_back("-freroll-loops");
4624
4625 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4626 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4627 options::OPT_fno_unroll_loops);
4628
4629 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4630
Zola Bridgesc8666792018-11-26 18:13:31 +00004631 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4632 false))
4633 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
Chandler Carruth664aa862018-09-04 12:38:00 +00004634
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004635 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
JF Bastien14daa202018-12-18 05:12:21 +00004636 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004637
4638 // Translate -mstackrealign
4639 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4640 false))
4641 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4642
4643 if (Args.hasArg(options::OPT_mstack_alignment)) {
4644 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4645 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4646 }
4647
4648 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4649 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4650
4651 if (!Size.empty())
4652 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4653 else
4654 CmdArgs.push_back("-mstack-probe-size=0");
4655 }
4656
Hans Wennborgd43f40d2018-02-23 13:47:36 +00004657 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4658 options::OPT_mno_stack_arg_probe, true))
4659 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4660
David L. Jonesf561aba2017-03-08 01:02:16 +00004661 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4662 options::OPT_mno_restrict_it)) {
4663 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Eli Friedman01d349b2018-04-12 22:21:36 +00004664 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004665 CmdArgs.push_back("-arm-restrict-it");
4666 } else {
Eli Friedman01d349b2018-04-12 22:21:36 +00004667 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004668 CmdArgs.push_back("-arm-no-restrict-it");
4669 }
4670 } else if (Triple.isOSWindows() &&
4671 (Triple.getArch() == llvm::Triple::arm ||
4672 Triple.getArch() == llvm::Triple::thumb)) {
4673 // Windows on ARM expects restricted IT blocks
Eli Friedman01d349b2018-04-12 22:21:36 +00004674 CmdArgs.push_back("-mllvm");
David L. Jonesf561aba2017-03-08 01:02:16 +00004675 CmdArgs.push_back("-arm-restrict-it");
4676 }
4677
4678 // Forward -cl options to -cc1
Saleem Abdulrasool68c808f62017-08-29 23:59:07 +00004679 RenderOpenCLOptions(Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004680
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00004681 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4682 CmdArgs.push_back(
4683 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4684 }
4685
David L. Jonesf561aba2017-03-08 01:02:16 +00004686 // Forward -f options with positive and negative forms; we translate
4687 // these by hand.
Dehao Chenea4b78f2017-03-21 21:40:53 +00004688 if (Arg *A = getLastProfileSampleUseArg(Args)) {
Rong Xua4a09b22019-03-04 20:21:31 +00004689 auto *PGOArg = Args.getLastArg(
4690 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4691 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4692 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4693 if (PGOArg)
4694 D.Diag(diag::err_drv_argument_not_allowed_with)
4695 << "SampleUse with PGO options";
4696
David L. Jonesf561aba2017-03-08 01:02:16 +00004697 StringRef fname = A->getValue();
4698 if (!llvm::sys::fs::exists(fname))
4699 D.Diag(diag::err_drv_no_such_file) << fname;
4700 else
4701 A->render(Args, CmdArgs);
4702 }
Richard Smith8654ae52018-10-10 23:13:35 +00004703 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00004704
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004705 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004706
4707 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4708 options::OPT_fno_assume_sane_operator_new))
4709 CmdArgs.push_back("-fno-assume-sane-operator-new");
4710
4711 // -fblocks=0 is default.
4712 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004713 TC.IsBlocksDefault()) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004714 (Args.hasArg(options::OPT_fgnu_runtime) &&
4715 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4716 !Args.hasArg(options::OPT_fno_blocks))) {
4717 CmdArgs.push_back("-fblocks");
4718
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004719 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
David L. Jonesf561aba2017-03-08 01:02:16 +00004720 CmdArgs.push_back("-fblocks-runtime-optional");
4721 }
4722
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004723 // -fencode-extended-block-signature=1 is default.
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004724 if (TC.IsEncodeExtendedBlockSignatureDefault())
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004725 CmdArgs.push_back("-fencode-extended-block-signature");
4726
David L. Jonesf561aba2017-03-08 01:02:16 +00004727 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4728 false) &&
4729 types::isCXX(InputType)) {
4730 CmdArgs.push_back("-fcoroutines-ts");
4731 }
4732
Aaron Ballman61736552017-10-21 20:28:58 +00004733 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4734 options::OPT_fno_double_square_bracket_attributes);
4735
David L. Jonesf561aba2017-03-08 01:02:16 +00004736 // -faccess-control is default.
4737 if (Args.hasFlag(options::OPT_fno_access_control,
4738 options::OPT_faccess_control, false))
4739 CmdArgs.push_back("-fno-access-control");
4740
4741 // -felide-constructors is the default.
4742 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4743 options::OPT_felide_constructors, false))
4744 CmdArgs.push_back("-fno-elide-constructors");
4745
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004746 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
David L. Jonesf561aba2017-03-08 01:02:16 +00004747
4748 if (KernelOrKext || (types::isCXX(InputType) &&
Sunil Srivastava2ada2492018-05-18 23:32:01 +00004749 (RTTIMode == ToolChain::RM_Disabled)))
David L. Jonesf561aba2017-03-08 01:02:16 +00004750 CmdArgs.push_back("-fno-rtti");
4751
4752 // -fshort-enums=0 is default for all architectures except Hexagon.
4753 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004754 TC.getArch() == llvm::Triple::hexagon))
David L. Jonesf561aba2017-03-08 01:02:16 +00004755 CmdArgs.push_back("-fshort-enums");
4756
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00004757 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004758
4759 // -fuse-cxa-atexit is default.
4760 if (!Args.hasFlag(
4761 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
Saleem Abdulrasool015bded2017-09-11 20:18:09 +00004762 !RawTriple.isOSWindows() &&
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004763 TC.getArch() != llvm::Triple::xcore &&
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004764 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4765 RawTriple.hasEnvironment())) ||
David L. Jonesf561aba2017-03-08 01:02:16 +00004766 KernelOrKext)
4767 CmdArgs.push_back("-fno-use-cxa-atexit");
4768
Akira Hatanaka617e2612018-04-17 18:41:52 +00004769 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4770 options::OPT_fno_register_global_dtors_with_atexit,
Akira Hatanaka18db58e2018-04-27 01:42:33 +00004771 RawTriple.isOSDarwin() && !KernelOrKext))
Akira Hatanaka617e2612018-04-17 18:41:52 +00004772 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4773
David L. Jonesf561aba2017-03-08 01:02:16 +00004774 // -fms-extensions=0 is default.
4775 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4776 IsWindowsMSVC))
4777 CmdArgs.push_back("-fms-extensions");
4778
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004779 // -fno-use-line-directives is default.
David L. Jonesf561aba2017-03-08 01:02:16 +00004780 if (Args.hasFlag(options::OPT_fuse_line_directives,
Martin Storsjof1f8f4a2018-05-09 09:11:01 +00004781 options::OPT_fno_use_line_directives, false))
David L. Jonesf561aba2017-03-08 01:02:16 +00004782 CmdArgs.push_back("-fuse-line-directives");
4783
4784 // -fms-compatibility=0 is default.
4785 if (Args.hasFlag(options::OPT_fms_compatibility,
4786 options::OPT_fno_ms_compatibility,
4787 (IsWindowsMSVC &&
4788 Args.hasFlag(options::OPT_fms_extensions,
4789 options::OPT_fno_ms_extensions, true))))
4790 CmdArgs.push_back("-fms-compatibility");
4791
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004792 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
David L. Jonesf561aba2017-03-08 01:02:16 +00004793 if (!MSVT.empty())
4794 CmdArgs.push_back(
4795 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4796
4797 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4798 if (ImplyVCPPCXXVer) {
4799 StringRef LanguageStandard;
4800 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
Richard Smithb1b580e2019-04-14 11:11:37 +00004801 Std = StdArg;
David L. Jonesf561aba2017-03-08 01:02:16 +00004802 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4803 .Case("c++14", "-std=c++14")
Martell Malonef6f6a9c2017-10-15 17:27:58 +00004804 .Case("c++17", "-std=c++17")
4805 .Case("c++latest", "-std=c++2a")
David L. Jonesf561aba2017-03-08 01:02:16 +00004806 .Default("");
4807 if (LanguageStandard.empty())
4808 D.Diag(clang::diag::warn_drv_unused_argument)
4809 << StdArg->getAsString(Args);
4810 }
4811
4812 if (LanguageStandard.empty()) {
4813 if (IsMSVC2015Compatible)
4814 LanguageStandard = "-std=c++14";
4815 else
4816 LanguageStandard = "-std=c++11";
4817 }
4818
4819 CmdArgs.push_back(LanguageStandard.data());
4820 }
4821
4822 // -fno-borland-extensions is default.
4823 if (Args.hasFlag(options::OPT_fborland_extensions,
4824 options::OPT_fno_borland_extensions, false))
4825 CmdArgs.push_back("-fborland-extensions");
4826
4827 // -fno-declspec is default, except for PS4.
4828 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004829 RawTriple.isPS4()))
David L. Jonesf561aba2017-03-08 01:02:16 +00004830 CmdArgs.push_back("-fdeclspec");
4831 else if (Args.hasArg(options::OPT_fno_declspec))
4832 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4833
4834 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4835 // than 19.
4836 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4837 options::OPT_fno_threadsafe_statics,
4838 !IsWindowsMSVC || IsMSVC2015Compatible))
4839 CmdArgs.push_back("-fno-threadsafe-statics");
4840
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004841 // -fno-delayed-template-parsing is default, except when targeting MSVC.
Reid Klecknerea2683e2017-08-28 17:59:24 +00004842 // Many old Windows SDK versions require this to parse.
4843 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4844 // compiler. We should be able to disable this by default at some point.
David L. Jonesf561aba2017-03-08 01:02:16 +00004845 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4846 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4847 CmdArgs.push_back("-fdelayed-template-parsing");
4848
4849 // -fgnu-keywords default varies depending on language; only pass if
4850 // specified.
Nico Weber908b6972019-06-26 17:51:47 +00004851 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4852 options::OPT_fno_gnu_keywords);
David L. Jonesf561aba2017-03-08 01:02:16 +00004853
4854 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4855 false))
4856 CmdArgs.push_back("-fgnu89-inline");
4857
4858 if (Args.hasArg(options::OPT_fno_inline))
4859 CmdArgs.push_back("-fno-inline");
4860
Nico Weber908b6972019-06-26 17:51:47 +00004861 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4862 options::OPT_finline_hint_functions,
4863 options::OPT_fno_inline_functions);
David L. Jonesf561aba2017-03-08 01:02:16 +00004864
Richard Smithb1b580e2019-04-14 11:11:37 +00004865 // FIXME: Find a better way to determine whether the language has modules
4866 // support by default, or just assume that all languages do.
4867 bool HaveModules =
4868 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4869 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4870
David L. Jonesf561aba2017-03-08 01:02:16 +00004871 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4872 options::OPT_fno_experimental_new_pass_manager);
4873
Saleem Abdulrasoolb2d4ebb2017-09-01 17:43:59 +00004874 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004875 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4876 Input, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004877
4878 if (Args.hasFlag(options::OPT_fapplication_extension,
4879 options::OPT_fno_application_extension, false))
4880 CmdArgs.push_back("-fapplication-extension");
4881
4882 // Handle GCC-style exception args.
4883 if (!C.getDriver().IsCLMode())
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004884 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00004885
Martell Malonec950c652017-11-29 07:25:12 +00004886 // Handle exception personalities
4887 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4888 options::OPT_fseh_exceptions,
4889 options::OPT_fdwarf_exceptions);
4890 if (A) {
4891 const Option &Opt = A->getOption();
4892 if (Opt.matches(options::OPT_fsjlj_exceptions))
4893 CmdArgs.push_back("-fsjlj-exceptions");
4894 if (Opt.matches(options::OPT_fseh_exceptions))
4895 CmdArgs.push_back("-fseh-exceptions");
4896 if (Opt.matches(options::OPT_fdwarf_exceptions))
4897 CmdArgs.push_back("-fdwarf-exceptions");
4898 } else {
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00004899 switch (TC.GetExceptionModel(Args)) {
Reid Kleckner7383b8e2017-11-29 21:36:00 +00004900 default:
4901 break;
4902 case llvm::ExceptionHandling::DwarfCFI:
4903 CmdArgs.push_back("-fdwarf-exceptions");
4904 break;
4905 case llvm::ExceptionHandling::SjLj:
4906 CmdArgs.push_back("-fsjlj-exceptions");
4907 break;
4908 case llvm::ExceptionHandling::WinEH:
4909 CmdArgs.push_back("-fseh-exceptions");
4910 break;
Martell Malonec950c652017-11-29 07:25:12 +00004911 }
4912 }
David L. Jonesf561aba2017-03-08 01:02:16 +00004913
4914 // C++ "sane" operator new.
4915 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4916 options::OPT_fno_assume_sane_operator_new))
4917 CmdArgs.push_back("-fno-assume-sane-operator-new");
4918
4919 // -frelaxed-template-template-args is off by default, as it is a severe
4920 // breaking change until a corresponding change to template partial ordering
4921 // is provided.
4922 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4923 options::OPT_fno_relaxed_template_template_args, false))
4924 CmdArgs.push_back("-frelaxed-template-template-args");
4925
4926 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4927 // most platforms.
4928 if (Args.hasFlag(options::OPT_fsized_deallocation,
4929 options::OPT_fno_sized_deallocation, false))
4930 CmdArgs.push_back("-fsized-deallocation");
4931
4932 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4933 // by default.
4934 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4935 options::OPT_fno_aligned_allocation,
4936 options::OPT_faligned_new_EQ)) {
4937 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4938 CmdArgs.push_back("-fno-aligned-allocation");
4939 else
4940 CmdArgs.push_back("-faligned-allocation");
4941 }
4942
4943 // The default new alignment can be specified using a dedicated option or via
4944 // a GCC-compatible option that also turns on aligned allocation.
4945 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4946 options::OPT_faligned_new_EQ))
4947 CmdArgs.push_back(
4948 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4949
4950 // -fconstant-cfstrings is default, and may be subject to argument translation
4951 // on Darwin.
4952 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4953 options::OPT_fno_constant_cfstrings) ||
4954 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4955 options::OPT_mno_constant_cfstrings))
4956 CmdArgs.push_back("-fno-constant-cfstrings");
4957
David L. Jonesf561aba2017-03-08 01:02:16 +00004958 // -fno-pascal-strings is default, only pass non-default.
4959 if (Args.hasFlag(options::OPT_fpascal_strings,
4960 options::OPT_fno_pascal_strings, false))
4961 CmdArgs.push_back("-fpascal-strings");
4962
4963 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4964 // -fno-pack-struct doesn't apply to -fpack-struct=.
4965 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4966 std::string PackStructStr = "-fpack-struct=";
4967 PackStructStr += A->getValue();
4968 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4969 } else if (Args.hasFlag(options::OPT_fpack_struct,
4970 options::OPT_fno_pack_struct, false)) {
4971 CmdArgs.push_back("-fpack-struct=1");
4972 }
4973
4974 // Handle -fmax-type-align=N and -fno-type-align
4975 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4976 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4977 if (!SkipMaxTypeAlign) {
4978 std::string MaxTypeAlignStr = "-fmax-type-align=";
4979 MaxTypeAlignStr += A->getValue();
4980 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4981 }
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004982 } else if (RawTriple.isOSDarwin()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00004983 if (!SkipMaxTypeAlign) {
4984 std::string MaxTypeAlignStr = "-fmax-type-align=16";
4985 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4986 }
4987 }
4988
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00004989 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4990 CmdArgs.push_back("-Qn");
4991
David L. Jonesf561aba2017-03-08 01:02:16 +00004992 // -fcommon is the default unless compiling kernel code or the target says so
Saleem Abdulrasool374b5582017-08-29 23:59:05 +00004993 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
David L. Jonesf561aba2017-03-08 01:02:16 +00004994 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4995 !NoCommonDefault))
4996 CmdArgs.push_back("-fno-common");
4997
4998 // -fsigned-bitfields is default, and clang doesn't yet support
4999 // -funsigned-bitfields.
5000 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5001 options::OPT_funsigned_bitfields))
5002 D.Diag(diag::warn_drv_clang_unsupported)
5003 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5004
5005 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5006 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5007 D.Diag(diag::err_drv_clang_unsupported)
5008 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5009
5010 // -finput_charset=UTF-8 is default. Reject others
5011 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5012 StringRef value = inputCharset->getValue();
5013 if (!value.equals_lower("utf-8"))
5014 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5015 << value;
5016 }
5017
5018 // -fexec_charset=UTF-8 is default. Reject others
5019 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5020 StringRef value = execCharset->getValue();
5021 if (!value.equals_lower("utf-8"))
5022 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5023 << value;
5024 }
5025
Saleem Abdulrasool75557fa2017-09-01 18:57:34 +00005026 RenderDiagnosticsOptions(D, Args, CmdArgs);
David L. Jonesf561aba2017-03-08 01:02:16 +00005027
5028 // -fno-asm-blocks is default.
5029 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5030 false))
5031 CmdArgs.push_back("-fasm-blocks");
5032
5033 // -fgnu-inline-asm is default.
5034 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5035 options::OPT_fno_gnu_inline_asm, true))
5036 CmdArgs.push_back("-fno-gnu-inline-asm");
5037
5038 // Enable vectorization per default according to the optimization level
5039 // selected. For optimization levels that want vectorization we use the alias
5040 // option to simplify the hasFlag logic.
5041 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5042 OptSpecifier VectorizeAliasOption =
5043 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5044 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5045 options::OPT_fno_vectorize, EnableVec))
5046 CmdArgs.push_back("-vectorize-loops");
5047
5048 // -fslp-vectorize is enabled based on the optimization level selected.
5049 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5050 OptSpecifier SLPVectAliasOption =
5051 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5052 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5053 options::OPT_fno_slp_vectorize, EnableSLPVec))
5054 CmdArgs.push_back("-vectorize-slp");
5055
Craig Topper9a724aa2017-12-11 21:09:19 +00005056 ParseMPreferVectorWidth(D, Args, CmdArgs);
5057
Nico Weber908b6972019-06-26 17:51:47 +00005058 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5059 Args.AddLastArg(CmdArgs,
5060 options::OPT_fsanitize_undefined_strip_path_components_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005061
5062 // -fdollars-in-identifiers default varies depending on platform and
5063 // language; only pass if specified.
5064 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5065 options::OPT_fno_dollars_in_identifiers)) {
5066 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5067 CmdArgs.push_back("-fdollars-in-identifiers");
5068 else
5069 CmdArgs.push_back("-fno-dollars-in-identifiers");
5070 }
5071
5072 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5073 // practical purposes.
5074 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5075 options::OPT_fno_unit_at_a_time)) {
5076 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5077 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5078 }
5079
5080 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5081 options::OPT_fno_apple_pragma_pack, false))
5082 CmdArgs.push_back("-fapple-pragma-pack");
5083
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005084 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
David L. Jonesf561aba2017-03-08 01:02:16 +00005085 if (Args.hasFlag(options::OPT_fsave_optimization_record,
Jonas Devliegherecf73eba2017-12-19 17:16:45 +00005086 options::OPT_foptimization_record_file_EQ,
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005087 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005088 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5089 options::OPT_fno_save_optimization_record, false) ||
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005090 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
David L. Jonesf561aba2017-03-08 01:02:16 +00005091 options::OPT_fno_save_optimization_record, false)) {
5092 CmdArgs.push_back("-opt-record-file");
5093
5094 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5095 if (A) {
5096 CmdArgs.push_back(A->getValue());
5097 } else {
5098 SmallString<128> F;
Hal Finkel67814df2017-08-16 21:34:27 +00005099
5100 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5101 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5102 F = FinalOutput->getValue();
5103 }
5104
5105 if (F.empty()) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005106 // Use the input filename.
5107 F = llvm::sys::path::stem(Input.getBaseInput());
5108
5109 // If we're compiling for an offload architecture (i.e. a CUDA device),
5110 // we need to make the file name for the device compilation different
5111 // from the host compilation.
5112 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5113 !JA.isDeviceOffloading(Action::OFK_Host)) {
5114 llvm::sys::path::replace_extension(F, "");
5115 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5116 Triple.normalize());
5117 F += "-";
5118 F += JA.getOffloadingArch();
5119 }
5120 }
5121
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005122 std::string Extension = "opt.";
5123 if (const Arg *A =
5124 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5125 Extension += A->getValue();
5126 else
5127 Extension += "yaml";
5128
5129 llvm::sys::path::replace_extension(F, Extension);
David L. Jonesf561aba2017-03-08 01:02:16 +00005130 CmdArgs.push_back(Args.MakeArgString(F));
5131 }
Francis Visoiu Mistrih36a7a982019-06-17 22:49:38 +00005132
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00005133 if (const Arg *A =
5134 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5135 CmdArgs.push_back("-opt-record-passes");
5136 CmdArgs.push_back(A->getValue());
5137 }
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00005138
5139 if (const Arg *A =
5140 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5141 CmdArgs.push_back("-opt-record-format");
5142 CmdArgs.push_back(A->getValue());
5143 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005144 }
5145
Richard Smith86a3ef52017-06-09 21:24:02 +00005146 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5147 options::OPT_fno_rewrite_imports, false);
5148 if (RewriteImports)
5149 CmdArgs.push_back("-frewrite-imports");
5150
David L. Jonesf561aba2017-03-08 01:02:16 +00005151 // Enable rewrite includes if the user's asked for it or if we're generating
5152 // diagnostics.
5153 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5154 // nice to enable this when doing a crashdump for modules as well.
5155 if (Args.hasFlag(options::OPT_frewrite_includes,
5156 options::OPT_fno_rewrite_includes, false) ||
David Blaikiea99b8e42018-11-15 03:04:19 +00005157 (C.isForDiagnostics() && !HaveModules))
David L. Jonesf561aba2017-03-08 01:02:16 +00005158 CmdArgs.push_back("-frewrite-includes");
5159
5160 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5161 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5162 options::OPT_traditional_cpp)) {
5163 if (isa<PreprocessJobAction>(JA))
5164 CmdArgs.push_back("-traditional-cpp");
5165 else
5166 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5167 }
5168
5169 Args.AddLastArg(CmdArgs, options::OPT_dM);
5170 Args.AddLastArg(CmdArgs, options::OPT_dD);
5171
5172 // Handle serialized diagnostics.
5173 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5174 CmdArgs.push_back("-serialize-diagnostic-file");
5175 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5176 }
5177
5178 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5179 CmdArgs.push_back("-fretain-comments-from-system-headers");
5180
5181 // Forward -fcomment-block-commands to -cc1.
5182 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5183 // Forward -fparse-all-comments to -cc1.
5184 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5185
5186 // Turn -fplugin=name.so into -load name.so
5187 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5188 CmdArgs.push_back("-load");
5189 CmdArgs.push_back(A->getValue());
5190 A->claim();
5191 }
5192
Philip Pfaffee3f105c2019-02-02 23:19:32 +00005193 // Forward -fpass-plugin=name.so to -cc1.
5194 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5195 CmdArgs.push_back(
5196 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5197 A->claim();
5198 }
5199
David L. Jonesf561aba2017-03-08 01:02:16 +00005200 // Setup statistics file output.
Florian Hahn2e081d12018-04-20 12:50:10 +00005201 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5202 if (!StatsFile.empty())
5203 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
David L. Jonesf561aba2017-03-08 01:02:16 +00005204
5205 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5206 // parser.
Guansong Zhang4747cf52017-03-15 20:57:11 +00005207 // -finclude-default-header flag is for preprocessor,
5208 // do not pass it to other cc1 commands when save-temps is enabled
5209 if (C.getDriver().isSaveTempsEnabled() &&
5210 !isa<PreprocessJobAction>(JA)) {
5211 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5212 Arg->claim();
5213 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5214 CmdArgs.push_back(Arg->getValue());
5215 }
5216 }
5217 else {
5218 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5219 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005220 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5221 A->claim();
5222
5223 // We translate this by hand to the -cc1 argument, since nightly test uses
5224 // it and developers have been trained to spell it with -mllvm. Both
5225 // spellings are now deprecated and should be removed.
5226 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5227 CmdArgs.push_back("-disable-llvm-optzns");
5228 } else {
5229 A->render(Args, CmdArgs);
5230 }
5231 }
5232
5233 // With -save-temps, we want to save the unoptimized bitcode output from the
5234 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5235 // by the frontend.
5236 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5237 // has slightly different breakdown between stages.
5238 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5239 // pristine IR generated by the frontend. Ideally, a new compile action should
5240 // be added so both IR can be captured.
5241 if (C.getDriver().isSaveTempsEnabled() &&
5242 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5243 isa<CompileJobAction>(JA))
5244 CmdArgs.push_back("-disable-llvm-passes");
5245
David L. Jonesf561aba2017-03-08 01:02:16 +00005246 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5247
Saleem Abdulrasool33d41382017-08-29 23:59:06 +00005248 const char *Exec = D.getClangProgramPath();
David L. Jonesf561aba2017-03-08 01:02:16 +00005249
Scott Linderde6beb02018-12-14 15:38:15 +00005250 // Optionally embed the -cc1 level arguments into the debug info or a
5251 // section, for build analysis.
Eric Christopherca325172017-03-29 23:34:20 +00005252 // Also record command line arguments into the debug info if
5253 // -grecord-gcc-switches options is set on.
5254 // By default, -gno-record-gcc-switches is set on and no recording.
Scott Linderde6beb02018-12-14 15:38:15 +00005255 auto GRecordSwitches =
5256 Args.hasFlag(options::OPT_grecord_command_line,
5257 options::OPT_gno_record_command_line, false);
5258 auto FRecordSwitches =
5259 Args.hasFlag(options::OPT_frecord_command_line,
5260 options::OPT_fno_record_command_line, false);
5261 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5262 D.Diag(diag::err_drv_unsupported_opt_for_target)
5263 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5264 << TripleStr;
5265 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005266 ArgStringList OriginalArgs;
5267 for (const auto &Arg : Args)
5268 Arg->render(Args, OriginalArgs);
5269
5270 SmallString<256> Flags;
5271 Flags += Exec;
5272 for (const char *OriginalArg : OriginalArgs) {
5273 SmallString<128> EscapedArg;
5274 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5275 Flags += " ";
5276 Flags += EscapedArg;
5277 }
Scott Linderde6beb02018-12-14 15:38:15 +00005278 auto FlagsArgString = Args.MakeArgString(Flags);
5279 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5280 CmdArgs.push_back("-dwarf-debug-flags");
5281 CmdArgs.push_back(FlagsArgString);
5282 }
5283 if (FRecordSwitches) {
5284 CmdArgs.push_back("-record-command-line");
5285 CmdArgs.push_back(FlagsArgString);
5286 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005287 }
5288
Yaxun Liu97670892018-10-02 17:48:54 +00005289 // Host-side cuda compilation receives all device-side outputs in a single
5290 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5291 if ((IsCuda || IsHIP) && CudaDeviceInput) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +00005292 CmdArgs.push_back("-fcuda-include-gpubinary");
Richard Smithcd35eff2018-09-15 01:21:16 +00005293 CmdArgs.push_back(CudaDeviceInput->getFilename());
Yaxun Liu97670892018-10-02 17:48:54 +00005294 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5295 CmdArgs.push_back("-fgpu-rdc");
5296 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005297
Yaxun Liu97670892018-10-02 17:48:54 +00005298 if (IsCuda) {
Artem Belevich679dafe2018-05-09 23:10:09 +00005299 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5300 options::OPT_fno_cuda_short_ptr, false))
5301 CmdArgs.push_back("-fcuda-short-ptr");
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00005302 }
5303
David L. Jonesf561aba2017-03-08 01:02:16 +00005304 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5305 // to specify the result of the compile phase on the host, so the meaningful
5306 // device declarations can be identified. Also, -fopenmp-is-device is passed
5307 // along to tell the frontend that it is generating code for a device, so that
5308 // only the relevant declarations are emitted.
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005309 if (IsOpenMPDevice) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005310 CmdArgs.push_back("-fopenmp-is-device");
Richard Smithcd35eff2018-09-15 01:21:16 +00005311 if (OpenMPDeviceInput) {
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005312 CmdArgs.push_back("-fopenmp-host-ir-file-path");
Richard Smithcd35eff2018-09-15 01:21:16 +00005313 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
Gheorghe-Teodor Bercea3addb7d2017-06-29 15:59:19 +00005314 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005315 }
5316
5317 // For all the host OpenMP offloading compile jobs we need to pass the targets
5318 // information using -fopenmp-targets= option.
Alexey Bataev77403de2018-07-26 15:17:38 +00005319 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005320 SmallString<128> TargetInfo("-fopenmp-targets=");
5321
5322 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5323 assert(Tgts && Tgts->getNumValues() &&
5324 "OpenMP offloading has to have targets specified.");
5325 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5326 if (i)
5327 TargetInfo += ',';
5328 // We need to get the string from the triple because it may be not exactly
5329 // the same as the one we get directly from the arguments.
5330 llvm::Triple T(Tgts->getValue(i));
5331 TargetInfo += T.getTriple();
5332 }
5333 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5334 }
5335
5336 bool WholeProgramVTables =
5337 Args.hasFlag(options::OPT_fwhole_program_vtables,
5338 options::OPT_fno_whole_program_vtables, false);
5339 if (WholeProgramVTables) {
5340 if (!D.isUsingLTO())
5341 D.Diag(diag::err_drv_argument_only_allowed_with)
5342 << "-fwhole-program-vtables"
5343 << "-flto";
5344 CmdArgs.push_back("-fwhole-program-vtables");
5345 }
5346
Teresa Johnson84cecfc2019-01-11 18:32:07 +00005347 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5348 bool SplitLTOUnit =
5349 Args.hasFlag(options::OPT_fsplit_lto_unit,
5350 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5351 if (RequiresSplitLTOUnit && !SplitLTOUnit)
5352 D.Diag(diag::err_drv_argument_not_allowed_with)
5353 << "-fno-split-lto-unit"
5354 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5355 if (SplitLTOUnit)
5356 CmdArgs.push_back("-fsplit-lto-unit");
5357
Amara Emerson4ee9f822018-01-26 00:27:22 +00005358 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5359 options::OPT_fno_experimental_isel)) {
5360 CmdArgs.push_back("-mllvm");
5361 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5362 CmdArgs.push_back("-global-isel=1");
5363
5364 // GISel is on by default on AArch64 -O0, so don't bother adding
5365 // the fallback remarks for it. Other combinations will add a warning of
5366 // some kind.
5367 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5368 bool IsOptLevelSupported = false;
5369
5370 Arg *A = Args.getLastArg(options::OPT_O_Group);
5371 if (Triple.getArch() == llvm::Triple::aarch64) {
5372 if (!A || A->getOption().matches(options::OPT_O0))
5373 IsOptLevelSupported = true;
5374 }
5375 if (!IsArchSupported || !IsOptLevelSupported) {
5376 CmdArgs.push_back("-mllvm");
5377 CmdArgs.push_back("-global-isel-abort=2");
5378
5379 if (!IsArchSupported)
5380 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5381 else
5382 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5383 }
5384 } else {
5385 CmdArgs.push_back("-global-isel=0");
5386 }
5387 }
5388
Manman Ren394d4cc2019-03-04 20:30:30 +00005389 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5390 CmdArgs.push_back("-forder-file-instrumentation");
5391 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5392 // on, we need to pass these flags as linker flags and that will be handled
5393 // outside of the compiler.
5394 if (!D.isUsingLTO()) {
5395 CmdArgs.push_back("-mllvm");
5396 CmdArgs.push_back("-enable-order-file-instrumentation");
5397 }
5398 }
5399
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00005400 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5401 options::OPT_fno_force_enable_int128)) {
5402 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5403 CmdArgs.push_back("-fforce-enable-int128");
5404 }
5405
Peter Collingbourne54d13b42018-05-30 03:40:04 +00005406 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5407 options::OPT_fno_complete_member_pointers, false))
5408 CmdArgs.push_back("-fcomplete-member-pointers");
5409
Erik Pilkington5a559e62018-08-21 17:24:06 +00005410 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5411 options::OPT_fno_cxx_static_destructors, true))
5412 CmdArgs.push_back("-fno-c++-static-destructors");
5413
Jessica Paquette36a25672018-06-29 18:06:10 +00005414 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5415 options::OPT_mno_outline)) {
5416 if (A->getOption().matches(options::OPT_moutline)) {
5417 // We only support -moutline in AArch64 right now. If we're not compiling
5418 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5419 // proper mllvm flags.
5420 if (Triple.getArch() != llvm::Triple::aarch64) {
5421 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5422 } else {
Jessica Paquette36a25672018-06-29 18:06:10 +00005423 CmdArgs.push_back("-mllvm");
Jessica Paquette33648c32018-07-06 22:24:56 +00005424 CmdArgs.push_back("-enable-machine-outliner");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005425 }
Jessica Paquette36a25672018-06-29 18:06:10 +00005426 } else {
5427 // Disable all outlining behaviour.
5428 CmdArgs.push_back("-mllvm");
5429 CmdArgs.push_back("-enable-machine-outliner=never");
Jessica Paquettea67abc82018-06-26 22:09:48 +00005430 }
5431 }
5432
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005433 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
Saleem Abdulrasool3806c532018-09-18 22:14:50 +00005434 (TC.getTriple().isOSBinFormatELF() ||
5435 TC.getTriple().isOSBinFormatCOFF()) &&
Douglas Yung25f04772018-12-19 22:45:26 +00005436 !TC.getTriple().isPS4() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005437 !TC.getTriple().isOSNetBSD() &&
Michal Gornydae01c32018-12-23 15:07:26 +00005438 !Distro(D.getVFS()).IsGentoo() &&
Dan Albertdd142342019-01-08 22:33:59 +00005439 !TC.getTriple().isAndroid() &&
Michal Gorny5a409d02018-12-20 13:09:30 +00005440 TC.useIntegratedAs()))
Peter Collingbourne14b468b2018-07-18 00:27:07 +00005441 CmdArgs.push_back("-faddrsig");
5442
Peter Collingbournee08e68d2019-06-07 19:10:08 +00005443 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5444 std::string Str = A->getAsString(Args);
5445 if (!TC.getTriple().isOSBinFormatELF())
5446 D.Diag(diag::err_drv_unsupported_opt_for_target)
5447 << Str << TC.getTripleString();
5448 CmdArgs.push_back(Args.MakeArgString(Str));
5449 }
5450
Reid Kleckner549ed542019-05-23 18:35:43 +00005451 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5452 // the -cc1 command easier to edit when reproducing compiler crashes.
5453 if (Output.getType() == types::TY_Dependencies) {
5454 // Handled with other dependency code.
5455 } else if (Output.isFilename()) {
5456 CmdArgs.push_back("-o");
5457 CmdArgs.push_back(Output.getFilename());
5458 } else {
5459 assert(Output.isNothing() && "Invalid output.");
5460 }
5461
5462 addDashXForInput(Args, Input, CmdArgs);
5463
5464 ArrayRef<InputInfo> FrontendInputs = Input;
5465 if (IsHeaderModulePrecompile)
5466 FrontendInputs = ModuleHeaderInputs;
5467 else if (Input.isNothing())
5468 FrontendInputs = {};
5469
5470 for (const InputInfo &Input : FrontendInputs) {
5471 if (Input.isFilename())
5472 CmdArgs.push_back(Input.getFilename());
5473 else
5474 Input.getInputArg().renderAsInput(Args, CmdArgs);
5475 }
5476
David L. Jonesf561aba2017-03-08 01:02:16 +00005477 // Finally add the compile command to the compilation.
5478 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5479 Output.getType() == types::TY_Object &&
5480 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5481 auto CLCommand =
5482 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5483 C.addCommand(llvm::make_unique<FallbackCommand>(
5484 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5485 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5486 isa<PrecompileJobAction>(JA)) {
5487 // In /fallback builds, run the main compilation even if the pch generation
5488 // fails, so that the main compilation's fallback to cl.exe runs.
5489 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5490 CmdArgs, Inputs));
5491 } else {
5492 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5493 }
5494
Hans Wennborg2fe01042018-10-13 19:13:14 +00005495 // Make the compile command echo its inputs for /showFilenames.
5496 if (Output.getType() == types::TY_Object &&
5497 Args.hasFlag(options::OPT__SLASH_showFilenames,
5498 options::OPT__SLASH_showFilenames_, false)) {
5499 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5500 }
5501
David L. Jonesf561aba2017-03-08 01:02:16 +00005502 if (Arg *A = Args.getLastArg(options::OPT_pg))
Yuanfang Chenff22ec32019-07-20 22:50:50 +00005503 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
David L. Jonesf561aba2017-03-08 01:02:16 +00005504 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5505 << A->getAsString(Args);
5506
5507 // Claim some arguments which clang supports automatically.
5508
5509 // -fpch-preprocess is used with gcc to add a special marker in the output to
Erich Keane0a6b5b62018-12-04 14:34:09 +00005510 // include the PCH file.
David L. Jonesf561aba2017-03-08 01:02:16 +00005511 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5512
5513 // Claim some arguments which clang doesn't support, but we don't
5514 // care to warn the user about.
5515 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5516 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5517
5518 // Disable warnings for clang -E -emit-llvm foo.c
5519 Args.ClaimAllArgs(options::OPT_emit_llvm);
5520}
5521
5522Clang::Clang(const ToolChain &TC)
5523 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5524 // as it is for other tools. Some operations on a Tool actually test
5525 // whether that tool is Clang based on the Tool's Name as a string.
5526 : Tool("clang", "clang frontend", TC, RF_Full) {}
5527
5528Clang::~Clang() {}
5529
5530/// Add options related to the Objective-C runtime/ABI.
5531///
5532/// Returns true if the runtime is non-fragile.
5533ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5534 ArgStringList &cmdArgs,
5535 RewriteKind rewriteKind) const {
5536 // Look for the controlling runtime option.
5537 Arg *runtimeArg =
5538 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5539 options::OPT_fobjc_runtime_EQ);
5540
5541 // Just forward -fobjc-runtime= to the frontend. This supercedes
5542 // options about fragility.
5543 if (runtimeArg &&
5544 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5545 ObjCRuntime runtime;
5546 StringRef value = runtimeArg->getValue();
5547 if (runtime.tryParse(value)) {
5548 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5549 << value;
5550 }
David Chisnall404bbcb2018-05-22 10:13:06 +00005551 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5552 (runtime.getVersion() >= VersionTuple(2, 0)))
David Chisnallef16ea72018-09-04 10:07:27 +00005553 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5554 !getToolChain().getTriple().isOSBinFormatCOFF()) {
David Chisnall404bbcb2018-05-22 10:13:06 +00005555 getToolChain().getDriver().Diag(
5556 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5557 << runtime.getVersion().getMajor();
5558 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005559
5560 runtimeArg->render(args, cmdArgs);
5561 return runtime;
5562 }
5563
5564 // Otherwise, we'll need the ABI "version". Version numbers are
5565 // slightly confusing for historical reasons:
5566 // 1 - Traditional "fragile" ABI
5567 // 2 - Non-fragile ABI, version 1
5568 // 3 - Non-fragile ABI, version 2
5569 unsigned objcABIVersion = 1;
5570 // If -fobjc-abi-version= is present, use that to set the version.
5571 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5572 StringRef value = abiArg->getValue();
5573 if (value == "1")
5574 objcABIVersion = 1;
5575 else if (value == "2")
5576 objcABIVersion = 2;
5577 else if (value == "3")
5578 objcABIVersion = 3;
5579 else
5580 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5581 } else {
5582 // Otherwise, determine if we are using the non-fragile ABI.
5583 bool nonFragileABIIsDefault =
5584 (rewriteKind == RK_NonFragile ||
5585 (rewriteKind == RK_None &&
5586 getToolChain().IsObjCNonFragileABIDefault()));
5587 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5588 options::OPT_fno_objc_nonfragile_abi,
5589 nonFragileABIIsDefault)) {
5590// Determine the non-fragile ABI version to use.
5591#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5592 unsigned nonFragileABIVersion = 1;
5593#else
5594 unsigned nonFragileABIVersion = 2;
5595#endif
5596
5597 if (Arg *abiArg =
5598 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5599 StringRef value = abiArg->getValue();
5600 if (value == "1")
5601 nonFragileABIVersion = 1;
5602 else if (value == "2")
5603 nonFragileABIVersion = 2;
5604 else
5605 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5606 << value;
5607 }
5608
5609 objcABIVersion = 1 + nonFragileABIVersion;
5610 } else {
5611 objcABIVersion = 1;
5612 }
5613 }
5614
5615 // We don't actually care about the ABI version other than whether
5616 // it's non-fragile.
5617 bool isNonFragile = objcABIVersion != 1;
5618
5619 // If we have no runtime argument, ask the toolchain for its default runtime.
5620 // However, the rewriter only really supports the Mac runtime, so assume that.
5621 ObjCRuntime runtime;
5622 if (!runtimeArg) {
5623 switch (rewriteKind) {
5624 case RK_None:
5625 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5626 break;
5627 case RK_Fragile:
5628 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5629 break;
5630 case RK_NonFragile:
5631 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5632 break;
5633 }
5634
5635 // -fnext-runtime
5636 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5637 // On Darwin, make this use the default behavior for the toolchain.
5638 if (getToolChain().getTriple().isOSDarwin()) {
5639 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5640
5641 // Otherwise, build for a generic macosx port.
5642 } else {
5643 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5644 }
5645
5646 // -fgnu-runtime
5647 } else {
5648 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5649 // Legacy behaviour is to target the gnustep runtime if we are in
5650 // non-fragile mode or the GCC runtime in fragile mode.
5651 if (isNonFragile)
David Chisnall404bbcb2018-05-22 10:13:06 +00005652 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
David L. Jonesf561aba2017-03-08 01:02:16 +00005653 else
5654 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5655 }
5656
5657 cmdArgs.push_back(
5658 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5659 return runtime;
5660}
5661
5662static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5663 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5664 I += HaveDash;
5665 return !HaveDash;
5666}
5667
5668namespace {
5669struct EHFlags {
5670 bool Synch = false;
5671 bool Asynch = false;
5672 bool NoUnwindC = false;
5673};
5674} // end anonymous namespace
5675
5676/// /EH controls whether to run destructor cleanups when exceptions are
5677/// thrown. There are three modifiers:
5678/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5679/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5680/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5681/// - c: Assume that extern "C" functions are implicitly nounwind.
5682/// The default is /EHs-c-, meaning cleanups are disabled.
5683static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5684 EHFlags EH;
5685
5686 std::vector<std::string> EHArgs =
5687 Args.getAllArgValues(options::OPT__SLASH_EH);
5688 for (auto EHVal : EHArgs) {
5689 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5690 switch (EHVal[I]) {
5691 case 'a':
5692 EH.Asynch = maybeConsumeDash(EHVal, I);
5693 if (EH.Asynch)
5694 EH.Synch = false;
5695 continue;
5696 case 'c':
5697 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5698 continue;
5699 case 's':
5700 EH.Synch = maybeConsumeDash(EHVal, I);
5701 if (EH.Synch)
5702 EH.Asynch = false;
5703 continue;
5704 default:
5705 break;
5706 }
5707 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5708 break;
5709 }
5710 }
5711 // The /GX, /GX- flags are only processed if there are not /EH flags.
5712 // The default is that /GX is not specified.
5713 if (EHArgs.empty() &&
5714 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005715 /*Default=*/false)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005716 EH.Synch = true;
5717 EH.NoUnwindC = true;
5718 }
5719
5720 return EH;
5721}
5722
5723void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5724 ArgStringList &CmdArgs,
5725 codegenoptions::DebugInfoKind *DebugInfoKind,
5726 bool *EmitCodeView) const {
5727 unsigned RTOptionID = options::OPT__SLASH_MT;
5728
5729 if (Args.hasArg(options::OPT__SLASH_LDd))
5730 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5731 // but defining _DEBUG is sticky.
5732 RTOptionID = options::OPT__SLASH_MTd;
5733
5734 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5735 RTOptionID = A->getOption().getID();
5736
5737 StringRef FlagForCRT;
5738 switch (RTOptionID) {
5739 case options::OPT__SLASH_MD:
5740 if (Args.hasArg(options::OPT__SLASH_LDd))
5741 CmdArgs.push_back("-D_DEBUG");
5742 CmdArgs.push_back("-D_MT");
5743 CmdArgs.push_back("-D_DLL");
5744 FlagForCRT = "--dependent-lib=msvcrt";
5745 break;
5746 case options::OPT__SLASH_MDd:
5747 CmdArgs.push_back("-D_DEBUG");
5748 CmdArgs.push_back("-D_MT");
5749 CmdArgs.push_back("-D_DLL");
5750 FlagForCRT = "--dependent-lib=msvcrtd";
5751 break;
5752 case options::OPT__SLASH_MT:
5753 if (Args.hasArg(options::OPT__SLASH_LDd))
5754 CmdArgs.push_back("-D_DEBUG");
5755 CmdArgs.push_back("-D_MT");
5756 CmdArgs.push_back("-flto-visibility-public-std");
5757 FlagForCRT = "--dependent-lib=libcmt";
5758 break;
5759 case options::OPT__SLASH_MTd:
5760 CmdArgs.push_back("-D_DEBUG");
5761 CmdArgs.push_back("-D_MT");
5762 CmdArgs.push_back("-flto-visibility-public-std");
5763 FlagForCRT = "--dependent-lib=libcmtd";
5764 break;
5765 default:
5766 llvm_unreachable("Unexpected option ID.");
5767 }
5768
5769 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5770 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5771 } else {
5772 CmdArgs.push_back(FlagForCRT.data());
5773
5774 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5775 // users want. The /Za flag to cl.exe turns this off, but it's not
5776 // implemented in clang.
5777 CmdArgs.push_back("--dependent-lib=oldnames");
5778 }
5779
Nico Weber908b6972019-06-26 17:51:47 +00005780 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
David L. Jonesf561aba2017-03-08 01:02:16 +00005781
5782 // This controls whether or not we emit RTTI data for polymorphic types.
5783 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005784 /*Default=*/false))
David L. Jonesf561aba2017-03-08 01:02:16 +00005785 CmdArgs.push_back("-fno-rtti-data");
5786
5787 // This controls whether or not we emit stack-protector instrumentation.
5788 // In MSVC, Buffer Security Check (/GS) is on by default.
5789 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005790 /*Default=*/true)) {
David L. Jonesf561aba2017-03-08 01:02:16 +00005791 CmdArgs.push_back("-stack-protector");
5792 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5793 }
5794
5795 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5796 if (Arg *DebugInfoArg =
5797 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5798 options::OPT_gline_tables_only)) {
5799 *EmitCodeView = true;
5800 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5801 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5802 else
5803 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
David L. Jonesf561aba2017-03-08 01:02:16 +00005804 } else {
5805 *EmitCodeView = false;
5806 }
5807
5808 const Driver &D = getToolChain().getDriver();
5809 EHFlags EH = parseClangCLEHFlags(D, Args);
5810 if (EH.Synch || EH.Asynch) {
5811 if (types::isCXX(InputType))
5812 CmdArgs.push_back("-fcxx-exceptions");
5813 CmdArgs.push_back("-fexceptions");
5814 }
5815 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5816 CmdArgs.push_back("-fexternc-nounwind");
5817
5818 // /EP should expand to -E -P.
5819 if (Args.hasArg(options::OPT__SLASH_EP)) {
5820 CmdArgs.push_back("-E");
5821 CmdArgs.push_back("-P");
5822 }
5823
5824 unsigned VolatileOptionID;
5825 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5826 getToolChain().getArch() == llvm::Triple::x86)
5827 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5828 else
5829 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5830
5831 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5832 VolatileOptionID = A->getOption().getID();
5833
5834 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5835 CmdArgs.push_back("-fms-volatile");
5836
Takuto Ikuta302c6432018-11-03 06:45:00 +00005837 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5838 options::OPT__SLASH_Zc_dllexportInlines,
Takuto Ikuta245d9472018-11-13 04:14:09 +00005839 false)) {
5840 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5841 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5842 } else {
Takuto Ikuta302c6432018-11-03 06:45:00 +00005843 CmdArgs.push_back("-fno-dllexport-inlines");
Takuto Ikuta245d9472018-11-13 04:14:09 +00005844 }
5845 }
Takuto Ikuta302c6432018-11-03 06:45:00 +00005846
David L. Jonesf561aba2017-03-08 01:02:16 +00005847 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5848 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5849 if (MostGeneralArg && BestCaseArg)
5850 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5851 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5852
5853 if (MostGeneralArg) {
5854 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5855 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5856 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5857
5858 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5859 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5860 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5861 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5862 << FirstConflict->getAsString(Args)
5863 << SecondConflict->getAsString(Args);
5864
5865 if (SingleArg)
5866 CmdArgs.push_back("-fms-memptr-rep=single");
5867 else if (MultipleArg)
5868 CmdArgs.push_back("-fms-memptr-rep=multiple");
5869 else
5870 CmdArgs.push_back("-fms-memptr-rep=virtual");
5871 }
5872
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005873 // Parse the default calling convention options.
5874 if (Arg *CCArg =
5875 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
Erich Keanea957ffb2017-11-02 21:08:00 +00005876 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5877 options::OPT__SLASH_Gregcall)) {
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005878 unsigned DCCOptId = CCArg->getOption().getID();
5879 const char *DCCFlag = nullptr;
5880 bool ArchSupported = true;
5881 llvm::Triple::ArchType Arch = getToolChain().getArch();
5882 switch (DCCOptId) {
5883 case options::OPT__SLASH_Gd:
Reid Kleckner6344f102017-05-31 15:50:35 +00005884 DCCFlag = "-fdefault-calling-conv=cdecl";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005885 break;
5886 case options::OPT__SLASH_Gr:
5887 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005888 DCCFlag = "-fdefault-calling-conv=fastcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005889 break;
5890 case options::OPT__SLASH_Gz:
5891 ArchSupported = Arch == llvm::Triple::x86;
Reid Kleckner6344f102017-05-31 15:50:35 +00005892 DCCFlag = "-fdefault-calling-conv=stdcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005893 break;
5894 case options::OPT__SLASH_Gv:
5895 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
Reid Kleckner6344f102017-05-31 15:50:35 +00005896 DCCFlag = "-fdefault-calling-conv=vectorcall";
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005897 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00005898 case options::OPT__SLASH_Gregcall:
5899 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5900 DCCFlag = "-fdefault-calling-conv=regcall";
5901 break;
Reid Kleckner4b2f3262017-05-31 15:39:28 +00005902 }
5903
5904 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5905 if (ArchSupported && DCCFlag)
5906 CmdArgs.push_back(DCCFlag);
5907 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005908
Nico Weber908b6972019-06-26 17:51:47 +00005909 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
David L. Jonesf561aba2017-03-08 01:02:16 +00005910
5911 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5912 CmdArgs.push_back("-fdiagnostics-format");
5913 if (Args.hasArg(options::OPT__SLASH_fallback))
5914 CmdArgs.push_back("msvc-fallback");
5915 else
5916 CmdArgs.push_back("msvc");
5917 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +00005918
Hans Wennborga912e3e2018-08-10 09:49:21 +00005919 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5920 SmallVector<StringRef, 1> SplitArgs;
5921 StringRef(A->getValue()).split(SplitArgs, ",");
5922 bool Instrument = false;
5923 bool NoChecks = false;
5924 for (StringRef Arg : SplitArgs) {
5925 if (Arg.equals_lower("cf"))
5926 Instrument = true;
5927 else if (Arg.equals_lower("cf-"))
5928 Instrument = false;
5929 else if (Arg.equals_lower("nochecks"))
5930 NoChecks = true;
5931 else if (Arg.equals_lower("nochecks-"))
5932 NoChecks = false;
5933 else
5934 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5935 }
5936 // Currently there's no support emitting CFG instrumentation; the flag only
5937 // emits the table of address-taken functions.
5938 if (Instrument || NoChecks)
5939 CmdArgs.push_back("-cfguard");
5940 }
David L. Jonesf561aba2017-03-08 01:02:16 +00005941}
5942
5943visualstudio::Compiler *Clang::getCLFallback() const {
5944 if (!CLFallback)
5945 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5946 return CLFallback.get();
5947}
5948
5949
5950const char *Clang::getBaseInputName(const ArgList &Args,
5951 const InputInfo &Input) {
5952 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5953}
5954
5955const char *Clang::getBaseInputStem(const ArgList &Args,
5956 const InputInfoList &Inputs) {
5957 const char *Str = getBaseInputName(Args, Inputs[0]);
5958
5959 if (const char *End = strrchr(Str, '.'))
5960 return Args.MakeArgString(std::string(Str, End));
5961
5962 return Str;
5963}
5964
5965const char *Clang::getDependencyFileName(const ArgList &Args,
5966 const InputInfoList &Inputs) {
5967 // FIXME: Think about this more.
5968 std::string Res;
5969
5970 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5971 std::string Str(OutputOpt->getValue());
5972 Res = Str.substr(0, Str.rfind('.'));
5973 } else {
5974 Res = getBaseInputStem(Args, Inputs);
5975 }
5976 return Args.MakeArgString(Res + ".d");
5977}
5978
5979// Begin ClangAs
5980
5981void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5982 ArgStringList &CmdArgs) const {
5983 StringRef CPUName;
5984 StringRef ABIName;
5985 const llvm::Triple &Triple = getToolChain().getTriple();
5986 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5987
5988 CmdArgs.push_back("-target-abi");
5989 CmdArgs.push_back(ABIName.data());
5990}
5991
5992void ClangAs::AddX86TargetArgs(const ArgList &Args,
5993 ArgStringList &CmdArgs) const {
5994 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5995 StringRef Value = A->getValue();
5996 if (Value == "intel" || Value == "att") {
5997 CmdArgs.push_back("-mllvm");
5998 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5999 } else {
6000 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6001 << A->getOption().getName() << Value;
6002 }
6003 }
6004}
6005
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006006void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6007 ArgStringList &CmdArgs) const {
6008 const llvm::Triple &Triple = getToolChain().getTriple();
6009 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6010
6011 CmdArgs.push_back("-target-abi");
6012 CmdArgs.push_back(ABIName.data());
6013}
6014
David L. Jonesf561aba2017-03-08 01:02:16 +00006015void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6016 const InputInfo &Output, const InputInfoList &Inputs,
6017 const ArgList &Args,
6018 const char *LinkingOutput) const {
6019 ArgStringList CmdArgs;
6020
6021 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6022 const InputInfo &Input = Inputs[0];
6023
Martin Storsjob547ef22018-10-26 08:33:29 +00006024 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
David L. Jonesf561aba2017-03-08 01:02:16 +00006025 const std::string &TripleStr = Triple.getTriple();
Martin Storsjob547ef22018-10-26 08:33:29 +00006026 const auto &D = getToolChain().getDriver();
David L. Jonesf561aba2017-03-08 01:02:16 +00006027
6028 // Don't warn about "clang -w -c foo.s"
6029 Args.ClaimAllArgs(options::OPT_w);
6030 // and "clang -emit-llvm -c foo.s"
6031 Args.ClaimAllArgs(options::OPT_emit_llvm);
6032
6033 claimNoWarnArgs(Args);
6034
6035 // Invoke ourselves in -cc1as mode.
6036 //
6037 // FIXME: Implement custom jobs for internal actions.
6038 CmdArgs.push_back("-cc1as");
6039
6040 // Add the "effective" target triple.
6041 CmdArgs.push_back("-triple");
6042 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6043
6044 // Set the output mode, we currently only expect to be used as a real
6045 // assembler.
6046 CmdArgs.push_back("-filetype");
6047 CmdArgs.push_back("obj");
6048
6049 // Set the main file name, so that debug info works even with
6050 // -save-temps or preprocessed assembly.
6051 CmdArgs.push_back("-main-file-name");
6052 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6053
6054 // Add the target cpu
6055 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6056 if (!CPU.empty()) {
6057 CmdArgs.push_back("-target-cpu");
6058 CmdArgs.push_back(Args.MakeArgString(CPU));
6059 }
6060
6061 // Add the target features
6062 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6063
6064 // Ignore explicit -force_cpusubtype_ALL option.
6065 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6066
6067 // Pass along any -I options so we get proper .include search paths.
6068 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6069
6070 // Determine the original source input.
6071 const Action *SourceAction = &JA;
6072 while (SourceAction->getKind() != Action::InputClass) {
6073 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6074 SourceAction = SourceAction->getInputs()[0];
6075 }
6076
6077 // Forward -g and handle debug info related flags, assuming we are dealing
6078 // with an actual assembly file.
6079 bool WantDebug = false;
6080 unsigned DwarfVersion = 0;
6081 Args.ClaimAllArgs(options::OPT_g_Group);
6082 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6083 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6084 !A->getOption().matches(options::OPT_ggdb0);
6085 if (WantDebug)
6086 DwarfVersion = DwarfVersionNum(A->getSpelling());
6087 }
6088 if (DwarfVersion == 0)
6089 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6090
6091 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6092
6093 if (SourceAction->getType() == types::TY_Asm ||
6094 SourceAction->getType() == types::TY_PP_Asm) {
6095 // You might think that it would be ok to set DebugInfoKind outside of
6096 // the guard for source type, however there is a test which asserts
6097 // that some assembler invocation receives no -debug-info-kind,
6098 // and it's not clear whether that test is just overly restrictive.
6099 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6100 : codegenoptions::NoDebugInfo);
6101 // Add the -fdebug-compilation-dir flag if needed.
Michael J. Spencer7e48b402019-05-28 22:21:47 +00006102 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
David L. Jonesf561aba2017-03-08 01:02:16 +00006103
Paul Robinson9b292b42018-07-10 15:15:24 +00006104 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6105
David L. Jonesf561aba2017-03-08 01:02:16 +00006106 // Set the AT_producer to the clang version when using the integrated
6107 // assembler on assembly source files.
6108 CmdArgs.push_back("-dwarf-debug-producer");
6109 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6110
6111 // And pass along -I options
6112 Args.AddAllArgs(CmdArgs, options::OPT_I);
6113 }
6114 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6115 llvm::DebuggerKind::Default);
Alexey Bataevb83b4e42018-07-27 19:45:14 +00006116 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00006117
David L. Jonesf561aba2017-03-08 01:02:16 +00006118
6119 // Handle -fPIC et al -- the relocation-model affects the assembler
6120 // for some targets.
6121 llvm::Reloc::Model RelocationModel;
6122 unsigned PICLevel;
6123 bool IsPIE;
6124 std::tie(RelocationModel, PICLevel, IsPIE) =
6125 ParsePICArgs(getToolChain(), Args);
6126
6127 const char *RMName = RelocationModelName(RelocationModel);
6128 if (RMName) {
6129 CmdArgs.push_back("-mrelocation-model");
6130 CmdArgs.push_back(RMName);
6131 }
6132
6133 // Optionally embed the -cc1as level arguments into the debug info, for build
6134 // analysis.
6135 if (getToolChain().UseDwarfDebugFlags()) {
6136 ArgStringList OriginalArgs;
6137 for (const auto &Arg : Args)
6138 Arg->render(Args, OriginalArgs);
6139
6140 SmallString<256> Flags;
6141 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6142 Flags += Exec;
6143 for (const char *OriginalArg : OriginalArgs) {
6144 SmallString<128> EscapedArg;
6145 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6146 Flags += " ";
6147 Flags += EscapedArg;
6148 }
6149 CmdArgs.push_back("-dwarf-debug-flags");
6150 CmdArgs.push_back(Args.MakeArgString(Flags));
6151 }
6152
6153 // FIXME: Add -static support, once we have it.
6154
6155 // Add target specific flags.
6156 switch (getToolChain().getArch()) {
6157 default:
6158 break;
6159
6160 case llvm::Triple::mips:
6161 case llvm::Triple::mipsel:
6162 case llvm::Triple::mips64:
6163 case llvm::Triple::mips64el:
6164 AddMIPSTargetArgs(Args, CmdArgs);
6165 break;
6166
6167 case llvm::Triple::x86:
6168 case llvm::Triple::x86_64:
6169 AddX86TargetArgs(Args, CmdArgs);
6170 break;
Oliver Stannard692dc542017-04-18 13:21:05 +00006171
6172 case llvm::Triple::arm:
6173 case llvm::Triple::armeb:
6174 case llvm::Triple::thumb:
6175 case llvm::Triple::thumbeb:
6176 // This isn't in AddARMTargetArgs because we want to do this for assembly
6177 // only, not C/C++.
6178 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6179 options::OPT_mno_default_build_attributes, true)) {
6180 CmdArgs.push_back("-mllvm");
6181 CmdArgs.push_back("-arm-add-build-attributes");
6182 }
6183 break;
Roger Ferrer Ibaneze41a74e2019-03-26 08:01:18 +00006184
6185 case llvm::Triple::riscv32:
6186 case llvm::Triple::riscv64:
6187 AddRISCVTargetArgs(Args, CmdArgs);
6188 break;
David L. Jonesf561aba2017-03-08 01:02:16 +00006189 }
6190
6191 // Consume all the warning flags. Usually this would be handled more
6192 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6193 // doesn't handle that so rather than warning about unused flags that are
6194 // actually used, we'll lie by omission instead.
6195 // FIXME: Stop lying and consume only the appropriate driver flags
6196 Args.ClaimAllArgs(options::OPT_W_Group);
6197
6198 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6199 getToolChain().getDriver());
6200
6201 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6202
6203 assert(Output.isFilename() && "Unexpected lipo output.");
6204 CmdArgs.push_back("-o");
Martin Storsjob547ef22018-10-26 08:33:29 +00006205 CmdArgs.push_back(Output.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006206
Petr Hosekd3265352018-10-15 21:30:32 +00006207 const llvm::Triple &T = getToolChain().getTriple();
George Rimar91829ee2018-11-14 09:22:16 +00006208 Arg *A;
Fangrui Songee957e02019-03-28 08:24:00 +00006209 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6210 T.isOSBinFormatELF()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00006211 CmdArgs.push_back("-split-dwarf-output");
George Rimar36d71da2019-03-27 11:00:03 +00006212 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
Peter Collingbourne91d02842018-05-22 18:52:37 +00006213 }
6214
David L. Jonesf561aba2017-03-08 01:02:16 +00006215 assert(Input.isFilename() && "Invalid input.");
Martin Storsjob547ef22018-10-26 08:33:29 +00006216 CmdArgs.push_back(Input.getFilename());
David L. Jonesf561aba2017-03-08 01:02:16 +00006217
6218 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6219 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
David L. Jonesf561aba2017-03-08 01:02:16 +00006220}
6221
6222// Begin OffloadBundler
6223
6224void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6225 const InputInfo &Output,
6226 const InputInfoList &Inputs,
6227 const llvm::opt::ArgList &TCArgs,
6228 const char *LinkingOutput) const {
6229 // The version with only one output is expected to refer to a bundling job.
6230 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6231
6232 // The bundling command looks like this:
6233 // clang-offload-bundler -type=bc
6234 // -targets=host-triple,openmp-triple1,openmp-triple2
6235 // -outputs=input_file
6236 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6237
6238 ArgStringList CmdArgs;
6239
6240 // Get the type.
6241 CmdArgs.push_back(TCArgs.MakeArgString(
6242 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6243
6244 assert(JA.getInputs().size() == Inputs.size() &&
6245 "Not have inputs for all dependence actions??");
6246
6247 // Get the targets.
6248 SmallString<128> Triples;
6249 Triples += "-targets=";
6250 for (unsigned I = 0; I < Inputs.size(); ++I) {
6251 if (I)
6252 Triples += ',';
6253
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006254 // Find ToolChain for this input.
David L. Jonesf561aba2017-03-08 01:02:16 +00006255 Action::OffloadKind CurKind = Action::OFK_Host;
6256 const ToolChain *CurTC = &getToolChain();
6257 const Action *CurDep = JA.getInputs()[I];
6258
6259 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006260 CurTC = nullptr;
David L. Jonesf561aba2017-03-08 01:02:16 +00006261 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006262 assert(CurTC == nullptr && "Expected one dependence!");
David L. Jonesf561aba2017-03-08 01:02:16 +00006263 CurKind = A->getOffloadingDeviceKind();
6264 CurTC = TC;
6265 });
6266 }
6267 Triples += Action::GetOffloadKindName(CurKind);
6268 Triples += '-';
6269 Triples += CurTC->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006270 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6271 Triples += '-';
6272 Triples += CurDep->getOffloadingArch();
6273 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006274 }
6275 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6276
6277 // Get bundled file command.
6278 CmdArgs.push_back(
6279 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6280
6281 // Get unbundled files command.
6282 SmallString<128> UB;
6283 UB += "-inputs=";
6284 for (unsigned I = 0; I < Inputs.size(); ++I) {
6285 if (I)
6286 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006287
6288 // Find ToolChain for this input.
6289 const ToolChain *CurTC = &getToolChain();
6290 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6291 CurTC = nullptr;
6292 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6293 assert(CurTC == nullptr && "Expected one dependence!");
6294 CurTC = TC;
6295 });
6296 }
6297 UB += CurTC->getInputFilename(Inputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006298 }
6299 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6300
6301 // All the inputs are encoded as commands.
6302 C.addCommand(llvm::make_unique<Command>(
6303 JA, *this,
6304 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6305 CmdArgs, None));
6306}
6307
6308void OffloadBundler::ConstructJobMultipleOutputs(
6309 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6310 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6311 const char *LinkingOutput) const {
6312 // The version with multiple outputs is expected to refer to a unbundling job.
6313 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6314
6315 // The unbundling command looks like this:
6316 // clang-offload-bundler -type=bc
6317 // -targets=host-triple,openmp-triple1,openmp-triple2
6318 // -inputs=input_file
6319 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6320 // -unbundle
6321
6322 ArgStringList CmdArgs;
6323
6324 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6325 InputInfo Input = Inputs.front();
6326
6327 // Get the type.
6328 CmdArgs.push_back(TCArgs.MakeArgString(
6329 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6330
6331 // Get the targets.
6332 SmallString<128> Triples;
6333 Triples += "-targets=";
6334 auto DepInfo = UA.getDependentActionsInfo();
6335 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6336 if (I)
6337 Triples += ',';
6338
6339 auto &Dep = DepInfo[I];
6340 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6341 Triples += '-';
6342 Triples += Dep.DependentToolChain->getTriple().normalize();
Yaxun Liu609f7522018-05-11 19:02:18 +00006343 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6344 !Dep.DependentBoundArch.empty()) {
6345 Triples += '-';
6346 Triples += Dep.DependentBoundArch;
6347 }
David L. Jonesf561aba2017-03-08 01:02:16 +00006348 }
6349
6350 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6351
6352 // Get bundled file command.
6353 CmdArgs.push_back(
6354 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6355
6356 // Get unbundled files command.
6357 SmallString<128> UB;
6358 UB += "-outputs=";
6359 for (unsigned I = 0; I < Outputs.size(); ++I) {
6360 if (I)
6361 UB += ',';
Jonas Hahnfeld7c78cc52017-11-21 14:44:45 +00006362 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
David L. Jonesf561aba2017-03-08 01:02:16 +00006363 }
6364 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6365 CmdArgs.push_back("-unbundle");
6366
6367 // All the inputs are encoded as commands.
6368 C.addCommand(llvm::make_unique<Command>(
6369 JA, *this,
6370 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6371 CmdArgs, None));
6372}