1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Tools.h"
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
45
46 #ifdef LLVM_ON_UNIX
47 #include <unistd.h> // For getuid().
48 #endif
49
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
54
handleTargetFeaturesGroup(const ArgList & Args,std::vector<const char * > & Features,OptSpecifier Group)55 static void handleTargetFeaturesGroup(const ArgList &Args,
56 std::vector<const char *> &Features,
57 OptSpecifier Group) {
58 for (const Arg *A : Args.filtered(Group)) {
59 StringRef Name = A->getOption().getName();
60 A->claim();
61
62 // Skip over "-m".
63 assert(Name.startswith("m") && "Invalid feature name.");
64 Name = Name.substr(1);
65
66 bool IsNegative = Name.startswith("no-");
67 if (IsNegative)
68 Name = Name.substr(3);
69 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
70 }
71 }
72
getSparcAsmModeForCPU(StringRef Name,const llvm::Triple & Triple)73 static const char *getSparcAsmModeForCPU(StringRef Name,
74 const llvm::Triple &Triple) {
75 if (Triple.getArch() == llvm::Triple::sparcv9) {
76 return llvm::StringSwitch<const char *>(Name)
77 .Case("niagara", "-Av9b")
78 .Case("niagara2", "-Av9b")
79 .Case("niagara3", "-Av9d")
80 .Case("niagara4", "-Av9d")
81 .Default("-Av9");
82 } else {
83 return llvm::StringSwitch<const char *>(Name)
84 .Case("v8", "-Av8")
85 .Case("supersparc", "-Av8")
86 .Case("sparclite", "-Asparclite")
87 .Case("f934", "-Asparclite")
88 .Case("hypersparc", "-Av8")
89 .Case("sparclite86x", "-Asparclite")
90 .Case("sparclet", "-Asparclet")
91 .Case("tsc701", "-Asparclet")
92 .Case("v9", "-Av8plus")
93 .Case("ultrasparc", "-Av8plus")
94 .Case("ultrasparc3", "-Av8plus")
95 .Case("niagara", "-Av8plusb")
96 .Case("niagara2", "-Av8plusb")
97 .Case("niagara3", "-Av8plusd")
98 .Case("niagara4", "-Av8plusd")
99 .Case("leon2", "-Av8")
100 .Case("at697e", "-Av8")
101 .Case("at697f", "-Av8")
102 .Case("leon3", "-Av8")
103 .Case("ut699", "-Av8")
104 .Case("gr712rc", "-Av8")
105 .Case("leon4", "-Av8")
106 .Case("gr740", "-Av8")
107 .Default("-Av8");
108 }
109 }
110
111 /// CheckPreprocessingOptions - Perform some validation of preprocessing
112 /// arguments that is shared with gcc.
CheckPreprocessingOptions(const Driver & D,const ArgList & Args)113 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
114 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
115 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
116 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
117 D.Diag(diag::err_drv_argument_only_allowed_with)
118 << A->getBaseArg().getAsString(Args)
119 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
120 }
121 }
122 }
123
124 /// CheckCodeGenerationOptions - Perform some validation of code generation
125 /// arguments that is shared with gcc.
CheckCodeGenerationOptions(const Driver & D,const ArgList & Args)126 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
127 // In gcc, only ARM checks this, but it seems reasonable to check universally.
128 if (Args.hasArg(options::OPT_static))
129 if (const Arg *A =
130 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
131 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
132 << "-static";
133 }
134
135 // Add backslashes to escape spaces and other backslashes.
136 // This is used for the space-separated argument list specified with
137 // the -dwarf-debug-flags option.
EscapeSpacesAndBackslashes(const char * Arg,SmallVectorImpl<char> & Res)138 static void EscapeSpacesAndBackslashes(const char *Arg,
139 SmallVectorImpl<char> &Res) {
140 for (; *Arg; ++Arg) {
141 switch (*Arg) {
142 default:
143 break;
144 case ' ':
145 case '\\':
146 Res.push_back('\\');
147 break;
148 }
149 Res.push_back(*Arg);
150 }
151 }
152
153 // Quote target names for inclusion in GNU Make dependency files.
154 // Only the characters '$', '#', ' ', '\t' are quoted.
QuoteTarget(StringRef Target,SmallVectorImpl<char> & Res)155 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
156 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
157 switch (Target[i]) {
158 case ' ':
159 case '\t':
160 // Escape the preceding backslashes
161 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
162 Res.push_back('\\');
163
164 // Escape the space/tab
165 Res.push_back('\\');
166 break;
167 case '$':
168 Res.push_back('$');
169 break;
170 case '#':
171 Res.push_back('\\');
172 break;
173 default:
174 break;
175 }
176
177 Res.push_back(Target[i]);
178 }
179 }
180
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)181 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
182 const char *ArgName, const char *EnvVar) {
183 const char *DirList = ::getenv(EnvVar);
184 bool CombinedArg = false;
185
186 if (!DirList)
187 return; // Nothing to do.
188
189 StringRef Name(ArgName);
190 if (Name.equals("-I") || Name.equals("-L"))
191 CombinedArg = true;
192
193 StringRef Dirs(DirList);
194 if (Dirs.empty()) // Empty string should not add '.'.
195 return;
196
197 StringRef::size_type Delim;
198 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
199 if (Delim == 0) { // Leading colon.
200 if (CombinedArg) {
201 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
202 } else {
203 CmdArgs.push_back(ArgName);
204 CmdArgs.push_back(".");
205 }
206 } else {
207 if (CombinedArg) {
208 CmdArgs.push_back(
209 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
210 } else {
211 CmdArgs.push_back(ArgName);
212 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
213 }
214 }
215 Dirs = Dirs.substr(Delim + 1);
216 }
217
218 if (Dirs.empty()) { // Trailing colon.
219 if (CombinedArg) {
220 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
221 } else {
222 CmdArgs.push_back(ArgName);
223 CmdArgs.push_back(".");
224 }
225 } else { // Add the last path.
226 if (CombinedArg) {
227 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
228 } else {
229 CmdArgs.push_back(ArgName);
230 CmdArgs.push_back(Args.MakeArgString(Dirs));
231 }
232 }
233 }
234
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs)235 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
236 const ArgList &Args, ArgStringList &CmdArgs) {
237 const Driver &D = TC.getDriver();
238
239 // Add extra linker input arguments which are not treated as inputs
240 // (constructed via -Xarch_).
241 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
242
243 for (const auto &II : Inputs) {
244 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
245 // Don't try to pass LLVM inputs unless we have native support.
246 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
247
248 // Add filenames immediately.
249 if (II.isFilename()) {
250 CmdArgs.push_back(II.getFilename());
251 continue;
252 }
253
254 // Otherwise, this is a linker input argument.
255 const Arg &A = II.getInputArg();
256
257 // Handle reserved library options.
258 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
259 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
260 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
261 TC.AddCCKextLibArgs(Args, CmdArgs);
262 else if (A.getOption().matches(options::OPT_z)) {
263 // Pass -z prefix for gcc linker compatibility.
264 A.claim();
265 A.render(Args, CmdArgs);
266 } else {
267 A.renderAsInput(Args, CmdArgs);
268 }
269 }
270
271 // LIBRARY_PATH - included following the user specified library paths.
272 // and only supported on native toolchains.
273 if (!TC.isCrossCompiling())
274 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
275 }
276
277 /// \brief Determine whether Objective-C automated reference counting is
278 /// enabled.
isObjCAutoRefCount(const ArgList & Args)279 static bool isObjCAutoRefCount(const ArgList &Args) {
280 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
281 }
282
283 /// \brief Determine whether we are linking the ObjC runtime.
isObjCRuntimeLinked(const ArgList & Args)284 static bool isObjCRuntimeLinked(const ArgList &Args) {
285 if (isObjCAutoRefCount(Args)) {
286 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
287 return true;
288 }
289 return Args.hasArg(options::OPT_fobjc_link_runtime);
290 }
291
forwardToGCC(const Option & O)292 static bool forwardToGCC(const Option &O) {
293 // Don't forward inputs from the original command line. They are added from
294 // InputInfoList.
295 return O.getKind() != Option::InputClass &&
296 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
297 }
298
AddPreprocessingOptions(Compilation & C,const JobAction & JA,const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfoList & Inputs,const ToolChain * AuxToolChain) const299 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
300 const Driver &D, const ArgList &Args,
301 ArgStringList &CmdArgs,
302 const InputInfo &Output,
303 const InputInfoList &Inputs,
304 const ToolChain *AuxToolChain) const {
305 Arg *A;
306 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
307
308 CheckPreprocessingOptions(D, Args);
309
310 Args.AddLastArg(CmdArgs, options::OPT_C);
311 Args.AddLastArg(CmdArgs, options::OPT_CC);
312
313 // Handle dependency file generation.
314 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
315 (A = Args.getLastArg(options::OPT_MD)) ||
316 (A = Args.getLastArg(options::OPT_MMD))) {
317 // Determine the output location.
318 const char *DepFile;
319 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
320 DepFile = MF->getValue();
321 C.addFailureResultFile(DepFile, &JA);
322 } else if (Output.getType() == types::TY_Dependencies) {
323 DepFile = Output.getFilename();
324 } else if (A->getOption().matches(options::OPT_M) ||
325 A->getOption().matches(options::OPT_MM)) {
326 DepFile = "-";
327 } else {
328 DepFile = getDependencyFileName(Args, Inputs);
329 C.addFailureResultFile(DepFile, &JA);
330 }
331 CmdArgs.push_back("-dependency-file");
332 CmdArgs.push_back(DepFile);
333
334 // Add a default target if one wasn't specified.
335 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
336 const char *DepTarget;
337
338 // If user provided -o, that is the dependency target, except
339 // when we are only generating a dependency file.
340 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
341 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
342 DepTarget = OutputOpt->getValue();
343 } else {
344 // Otherwise derive from the base input.
345 //
346 // FIXME: This should use the computed output file location.
347 SmallString<128> P(Inputs[0].getBaseInput());
348 llvm::sys::path::replace_extension(P, "o");
349 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
350 }
351
352 CmdArgs.push_back("-MT");
353 SmallString<128> Quoted;
354 QuoteTarget(DepTarget, Quoted);
355 CmdArgs.push_back(Args.MakeArgString(Quoted));
356 }
357
358 if (A->getOption().matches(options::OPT_M) ||
359 A->getOption().matches(options::OPT_MD))
360 CmdArgs.push_back("-sys-header-deps");
361 if ((isa<PrecompileJobAction>(JA) &&
362 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
363 Args.hasArg(options::OPT_fmodule_file_deps))
364 CmdArgs.push_back("-module-file-deps");
365 }
366
367 if (Args.hasArg(options::OPT_MG)) {
368 if (!A || A->getOption().matches(options::OPT_MD) ||
369 A->getOption().matches(options::OPT_MMD))
370 D.Diag(diag::err_drv_mg_requires_m_or_mm);
371 CmdArgs.push_back("-MG");
372 }
373
374 Args.AddLastArg(CmdArgs, options::OPT_MP);
375 Args.AddLastArg(CmdArgs, options::OPT_MV);
376
377 // Convert all -MQ <target> args to -MT <quoted target>
378 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
379 A->claim();
380
381 if (A->getOption().matches(options::OPT_MQ)) {
382 CmdArgs.push_back("-MT");
383 SmallString<128> Quoted;
384 QuoteTarget(A->getValue(), Quoted);
385 CmdArgs.push_back(Args.MakeArgString(Quoted));
386
387 // -MT flag - no change
388 } else {
389 A->render(Args, CmdArgs);
390 }
391 }
392
393 // Add -i* options, and automatically translate to
394 // -include-pch/-include-pth for transparent PCH support. It's
395 // wonky, but we include looking for .gch so we can support seamless
396 // replacement into a build system already set up to be generating
397 // .gch files.
398 int YcIndex = -1, YuIndex = -1;
399 {
400 int AI = -1;
401 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
402 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
403 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
404 // Walk the whole i_Group and skip non "-include" flags so that the index
405 // here matches the index in the next loop below.
406 ++AI;
407 if (!A->getOption().matches(options::OPT_include))
408 continue;
409 if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
410 YcIndex = AI;
411 if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
412 YuIndex = AI;
413 }
414 }
415 if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
416 Driver::InputList Inputs;
417 D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
418 assert(Inputs.size() == 1 && "Need one input when building pch");
419 CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
420 Inputs[0].second->getValue()));
421 }
422
423 bool RenderedImplicitInclude = false;
424 int AI = -1;
425 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
426 ++AI;
427
428 if (getToolChain().getDriver().IsCLMode() &&
429 A->getOption().matches(options::OPT_include)) {
430 // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
431 // include is compiled into foo.h, and everything after goes into
432 // the .obj file. /Yufoo.h means that all includes prior to and including
433 // foo.h are completely skipped and replaced with a use of the pch file
434 // for foo.h. (Each flag can have at most one value, multiple /Yc flags
435 // just mean that the last one wins.) If /Yc and /Yu are both present
436 // and refer to the same file, /Yc wins.
437 // Note that OPT__SLASH_FI gets mapped to OPT_include.
438 // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
439 // cl.exe seems to support both flags with different values, but that
440 // seems strange (which flag does /Fp now refer to?), so don't implement
441 // that until someone needs it.
442 int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
443 if (PchIndex != -1) {
444 if (isa<PrecompileJobAction>(JA)) {
445 // When building the pch, skip all includes after the pch.
446 assert(YcIndex != -1 && PchIndex == YcIndex);
447 if (AI >= YcIndex)
448 continue;
449 } else {
450 // When using the pch, skip all includes prior to the pch.
451 if (AI < PchIndex) {
452 A->claim();
453 continue;
454 }
455 if (AI == PchIndex) {
456 A->claim();
457 CmdArgs.push_back("-include-pch");
458 CmdArgs.push_back(
459 Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
460 continue;
461 }
462 }
463 }
464 } else if (A->getOption().matches(options::OPT_include)) {
465 // Handling of gcc-style gch precompiled headers.
466 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
467 RenderedImplicitInclude = true;
468
469 // Use PCH if the user requested it.
470 bool UsePCH = D.CCCUsePCH;
471
472 bool FoundPTH = false;
473 bool FoundPCH = false;
474 SmallString<128> P(A->getValue());
475 // We want the files to have a name like foo.h.pch. Add a dummy extension
476 // so that replace_extension does the right thing.
477 P += ".dummy";
478 if (UsePCH) {
479 llvm::sys::path::replace_extension(P, "pch");
480 if (llvm::sys::fs::exists(P))
481 FoundPCH = true;
482 }
483
484 if (!FoundPCH) {
485 llvm::sys::path::replace_extension(P, "pth");
486 if (llvm::sys::fs::exists(P))
487 FoundPTH = true;
488 }
489
490 if (!FoundPCH && !FoundPTH) {
491 llvm::sys::path::replace_extension(P, "gch");
492 if (llvm::sys::fs::exists(P)) {
493 FoundPCH = UsePCH;
494 FoundPTH = !UsePCH;
495 }
496 }
497
498 if (FoundPCH || FoundPTH) {
499 if (IsFirstImplicitInclude) {
500 A->claim();
501 if (UsePCH)
502 CmdArgs.push_back("-include-pch");
503 else
504 CmdArgs.push_back("-include-pth");
505 CmdArgs.push_back(Args.MakeArgString(P));
506 continue;
507 } else {
508 // Ignore the PCH if not first on command line and emit warning.
509 D.Diag(diag::warn_drv_pch_not_first_include) << P
510 << A->getAsString(Args);
511 }
512 }
513 } else if (A->getOption().matches(options::OPT_isystem_after)) {
514 // Handling of paths which must come late. These entries are handled by
515 // the toolchain itself after the resource dir is inserted in the right
516 // search order.
517 // Do not claim the argument so that the use of the argument does not
518 // silently go unnoticed on toolchains which do not honour the option.
519 continue;
520 }
521
522 // Not translated, render as usual.
523 A->claim();
524 A->render(Args, CmdArgs);
525 }
526
527 Args.AddAllArgs(CmdArgs,
528 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
529 options::OPT_F, options::OPT_index_header_map});
530
531 // Add -Wp, and -Xpreprocessor if using the preprocessor.
532
533 // FIXME: There is a very unfortunate problem here, some troubled
534 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
535 // really support that we would have to parse and then translate
536 // those options. :(
537 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
538 options::OPT_Xpreprocessor);
539
540 // -I- is a deprecated GCC feature, reject it.
541 if (Arg *A = Args.getLastArg(options::OPT_I_))
542 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
543
544 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
545 // -isysroot to the CC1 invocation.
546 StringRef sysroot = C.getSysRoot();
547 if (sysroot != "") {
548 if (!Args.hasArg(options::OPT_isysroot)) {
549 CmdArgs.push_back("-isysroot");
550 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
551 }
552 }
553
554 // Parse additional include paths from environment variables.
555 // FIXME: We should probably sink the logic for handling these from the
556 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
557 // CPATH - included following the user specified includes (but prior to
558 // builtin and standard includes).
559 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
560 // C_INCLUDE_PATH - system includes enabled when compiling C.
561 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
562 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
563 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
564 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
565 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
566 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
567 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
568
569 // Optional AuxToolChain indicates that we need to include headers
570 // for more than one target. If that's the case, add include paths
571 // from AuxToolChain right after include paths of the same kind for
572 // the current target.
573
574 // Add C++ include arguments, if needed.
575 if (types::isCXX(Inputs[0].getType())) {
576 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
577 if (AuxToolChain)
578 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
579 }
580
581 // Add system include arguments for all targets but IAMCU.
582 if (!IsIAMCU) {
583 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
584 if (AuxToolChain)
585 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
586 } else {
587 // For IAMCU add special include arguments.
588 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
589 }
590
591 // Add CUDA include arguments, if needed.
592 if (types::isCuda(Inputs[0].getType()))
593 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
594 }
595
596 // FIXME: Move to target hook.
isSignedCharDefault(const llvm::Triple & Triple)597 static bool isSignedCharDefault(const llvm::Triple &Triple) {
598 switch (Triple.getArch()) {
599 default:
600 return true;
601
602 case llvm::Triple::aarch64:
603 case llvm::Triple::aarch64_be:
604 case llvm::Triple::arm:
605 case llvm::Triple::armeb:
606 case llvm::Triple::thumb:
607 case llvm::Triple::thumbeb:
608 if (Triple.isOSDarwin() || Triple.isOSWindows())
609 return true;
610 return false;
611
612 case llvm::Triple::ppc:
613 case llvm::Triple::ppc64:
614 if (Triple.isOSDarwin())
615 return true;
616 return false;
617
618 case llvm::Triple::hexagon:
619 case llvm::Triple::ppc64le:
620 case llvm::Triple::systemz:
621 case llvm::Triple::xcore:
622 return false;
623 }
624 }
625
isNoCommonDefault(const llvm::Triple & Triple)626 static bool isNoCommonDefault(const llvm::Triple &Triple) {
627 switch (Triple.getArch()) {
628 default:
629 return false;
630
631 case llvm::Triple::xcore:
632 case llvm::Triple::wasm32:
633 case llvm::Triple::wasm64:
634 return true;
635 }
636 }
637
638 // ARM tools start.
639
640 // Get SubArch (vN).
getARMSubArchVersionNumber(const llvm::Triple & Triple)641 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
642 llvm::StringRef Arch = Triple.getArchName();
643 return llvm::ARM::parseArchVersion(Arch);
644 }
645
646 // True if M-profile.
isARMMProfile(const llvm::Triple & Triple)647 static bool isARMMProfile(const llvm::Triple &Triple) {
648 llvm::StringRef Arch = Triple.getArchName();
649 unsigned Profile = llvm::ARM::parseArchProfile(Arch);
650 return Profile == llvm::ARM::PK_M;
651 }
652
653 // Get Arch/CPU from args.
getARMArchCPUFromArgs(const ArgList & Args,llvm::StringRef & Arch,llvm::StringRef & CPU,bool FromAs=false)654 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
655 llvm::StringRef &CPU, bool FromAs = false) {
656 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
657 CPU = A->getValue();
658 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
659 Arch = A->getValue();
660 if (!FromAs)
661 return;
662
663 for (const Arg *A :
664 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
665 StringRef Value = A->getValue();
666 if (Value.startswith("-mcpu="))
667 CPU = Value.substr(6);
668 if (Value.startswith("-march="))
669 Arch = Value.substr(7);
670 }
671 }
672
673 // Handle -mhwdiv=.
674 // FIXME: Use ARMTargetParser.
getARMHWDivFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef HWDiv,std::vector<const char * > & Features)675 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
676 const ArgList &Args, StringRef HWDiv,
677 std::vector<const char *> &Features) {
678 unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
679 if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
680 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
681 }
682
683 // Handle -mfpu=.
getARMFPUFeatures(const Driver & D,const Arg * A,const ArgList & Args,StringRef FPU,std::vector<const char * > & Features)684 static void getARMFPUFeatures(const Driver &D, const Arg *A,
685 const ArgList &Args, StringRef FPU,
686 std::vector<const char *> &Features) {
687 unsigned FPUID = llvm::ARM::parseFPU(FPU);
688 if (!llvm::ARM::getFPUFeatures(FPUID, Features))
689 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
690 }
691
692 // Decode ARM features from string like +[no]featureA+[no]featureB+...
DecodeARMFeatures(const Driver & D,StringRef text,std::vector<const char * > & Features)693 static bool DecodeARMFeatures(const Driver &D, StringRef text,
694 std::vector<const char *> &Features) {
695 SmallVector<StringRef, 8> Split;
696 text.split(Split, StringRef("+"), -1, false);
697
698 for (StringRef Feature : Split) {
699 const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
700 if (FeatureName)
701 Features.push_back(FeatureName);
702 else
703 return false;
704 }
705 return true;
706 }
707
708 // Check if -march is valid by checking if it can be canonicalised and parsed.
709 // getARMArch is used here instead of just checking the -march value in order
710 // to handle -march=native correctly.
checkARMArchName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef ArchName,std::vector<const char * > & Features,const llvm::Triple & Triple)711 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
712 llvm::StringRef ArchName,
713 std::vector<const char *> &Features,
714 const llvm::Triple &Triple) {
715 std::pair<StringRef, StringRef> Split = ArchName.split("+");
716
717 std::string MArch = arm::getARMArch(ArchName, Triple);
718 if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
719 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
720 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
721 }
722
723 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
checkARMCPUName(const Driver & D,const Arg * A,const ArgList & Args,llvm::StringRef CPUName,llvm::StringRef ArchName,std::vector<const char * > & Features,const llvm::Triple & Triple)724 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
725 llvm::StringRef CPUName, llvm::StringRef ArchName,
726 std::vector<const char *> &Features,
727 const llvm::Triple &Triple) {
728 std::pair<StringRef, StringRef> Split = CPUName.split("+");
729
730 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
731 if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
732 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
733 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
734 }
735
useAAPCSForMachO(const llvm::Triple & T)736 static bool useAAPCSForMachO(const llvm::Triple &T) {
737 // The backend is hardwired to assume AAPCS for M-class processors, ensure
738 // the frontend matches that.
739 return T.getEnvironment() == llvm::Triple::EABI ||
740 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
741 }
742
743 // Select the float ABI as determined by -msoft-float, -mhard-float, and
744 // -mfloat-abi=.
getARMFloatABI(const ToolChain & TC,const ArgList & Args)745 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
746 const Driver &D = TC.getDriver();
747 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
748 auto SubArch = getARMSubArchVersionNumber(Triple);
749 arm::FloatABI ABI = FloatABI::Invalid;
750 if (Arg *A =
751 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
752 options::OPT_mfloat_abi_EQ)) {
753 if (A->getOption().matches(options::OPT_msoft_float)) {
754 ABI = FloatABI::Soft;
755 } else if (A->getOption().matches(options::OPT_mhard_float)) {
756 ABI = FloatABI::Hard;
757 } else {
758 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
759 .Case("soft", FloatABI::Soft)
760 .Case("softfp", FloatABI::SoftFP)
761 .Case("hard", FloatABI::Hard)
762 .Default(FloatABI::Invalid);
763 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
764 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
765 ABI = FloatABI::Soft;
766 }
767 }
768
769 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
770 // "apcs-gnu".
771 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
772 ABI == FloatABI::Hard) {
773 D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
774 << Triple.getArchName();
775 }
776 }
777
778 // If unspecified, choose the default based on the platform.
779 if (ABI == FloatABI::Invalid) {
780 switch (Triple.getOS()) {
781 case llvm::Triple::Darwin:
782 case llvm::Triple::MacOSX:
783 case llvm::Triple::IOS:
784 case llvm::Triple::TvOS: {
785 // Darwin defaults to "softfp" for v6 and v7.
786 ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
787 ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
788 break;
789 }
790 case llvm::Triple::WatchOS:
791 ABI = FloatABI::Hard;
792 break;
793
794 // FIXME: this is invalid for WindowsCE
795 case llvm::Triple::Win32:
796 ABI = FloatABI::Hard;
797 break;
798
799 case llvm::Triple::FreeBSD:
800 switch (Triple.getEnvironment()) {
801 case llvm::Triple::GNUEABIHF:
802 ABI = FloatABI::Hard;
803 break;
804 default:
805 // FreeBSD defaults to soft float
806 ABI = FloatABI::Soft;
807 break;
808 }
809 break;
810
811 default:
812 switch (Triple.getEnvironment()) {
813 case llvm::Triple::GNUEABIHF:
814 case llvm::Triple::MuslEABIHF:
815 case llvm::Triple::EABIHF:
816 ABI = FloatABI::Hard;
817 break;
818 case llvm::Triple::GNUEABI:
819 case llvm::Triple::MuslEABI:
820 case llvm::Triple::EABI:
821 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
822 ABI = FloatABI::SoftFP;
823 break;
824 case llvm::Triple::Android:
825 ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
826 break;
827 default:
828 // Assume "soft", but warn the user we are guessing.
829 if (Triple.isOSBinFormatMachO() &&
830 Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
831 ABI = FloatABI::Hard;
832 else
833 ABI = FloatABI::Soft;
834
835 if (Triple.getOS() != llvm::Triple::UnknownOS ||
836 !Triple.isOSBinFormatMachO())
837 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
838 break;
839 }
840 }
841 }
842
843 assert(ABI != FloatABI::Invalid && "must select an ABI");
844 return ABI;
845 }
846
getARMTargetFeatures(const ToolChain & TC,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features,bool ForAS)847 static void getARMTargetFeatures(const ToolChain &TC,
848 const llvm::Triple &Triple,
849 const ArgList &Args,
850 std::vector<const char *> &Features,
851 bool ForAS) {
852 const Driver &D = TC.getDriver();
853
854 bool KernelOrKext =
855 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
856 arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
857 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
858 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
859
860 if (!ForAS) {
861 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
862 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
863 // stripped out by the ARM target. We should probably pass this a new
864 // -target-option, which is handled by the -cc1/-cc1as invocation.
865 //
866 // FIXME2: For consistency, it would be ideal if we set up the target
867 // machine state the same when using the frontend or the assembler. We don't
868 // currently do that for the assembler, we pass the options directly to the
869 // backend and never even instantiate the frontend TargetInfo. If we did,
870 // and used its handleTargetFeatures hook, then we could ensure the
871 // assembler and the frontend behave the same.
872
873 // Use software floating point operations?
874 if (ABI == arm::FloatABI::Soft)
875 Features.push_back("+soft-float");
876
877 // Use software floating point argument passing?
878 if (ABI != arm::FloatABI::Hard)
879 Features.push_back("+soft-float-abi");
880 } else {
881 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
882 // to the assembler correctly.
883 for (const Arg *A :
884 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
885 StringRef Value = A->getValue();
886 if (Value.startswith("-mfpu=")) {
887 WaFPU = A;
888 } else if (Value.startswith("-mcpu=")) {
889 WaCPU = A;
890 } else if (Value.startswith("-mhwdiv=")) {
891 WaHDiv = A;
892 } else if (Value.startswith("-march=")) {
893 WaArch = A;
894 }
895 }
896 }
897
898 // Check -march. ClangAs gives preference to -Wa,-march=.
899 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
900 StringRef ArchName;
901 if (WaArch) {
902 if (ArchArg)
903 D.Diag(clang::diag::warn_drv_unused_argument)
904 << ArchArg->getAsString(Args);
905 ArchName = StringRef(WaArch->getValue()).substr(7);
906 checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
907 // FIXME: Set Arch.
908 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
909 } else if (ArchArg) {
910 ArchName = ArchArg->getValue();
911 checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
912 }
913
914 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
915 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
916 StringRef CPUName;
917 if (WaCPU) {
918 if (CPUArg)
919 D.Diag(clang::diag::warn_drv_unused_argument)
920 << CPUArg->getAsString(Args);
921 CPUName = StringRef(WaCPU->getValue()).substr(6);
922 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
923 } else if (CPUArg) {
924 CPUName = CPUArg->getValue();
925 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
926 }
927
928 // Add CPU features for generic CPUs
929 if (CPUName == "native") {
930 llvm::StringMap<bool> HostFeatures;
931 if (llvm::sys::getHostCPUFeatures(HostFeatures))
932 for (auto &F : HostFeatures)
933 Features.push_back(
934 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
935 }
936
937 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
938 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
939 if (WaFPU) {
940 if (FPUArg)
941 D.Diag(clang::diag::warn_drv_unused_argument)
942 << FPUArg->getAsString(Args);
943 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
944 Features);
945 } else if (FPUArg) {
946 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
947 }
948
949 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
950 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
951 if (WaHDiv) {
952 if (HDivArg)
953 D.Diag(clang::diag::warn_drv_unused_argument)
954 << HDivArg->getAsString(Args);
955 getARMHWDivFeatures(D, WaHDiv, Args,
956 StringRef(WaHDiv->getValue()).substr(8), Features);
957 } else if (HDivArg)
958 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
959
960 // Setting -msoft-float effectively disables NEON because of the GCC
961 // implementation, although the same isn't true of VFP or VFP3.
962 if (ABI == arm::FloatABI::Soft) {
963 Features.push_back("-neon");
964 // Also need to explicitly disable features which imply NEON.
965 Features.push_back("-crypto");
966 }
967
968 // En/disable crc code generation.
969 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
970 if (A->getOption().matches(options::OPT_mcrc))
971 Features.push_back("+crc");
972 else
973 Features.push_back("-crc");
974 }
975
976 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
977 // neither options are specified, see if we are compiling for kernel/kext and
978 // decide whether to pass "+long-calls" based on the OS and its version.
979 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
980 options::OPT_mno_long_calls)) {
981 if (A->getOption().matches(options::OPT_mlong_calls))
982 Features.push_back("+long-calls");
983 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
984 !Triple.isWatchOS()) {
985 Features.push_back("+long-calls");
986 }
987
988 // Kernel code has more strict alignment requirements.
989 if (KernelOrKext)
990 Features.push_back("+strict-align");
991 else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
992 options::OPT_munaligned_access)) {
993 if (A->getOption().matches(options::OPT_munaligned_access)) {
994 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
995 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
996 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
997 // v8M Baseline follows on from v6M, so doesn't support unaligned memory
998 // access either.
999 else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
1000 D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
1001 } else
1002 Features.push_back("+strict-align");
1003 } else {
1004 // Assume pre-ARMv6 doesn't support unaligned accesses.
1005 //
1006 // ARMv6 may or may not support unaligned accesses depending on the
1007 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
1008 // Darwin and NetBSD targets support unaligned accesses, and others don't.
1009 //
1010 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
1011 // which raises an alignment fault on unaligned accesses. Linux
1012 // defaults this bit to 0 and handles it as a system-wide (not
1013 // per-process) setting. It is therefore safe to assume that ARMv7+
1014 // Linux targets support unaligned accesses. The same goes for NaCl.
1015 //
1016 // The above behavior is consistent with GCC.
1017 int VersionNum = getARMSubArchVersionNumber(Triple);
1018 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
1019 if (VersionNum < 6 ||
1020 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
1021 Features.push_back("+strict-align");
1022 } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
1023 if (VersionNum < 7)
1024 Features.push_back("+strict-align");
1025 } else
1026 Features.push_back("+strict-align");
1027 }
1028
1029 // llvm does not support reserving registers in general. There is support
1030 // for reserving r9 on ARM though (defined as a platform-specific register
1031 // in ARM EABI).
1032 if (Args.hasArg(options::OPT_ffixed_r9))
1033 Features.push_back("+reserve-r9");
1034
1035 // The kext linker doesn't know how to deal with movw/movt.
1036 if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
1037 Features.push_back("+no-movt");
1038 }
1039
AddARMTargetArgs(const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool KernelOrKext) const1040 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1041 ArgStringList &CmdArgs, bool KernelOrKext) const {
1042 // Select the ABI to use.
1043 // FIXME: Support -meabi.
1044 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1045 const char *ABIName = nullptr;
1046 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1047 ABIName = A->getValue();
1048 } else if (Triple.isOSBinFormatMachO()) {
1049 if (useAAPCSForMachO(Triple)) {
1050 ABIName = "aapcs";
1051 } else if (Triple.isWatchABI()) {
1052 ABIName = "aapcs16";
1053 } else {
1054 ABIName = "apcs-gnu";
1055 }
1056 } else if (Triple.isOSWindows()) {
1057 // FIXME: this is invalid for WindowsCE
1058 ABIName = "aapcs";
1059 } else {
1060 // Select the default based on the platform.
1061 switch (Triple.getEnvironment()) {
1062 case llvm::Triple::Android:
1063 case llvm::Triple::GNUEABI:
1064 case llvm::Triple::GNUEABIHF:
1065 case llvm::Triple::MuslEABI:
1066 case llvm::Triple::MuslEABIHF:
1067 ABIName = "aapcs-linux";
1068 break;
1069 case llvm::Triple::EABIHF:
1070 case llvm::Triple::EABI:
1071 ABIName = "aapcs";
1072 break;
1073 default:
1074 if (Triple.getOS() == llvm::Triple::NetBSD)
1075 ABIName = "apcs-gnu";
1076 else
1077 ABIName = "aapcs";
1078 break;
1079 }
1080 }
1081 CmdArgs.push_back("-target-abi");
1082 CmdArgs.push_back(ABIName);
1083
1084 // Determine floating point ABI from the options & target defaults.
1085 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1086 if (ABI == arm::FloatABI::Soft) {
1087 // Floating point operations and argument passing are soft.
1088 // FIXME: This changes CPP defines, we need -target-soft-float.
1089 CmdArgs.push_back("-msoft-float");
1090 CmdArgs.push_back("-mfloat-abi");
1091 CmdArgs.push_back("soft");
1092 } else if (ABI == arm::FloatABI::SoftFP) {
1093 // Floating point operations are hard, but argument passing is soft.
1094 CmdArgs.push_back("-mfloat-abi");
1095 CmdArgs.push_back("soft");
1096 } else {
1097 // Floating point operations and argument passing are hard.
1098 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1099 CmdArgs.push_back("-mfloat-abi");
1100 CmdArgs.push_back("hard");
1101 }
1102
1103 // Forward the -mglobal-merge option for explicit control over the pass.
1104 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1105 options::OPT_mno_global_merge)) {
1106 CmdArgs.push_back("-backend-option");
1107 if (A->getOption().matches(options::OPT_mno_global_merge))
1108 CmdArgs.push_back("-arm-global-merge=false");
1109 else
1110 CmdArgs.push_back("-arm-global-merge=true");
1111 }
1112
1113 if (!Args.hasFlag(options::OPT_mimplicit_float,
1114 options::OPT_mno_implicit_float, true))
1115 CmdArgs.push_back("-no-implicit-float");
1116 }
1117 // ARM tools end.
1118
1119 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1120 /// targeting.
getAArch64TargetCPU(const ArgList & Args)1121 static std::string getAArch64TargetCPU(const ArgList &Args) {
1122 Arg *A;
1123 std::string CPU;
1124 // If we have -mtune or -mcpu, use that.
1125 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1126 CPU = StringRef(A->getValue()).lower();
1127 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1128 StringRef Mcpu = A->getValue();
1129 CPU = Mcpu.split("+").first.lower();
1130 }
1131
1132 // Handle CPU name is 'native'.
1133 if (CPU == "native")
1134 return llvm::sys::getHostCPUName();
1135 else if (CPU.size())
1136 return CPU;
1137
1138 // Make sure we pick "cyclone" if -arch is used.
1139 // FIXME: Should this be picked by checking the target triple instead?
1140 if (Args.getLastArg(options::OPT_arch))
1141 return "cyclone";
1142
1143 return "generic";
1144 }
1145
AddAArch64TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1146 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1147 ArgStringList &CmdArgs) const {
1148 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1149 llvm::Triple Triple(TripleStr);
1150
1151 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1152 Args.hasArg(options::OPT_mkernel) ||
1153 Args.hasArg(options::OPT_fapple_kext))
1154 CmdArgs.push_back("-disable-red-zone");
1155
1156 if (!Args.hasFlag(options::OPT_mimplicit_float,
1157 options::OPT_mno_implicit_float, true))
1158 CmdArgs.push_back("-no-implicit-float");
1159
1160 const char *ABIName = nullptr;
1161 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1162 ABIName = A->getValue();
1163 else if (Triple.isOSDarwin())
1164 ABIName = "darwinpcs";
1165 else
1166 ABIName = "aapcs";
1167
1168 CmdArgs.push_back("-target-abi");
1169 CmdArgs.push_back(ABIName);
1170
1171 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1172 options::OPT_mno_fix_cortex_a53_835769)) {
1173 CmdArgs.push_back("-backend-option");
1174 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1175 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1176 else
1177 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1178 } else if (Triple.isAndroid()) {
1179 // Enabled A53 errata (835769) workaround by default on android
1180 CmdArgs.push_back("-backend-option");
1181 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1182 }
1183
1184 // Forward the -mglobal-merge option for explicit control over the pass.
1185 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1186 options::OPT_mno_global_merge)) {
1187 CmdArgs.push_back("-backend-option");
1188 if (A->getOption().matches(options::OPT_mno_global_merge))
1189 CmdArgs.push_back("-aarch64-global-merge=false");
1190 else
1191 CmdArgs.push_back("-aarch64-global-merge=true");
1192 }
1193 }
1194
1195 // Get CPU and ABI names. They are not independent
1196 // so we have to calculate them together.
getMipsCPUAndABI(const ArgList & Args,const llvm::Triple & Triple,StringRef & CPUName,StringRef & ABIName)1197 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1198 StringRef &CPUName, StringRef &ABIName) {
1199 const char *DefMips32CPU = "mips32r2";
1200 const char *DefMips64CPU = "mips64r2";
1201
1202 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1203 // default for mips64(el)?-img-linux-gnu.
1204 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1205 Triple.getEnvironment() == llvm::Triple::GNU) {
1206 DefMips32CPU = "mips32r6";
1207 DefMips64CPU = "mips64r6";
1208 }
1209
1210 // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1211 if (Triple.isAndroid()) {
1212 DefMips32CPU = "mips32";
1213 DefMips64CPU = "mips64r6";
1214 }
1215
1216 // MIPS3 is the default for mips64*-unknown-openbsd.
1217 if (Triple.getOS() == llvm::Triple::OpenBSD)
1218 DefMips64CPU = "mips3";
1219
1220 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1221 CPUName = A->getValue();
1222
1223 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1224 ABIName = A->getValue();
1225 // Convert a GNU style Mips ABI name to the name
1226 // accepted by LLVM Mips backend.
1227 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1228 .Case("32", "o32")
1229 .Case("64", "n64")
1230 .Default(ABIName);
1231 }
1232
1233 // Setup default CPU and ABI names.
1234 if (CPUName.empty() && ABIName.empty()) {
1235 switch (Triple.getArch()) {
1236 default:
1237 llvm_unreachable("Unexpected triple arch name");
1238 case llvm::Triple::mips:
1239 case llvm::Triple::mipsel:
1240 CPUName = DefMips32CPU;
1241 break;
1242 case llvm::Triple::mips64:
1243 case llvm::Triple::mips64el:
1244 CPUName = DefMips64CPU;
1245 break;
1246 }
1247 }
1248
1249 if (ABIName.empty() &&
1250 (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
1251 Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
1252 ABIName = llvm::StringSwitch<const char *>(CPUName)
1253 .Case("mips1", "o32")
1254 .Case("mips2", "o32")
1255 .Case("mips3", "n64")
1256 .Case("mips4", "n64")
1257 .Case("mips5", "n64")
1258 .Case("mips32", "o32")
1259 .Case("mips32r2", "o32")
1260 .Case("mips32r3", "o32")
1261 .Case("mips32r5", "o32")
1262 .Case("mips32r6", "o32")
1263 .Case("mips64", "n64")
1264 .Case("mips64r2", "n64")
1265 .Case("mips64r3", "n64")
1266 .Case("mips64r5", "n64")
1267 .Case("mips64r6", "n64")
1268 .Case("octeon", "n64")
1269 .Case("p5600", "o32")
1270 .Default("");
1271 }
1272
1273 if (ABIName.empty()) {
1274 // Deduce ABI name from the target triple.
1275 if (Triple.getArch() == llvm::Triple::mips ||
1276 Triple.getArch() == llvm::Triple::mipsel)
1277 ABIName = "o32";
1278 else
1279 ABIName = "n64";
1280 }
1281
1282 if (CPUName.empty()) {
1283 // Deduce CPU name from ABI name.
1284 CPUName = llvm::StringSwitch<const char *>(ABIName)
1285 .Case("o32", DefMips32CPU)
1286 .Cases("n32", "n64", DefMips64CPU)
1287 .Default("");
1288 }
1289
1290 // FIXME: Warn on inconsistent use of -march and -mabi.
1291 }
1292
getMipsABILibSuffix(const ArgList & Args,const llvm::Triple & Triple)1293 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1294 const llvm::Triple &Triple) {
1295 StringRef CPUName, ABIName;
1296 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1297 return llvm::StringSwitch<std::string>(ABIName)
1298 .Case("o32", "")
1299 .Case("n32", "32")
1300 .Case("n64", "64");
1301 }
1302
1303 // Convert ABI name to the GNU tools acceptable variant.
getGnuCompatibleMipsABIName(StringRef ABI)1304 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1305 return llvm::StringSwitch<llvm::StringRef>(ABI)
1306 .Case("o32", "32")
1307 .Case("n64", "64")
1308 .Default(ABI);
1309 }
1310
1311 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1312 // and -mfloat-abi=.
getMipsFloatABI(const Driver & D,const ArgList & Args)1313 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1314 mips::FloatABI ABI = mips::FloatABI::Invalid;
1315 if (Arg *A =
1316 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1317 options::OPT_mfloat_abi_EQ)) {
1318 if (A->getOption().matches(options::OPT_msoft_float))
1319 ABI = mips::FloatABI::Soft;
1320 else if (A->getOption().matches(options::OPT_mhard_float))
1321 ABI = mips::FloatABI::Hard;
1322 else {
1323 ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1324 .Case("soft", mips::FloatABI::Soft)
1325 .Case("hard", mips::FloatABI::Hard)
1326 .Default(mips::FloatABI::Invalid);
1327 if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1328 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1329 ABI = mips::FloatABI::Hard;
1330 }
1331 }
1332 }
1333
1334 // If unspecified, choose the default based on the platform.
1335 if (ABI == mips::FloatABI::Invalid) {
1336 // Assume "hard", because it's a default value used by gcc.
1337 // When we start to recognize specific target MIPS processors,
1338 // we will be able to select the default more correctly.
1339 ABI = mips::FloatABI::Hard;
1340 }
1341
1342 assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1343 return ABI;
1344 }
1345
AddTargetFeature(const ArgList & Args,std::vector<const char * > & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)1346 static void AddTargetFeature(const ArgList &Args,
1347 std::vector<const char *> &Features,
1348 OptSpecifier OnOpt, OptSpecifier OffOpt,
1349 StringRef FeatureName) {
1350 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1351 if (A->getOption().matches(OnOpt))
1352 Features.push_back(Args.MakeArgString("+" + FeatureName));
1353 else
1354 Features.push_back(Args.MakeArgString("-" + FeatureName));
1355 }
1356 }
1357
getMIPSTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1358 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1359 const ArgList &Args,
1360 std::vector<const char *> &Features) {
1361 StringRef CPUName;
1362 StringRef ABIName;
1363 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1364 ABIName = getGnuCompatibleMipsABIName(ABIName);
1365
1366 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1367 options::OPT_mabicalls, "noabicalls");
1368
1369 mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1370 if (FloatABI == mips::FloatABI::Soft) {
1371 // FIXME: Note, this is a hack. We need to pass the selected float
1372 // mode to the MipsTargetInfoBase to define appropriate macros there.
1373 // Now it is the only method.
1374 Features.push_back("+soft-float");
1375 }
1376
1377 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1378 StringRef Val = StringRef(A->getValue());
1379 if (Val == "2008") {
1380 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1381 Features.push_back("+nan2008");
1382 else {
1383 Features.push_back("-nan2008");
1384 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1385 }
1386 } else if (Val == "legacy") {
1387 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1388 Features.push_back("-nan2008");
1389 else {
1390 Features.push_back("+nan2008");
1391 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1392 }
1393 } else
1394 D.Diag(diag::err_drv_unsupported_option_argument)
1395 << A->getOption().getName() << Val;
1396 }
1397
1398 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1399 options::OPT_mdouble_float, "single-float");
1400 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1401 "mips16");
1402 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1403 options::OPT_mno_micromips, "micromips");
1404 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1405 "dsp");
1406 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1407 "dspr2");
1408 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1409 "msa");
1410
1411 // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
1412 // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
1413 // nooddspreg.
1414 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1415 options::OPT_mfp64)) {
1416 if (A->getOption().matches(options::OPT_mfp32))
1417 Features.push_back(Args.MakeArgString("-fp64"));
1418 else if (A->getOption().matches(options::OPT_mfpxx)) {
1419 Features.push_back(Args.MakeArgString("+fpxx"));
1420 Features.push_back(Args.MakeArgString("+nooddspreg"));
1421 } else
1422 Features.push_back(Args.MakeArgString("+fp64"));
1423 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1424 Features.push_back(Args.MakeArgString("+fpxx"));
1425 Features.push_back(Args.MakeArgString("+nooddspreg"));
1426 } else if (mips::isFP64ADefault(Triple, CPUName)) {
1427 Features.push_back(Args.MakeArgString("+fp64"));
1428 Features.push_back(Args.MakeArgString("+nooddspreg"));
1429 }
1430
1431 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1432 options::OPT_modd_spreg, "nooddspreg");
1433 }
1434
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1435 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1436 ArgStringList &CmdArgs) const {
1437 const Driver &D = getToolChain().getDriver();
1438 StringRef CPUName;
1439 StringRef ABIName;
1440 const llvm::Triple &Triple = getToolChain().getTriple();
1441 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1442
1443 CmdArgs.push_back("-target-abi");
1444 CmdArgs.push_back(ABIName.data());
1445
1446 mips::FloatABI ABI = getMipsFloatABI(D, Args);
1447 if (ABI == mips::FloatABI::Soft) {
1448 // Floating point operations and argument passing are soft.
1449 CmdArgs.push_back("-msoft-float");
1450 CmdArgs.push_back("-mfloat-abi");
1451 CmdArgs.push_back("soft");
1452 } else {
1453 // Floating point operations and argument passing are hard.
1454 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1455 CmdArgs.push_back("-mfloat-abi");
1456 CmdArgs.push_back("hard");
1457 }
1458
1459 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1460 if (A->getOption().matches(options::OPT_mxgot)) {
1461 CmdArgs.push_back("-mllvm");
1462 CmdArgs.push_back("-mxgot");
1463 }
1464 }
1465
1466 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1467 options::OPT_mno_ldc1_sdc1)) {
1468 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1469 CmdArgs.push_back("-mllvm");
1470 CmdArgs.push_back("-mno-ldc1-sdc1");
1471 }
1472 }
1473
1474 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1475 options::OPT_mno_check_zero_division)) {
1476 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1477 CmdArgs.push_back("-mllvm");
1478 CmdArgs.push_back("-mno-check-zero-division");
1479 }
1480 }
1481
1482 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1483 StringRef v = A->getValue();
1484 CmdArgs.push_back("-mllvm");
1485 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1486 A->claim();
1487 }
1488
1489 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1490 StringRef Val = StringRef(A->getValue());
1491 if (mips::hasCompactBranches(CPUName)) {
1492 if (Val == "never" || Val == "always" || Val == "optimal") {
1493 CmdArgs.push_back("-mllvm");
1494 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1495 } else
1496 D.Diag(diag::err_drv_unsupported_option_argument)
1497 << A->getOption().getName() << Val;
1498 } else
1499 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1500 }
1501 }
1502
1503 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
getPPCTargetCPU(const ArgList & Args)1504 static std::string getPPCTargetCPU(const ArgList &Args) {
1505 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1506 StringRef CPUName = A->getValue();
1507
1508 if (CPUName == "native") {
1509 std::string CPU = llvm::sys::getHostCPUName();
1510 if (!CPU.empty() && CPU != "generic")
1511 return CPU;
1512 else
1513 return "";
1514 }
1515
1516 return llvm::StringSwitch<const char *>(CPUName)
1517 .Case("common", "generic")
1518 .Case("440", "440")
1519 .Case("440fp", "440")
1520 .Case("450", "450")
1521 .Case("601", "601")
1522 .Case("602", "602")
1523 .Case("603", "603")
1524 .Case("603e", "603e")
1525 .Case("603ev", "603ev")
1526 .Case("604", "604")
1527 .Case("604e", "604e")
1528 .Case("620", "620")
1529 .Case("630", "pwr3")
1530 .Case("G3", "g3")
1531 .Case("7400", "7400")
1532 .Case("G4", "g4")
1533 .Case("7450", "7450")
1534 .Case("G4+", "g4+")
1535 .Case("750", "750")
1536 .Case("970", "970")
1537 .Case("G5", "g5")
1538 .Case("a2", "a2")
1539 .Case("a2q", "a2q")
1540 .Case("e500mc", "e500mc")
1541 .Case("e5500", "e5500")
1542 .Case("power3", "pwr3")
1543 .Case("power4", "pwr4")
1544 .Case("power5", "pwr5")
1545 .Case("power5x", "pwr5x")
1546 .Case("power6", "pwr6")
1547 .Case("power6x", "pwr6x")
1548 .Case("power7", "pwr7")
1549 .Case("power8", "pwr8")
1550 .Case("power9", "pwr9")
1551 .Case("pwr3", "pwr3")
1552 .Case("pwr4", "pwr4")
1553 .Case("pwr5", "pwr5")
1554 .Case("pwr5x", "pwr5x")
1555 .Case("pwr6", "pwr6")
1556 .Case("pwr6x", "pwr6x")
1557 .Case("pwr7", "pwr7")
1558 .Case("pwr8", "pwr8")
1559 .Case("pwr9", "pwr9")
1560 .Case("powerpc", "ppc")
1561 .Case("powerpc64", "ppc64")
1562 .Case("powerpc64le", "ppc64le")
1563 .Default("");
1564 }
1565
1566 return "";
1567 }
1568
getPPCTargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)1569 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1570 const ArgList &Args,
1571 std::vector<const char *> &Features) {
1572 handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1573
1574 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1575 if (FloatABI == ppc::FloatABI::Soft &&
1576 !(Triple.getArch() == llvm::Triple::ppc64 ||
1577 Triple.getArch() == llvm::Triple::ppc64le))
1578 Features.push_back("+soft-float");
1579 else if (FloatABI == ppc::FloatABI::Soft &&
1580 (Triple.getArch() == llvm::Triple::ppc64 ||
1581 Triple.getArch() == llvm::Triple::ppc64le))
1582 D.Diag(diag::err_drv_invalid_mfloat_abi)
1583 << "soft float is not supported for ppc64";
1584
1585 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1586 AddTargetFeature(Args, Features, options::OPT_faltivec,
1587 options::OPT_fno_altivec, "altivec");
1588 }
1589
getPPCFloatABI(const Driver & D,const ArgList & Args)1590 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1591 ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1592 if (Arg *A =
1593 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1594 options::OPT_mfloat_abi_EQ)) {
1595 if (A->getOption().matches(options::OPT_msoft_float))
1596 ABI = ppc::FloatABI::Soft;
1597 else if (A->getOption().matches(options::OPT_mhard_float))
1598 ABI = ppc::FloatABI::Hard;
1599 else {
1600 ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1601 .Case("soft", ppc::FloatABI::Soft)
1602 .Case("hard", ppc::FloatABI::Hard)
1603 .Default(ppc::FloatABI::Invalid);
1604 if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1605 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1606 ABI = ppc::FloatABI::Hard;
1607 }
1608 }
1609 }
1610
1611 // If unspecified, choose the default based on the platform.
1612 if (ABI == ppc::FloatABI::Invalid) {
1613 ABI = ppc::FloatABI::Hard;
1614 }
1615
1616 return ABI;
1617 }
1618
AddPPCTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1619 void Clang::AddPPCTargetArgs(const ArgList &Args,
1620 ArgStringList &CmdArgs) const {
1621 // Select the ABI to use.
1622 const char *ABIName = nullptr;
1623 if (getToolChain().getTriple().isOSLinux())
1624 switch (getToolChain().getArch()) {
1625 case llvm::Triple::ppc64: {
1626 // When targeting a processor that supports QPX, or if QPX is
1627 // specifically enabled, default to using the ABI that supports QPX (so
1628 // long as it is not specifically disabled).
1629 bool HasQPX = false;
1630 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1631 HasQPX = A->getValue() == StringRef("a2q");
1632 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1633 if (HasQPX) {
1634 ABIName = "elfv1-qpx";
1635 break;
1636 }
1637
1638 ABIName = "elfv1";
1639 break;
1640 }
1641 case llvm::Triple::ppc64le:
1642 ABIName = "elfv2";
1643 break;
1644 default:
1645 break;
1646 }
1647
1648 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1649 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1650 // the option if given as we don't have backend support for any targets
1651 // that don't use the altivec abi.
1652 if (StringRef(A->getValue()) != "altivec")
1653 ABIName = A->getValue();
1654
1655 ppc::FloatABI FloatABI =
1656 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1657
1658 if (FloatABI == ppc::FloatABI::Soft) {
1659 // Floating point operations and argument passing are soft.
1660 CmdArgs.push_back("-msoft-float");
1661 CmdArgs.push_back("-mfloat-abi");
1662 CmdArgs.push_back("soft");
1663 } else {
1664 // Floating point operations and argument passing are hard.
1665 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1666 CmdArgs.push_back("-mfloat-abi");
1667 CmdArgs.push_back("hard");
1668 }
1669
1670 if (ABIName) {
1671 CmdArgs.push_back("-target-abi");
1672 CmdArgs.push_back(ABIName);
1673 }
1674 }
1675
hasPPCAbiArg(const ArgList & Args,const char * Value)1676 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1677 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1678 return A && (A->getValue() == StringRef(Value));
1679 }
1680
1681 /// Get the (LLVM) name of the R600 gpu we are targeting.
getR600TargetGPU(const ArgList & Args)1682 static std::string getR600TargetGPU(const ArgList &Args) {
1683 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1684 const char *GPUName = A->getValue();
1685 return llvm::StringSwitch<const char *>(GPUName)
1686 .Cases("rv630", "rv635", "r600")
1687 .Cases("rv610", "rv620", "rs780", "rs880")
1688 .Case("rv740", "rv770")
1689 .Case("palm", "cedar")
1690 .Cases("sumo", "sumo2", "sumo")
1691 .Case("hemlock", "cypress")
1692 .Case("aruba", "cayman")
1693 .Default(GPUName);
1694 }
1695 return "";
1696 }
1697
getLanaiTargetCPU(const ArgList & Args)1698 static std::string getLanaiTargetCPU(const ArgList &Args) {
1699 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1700 return A->getValue();
1701 }
1702 return "";
1703 }
1704
getSparcFloatABI(const Driver & D,const ArgList & Args)1705 sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
1706 const ArgList &Args) {
1707 sparc::FloatABI ABI = sparc::FloatABI::Invalid;
1708 if (Arg *A =
1709 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1710 options::OPT_mfloat_abi_EQ)) {
1711 if (A->getOption().matches(options::OPT_msoft_float))
1712 ABI = sparc::FloatABI::Soft;
1713 else if (A->getOption().matches(options::OPT_mhard_float))
1714 ABI = sparc::FloatABI::Hard;
1715 else {
1716 ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
1717 .Case("soft", sparc::FloatABI::Soft)
1718 .Case("hard", sparc::FloatABI::Hard)
1719 .Default(sparc::FloatABI::Invalid);
1720 if (ABI == sparc::FloatABI::Invalid &&
1721 !StringRef(A->getValue()).empty()) {
1722 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1723 ABI = sparc::FloatABI::Hard;
1724 }
1725 }
1726 }
1727
1728 // If unspecified, choose the default based on the platform.
1729 // Only the hard-float ABI on Sparc is standardized, and it is the
1730 // default. GCC also supports a nonstandard soft-float ABI mode, also
1731 // implemented in LLVM. However as this is not standard we set the default
1732 // to be hard-float.
1733 if (ABI == sparc::FloatABI::Invalid) {
1734 ABI = sparc::FloatABI::Hard;
1735 }
1736
1737 return ABI;
1738 }
1739
getSparcTargetFeatures(const Driver & D,const ArgList & Args,std::vector<const char * > & Features)1740 static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
1741 std::vector<const char *> &Features) {
1742 sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
1743 if (FloatABI == sparc::FloatABI::Soft)
1744 Features.push_back("+soft-float");
1745 }
1746
AddSparcTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1747 void Clang::AddSparcTargetArgs(const ArgList &Args,
1748 ArgStringList &CmdArgs) const {
1749 sparc::FloatABI FloatABI =
1750 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1751
1752 if (FloatABI == sparc::FloatABI::Soft) {
1753 // Floating point operations and argument passing are soft.
1754 CmdArgs.push_back("-msoft-float");
1755 CmdArgs.push_back("-mfloat-abi");
1756 CmdArgs.push_back("soft");
1757 } else {
1758 // Floating point operations and argument passing are hard.
1759 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1760 CmdArgs.push_back("-mfloat-abi");
1761 CmdArgs.push_back("hard");
1762 }
1763 }
1764
AddSystemZTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const1765 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1766 ArgStringList &CmdArgs) const {
1767 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1768 CmdArgs.push_back("-mbackchain");
1769 }
1770
getSystemZTargetCPU(const ArgList & Args)1771 static const char *getSystemZTargetCPU(const ArgList &Args) {
1772 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1773 return A->getValue();
1774 return "z10";
1775 }
1776
getSystemZTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)1777 static void getSystemZTargetFeatures(const ArgList &Args,
1778 std::vector<const char *> &Features) {
1779 // -m(no-)htm overrides use of the transactional-execution facility.
1780 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1781 if (A->getOption().matches(options::OPT_mhtm))
1782 Features.push_back("+transactional-execution");
1783 else
1784 Features.push_back("-transactional-execution");
1785 }
1786 // -m(no-)vx overrides use of the vector facility.
1787 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1788 if (A->getOption().matches(options::OPT_mvx))
1789 Features.push_back("+vector");
1790 else
1791 Features.push_back("-vector");
1792 }
1793 }
1794
getX86TargetCPU(const ArgList & Args,const llvm::Triple & Triple)1795 static const char *getX86TargetCPU(const ArgList &Args,
1796 const llvm::Triple &Triple) {
1797 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1798 if (StringRef(A->getValue()) != "native") {
1799 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1800 return "core-avx2";
1801
1802 return A->getValue();
1803 }
1804
1805 // FIXME: Reject attempts to use -march=native unless the target matches
1806 // the host.
1807 //
1808 // FIXME: We should also incorporate the detected target features for use
1809 // with -native.
1810 std::string CPU = llvm::sys::getHostCPUName();
1811 if (!CPU.empty() && CPU != "generic")
1812 return Args.MakeArgString(CPU);
1813 }
1814
1815 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1816 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1817 StringRef Arch = A->getValue();
1818 const char *CPU;
1819 if (Triple.getArch() == llvm::Triple::x86) {
1820 CPU = llvm::StringSwitch<const char *>(Arch)
1821 .Case("IA32", "i386")
1822 .Case("SSE", "pentium3")
1823 .Case("SSE2", "pentium4")
1824 .Case("AVX", "sandybridge")
1825 .Case("AVX2", "haswell")
1826 .Default(nullptr);
1827 } else {
1828 CPU = llvm::StringSwitch<const char *>(Arch)
1829 .Case("AVX", "sandybridge")
1830 .Case("AVX2", "haswell")
1831 .Default(nullptr);
1832 }
1833 if (CPU)
1834 return CPU;
1835 }
1836
1837 // Select the default CPU if none was given (or detection failed).
1838
1839 if (Triple.getArch() != llvm::Triple::x86_64 &&
1840 Triple.getArch() != llvm::Triple::x86)
1841 return nullptr; // This routine is only handling x86 targets.
1842
1843 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1844
1845 // FIXME: Need target hooks.
1846 if (Triple.isOSDarwin()) {
1847 if (Triple.getArchName() == "x86_64h")
1848 return "core-avx2";
1849 return Is64Bit ? "core2" : "yonah";
1850 }
1851
1852 // Set up default CPU name for PS4 compilers.
1853 if (Triple.isPS4CPU())
1854 return "btver2";
1855
1856 // On Android use targets compatible with gcc
1857 if (Triple.isAndroid())
1858 return Is64Bit ? "x86-64" : "i686";
1859
1860 // Everything else goes to x86-64 in 64-bit mode.
1861 if (Is64Bit)
1862 return "x86-64";
1863
1864 switch (Triple.getOS()) {
1865 case llvm::Triple::FreeBSD:
1866 case llvm::Triple::NetBSD:
1867 case llvm::Triple::OpenBSD:
1868 return "i486";
1869 case llvm::Triple::Haiku:
1870 return "i586";
1871 case llvm::Triple::Bitrig:
1872 return "i686";
1873 default:
1874 // Fallback to p4.
1875 return "pentium4";
1876 }
1877 }
1878
1879 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)1880 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1881 // If we have -mcpu=, use that.
1882 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1883 StringRef CPU = A->getValue();
1884
1885 #ifdef __wasm__
1886 // Handle "native" by examining the host. "native" isn't meaningful when
1887 // cross compiling, so only support this when the host is also WebAssembly.
1888 if (CPU == "native")
1889 return llvm::sys::getHostCPUName();
1890 #endif
1891
1892 return CPU;
1893 }
1894
1895 return "generic";
1896 }
1897
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs=false)1898 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1899 bool FromAs = false) {
1900 switch (T.getArch()) {
1901 default:
1902 return "";
1903
1904 case llvm::Triple::aarch64:
1905 case llvm::Triple::aarch64_be:
1906 return getAArch64TargetCPU(Args);
1907
1908 case llvm::Triple::arm:
1909 case llvm::Triple::armeb:
1910 case llvm::Triple::thumb:
1911 case llvm::Triple::thumbeb: {
1912 StringRef MArch, MCPU;
1913 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1914 return arm::getARMTargetCPU(MCPU, MArch, T);
1915 }
1916 case llvm::Triple::mips:
1917 case llvm::Triple::mipsel:
1918 case llvm::Triple::mips64:
1919 case llvm::Triple::mips64el: {
1920 StringRef CPUName;
1921 StringRef ABIName;
1922 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1923 return CPUName;
1924 }
1925
1926 case llvm::Triple::nvptx:
1927 case llvm::Triple::nvptx64:
1928 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1929 return A->getValue();
1930 return "";
1931
1932 case llvm::Triple::ppc:
1933 case llvm::Triple::ppc64:
1934 case llvm::Triple::ppc64le: {
1935 std::string TargetCPUName = getPPCTargetCPU(Args);
1936 // LLVM may default to generating code for the native CPU,
1937 // but, like gcc, we default to a more generic option for
1938 // each architecture. (except on Darwin)
1939 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1940 if (T.getArch() == llvm::Triple::ppc64)
1941 TargetCPUName = "ppc64";
1942 else if (T.getArch() == llvm::Triple::ppc64le)
1943 TargetCPUName = "ppc64le";
1944 else
1945 TargetCPUName = "ppc";
1946 }
1947 return TargetCPUName;
1948 }
1949
1950 case llvm::Triple::sparc:
1951 case llvm::Triple::sparcel:
1952 case llvm::Triple::sparcv9:
1953 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1954 return A->getValue();
1955 return "";
1956
1957 case llvm::Triple::x86:
1958 case llvm::Triple::x86_64:
1959 return getX86TargetCPU(Args, T);
1960
1961 case llvm::Triple::hexagon:
1962 return "hexagon" +
1963 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1964
1965 case llvm::Triple::lanai:
1966 return getLanaiTargetCPU(Args);
1967
1968 case llvm::Triple::systemz:
1969 return getSystemZTargetCPU(Args);
1970
1971 case llvm::Triple::r600:
1972 case llvm::Triple::amdgcn:
1973 return getR600TargetGPU(Args);
1974
1975 case llvm::Triple::wasm32:
1976 case llvm::Triple::wasm64:
1977 return getWebAssemblyTargetCPU(Args);
1978 }
1979 }
1980
AddGoldPlugin(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,bool IsThinLTO)1981 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1982 ArgStringList &CmdArgs, bool IsThinLTO) {
1983 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1984 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1985 // forward.
1986 CmdArgs.push_back("-plugin");
1987 std::string Plugin =
1988 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1989 CmdArgs.push_back(Args.MakeArgString(Plugin));
1990
1991 // Try to pass driver level flags relevant to LTO code generation down to
1992 // the plugin.
1993
1994 // Handle flags for selecting CPU variants.
1995 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1996 if (!CPU.empty())
1997 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1998
1999 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2000 StringRef OOpt;
2001 if (A->getOption().matches(options::OPT_O4) ||
2002 A->getOption().matches(options::OPT_Ofast))
2003 OOpt = "3";
2004 else if (A->getOption().matches(options::OPT_O))
2005 OOpt = A->getValue();
2006 else if (A->getOption().matches(options::OPT_O0))
2007 OOpt = "0";
2008 if (!OOpt.empty())
2009 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
2010 }
2011
2012 if (IsThinLTO)
2013 CmdArgs.push_back("-plugin-opt=thinlto");
2014
2015 // If an explicit debugger tuning argument appeared, pass it along.
2016 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
2017 options::OPT_ggdbN_Group)) {
2018 if (A->getOption().matches(options::OPT_glldb))
2019 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
2020 else if (A->getOption().matches(options::OPT_gsce))
2021 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
2022 else
2023 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
2024 }
2025 }
2026
2027 /// This is a helper function for validating the optional refinement step
2028 /// parameter in reciprocal argument strings. Return false if there is an error
2029 /// parsing the refinement step. Otherwise, return true and set the Position
2030 /// of the refinement step in the input string.
getRefinementStep(StringRef In,const Driver & D,const Arg & A,size_t & Position)2031 static bool getRefinementStep(StringRef In, const Driver &D,
2032 const Arg &A, size_t &Position) {
2033 const char RefinementStepToken = ':';
2034 Position = In.find(RefinementStepToken);
2035 if (Position != StringRef::npos) {
2036 StringRef Option = A.getOption().getName();
2037 StringRef RefStep = In.substr(Position + 1);
2038 // Allow exactly one numeric character for the additional refinement
2039 // step parameter. This is reasonable for all currently-supported
2040 // operations and architectures because we would expect that a larger value
2041 // of refinement steps would cause the estimate "optimization" to
2042 // under-perform the native operation. Also, if the estimate does not
2043 // converge quickly, it probably will not ever converge, so further
2044 // refinement steps will not produce a better answer.
2045 if (RefStep.size() != 1) {
2046 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2047 return false;
2048 }
2049 char RefStepChar = RefStep[0];
2050 if (RefStepChar < '0' || RefStepChar > '9') {
2051 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
2052 return false;
2053 }
2054 }
2055 return true;
2056 }
2057
2058 /// The -mrecip flag requires processing of many optional parameters.
ParseMRecip(const Driver & D,const ArgList & Args,ArgStringList & OutStrings)2059 static void ParseMRecip(const Driver &D, const ArgList &Args,
2060 ArgStringList &OutStrings) {
2061 StringRef DisabledPrefixIn = "!";
2062 StringRef DisabledPrefixOut = "!";
2063 StringRef EnabledPrefixOut = "";
2064 StringRef Out = "-mrecip=";
2065
2066 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
2067 if (!A)
2068 return;
2069
2070 unsigned NumOptions = A->getNumValues();
2071 if (NumOptions == 0) {
2072 // No option is the same as "all".
2073 OutStrings.push_back(Args.MakeArgString(Out + "all"));
2074 return;
2075 }
2076
2077 // Pass through "all", "none", or "default" with an optional refinement step.
2078 if (NumOptions == 1) {
2079 StringRef Val = A->getValue(0);
2080 size_t RefStepLoc;
2081 if (!getRefinementStep(Val, D, *A, RefStepLoc))
2082 return;
2083 StringRef ValBase = Val.slice(0, RefStepLoc);
2084 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
2085 OutStrings.push_back(Args.MakeArgString(Out + Val));
2086 return;
2087 }
2088 }
2089
2090 // Each reciprocal type may be enabled or disabled individually.
2091 // Check each input value for validity, concatenate them all back together,
2092 // and pass through.
2093
2094 llvm::StringMap<bool> OptionStrings;
2095 OptionStrings.insert(std::make_pair("divd", false));
2096 OptionStrings.insert(std::make_pair("divf", false));
2097 OptionStrings.insert(std::make_pair("vec-divd", false));
2098 OptionStrings.insert(std::make_pair("vec-divf", false));
2099 OptionStrings.insert(std::make_pair("sqrtd", false));
2100 OptionStrings.insert(std::make_pair("sqrtf", false));
2101 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
2102 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
2103
2104 for (unsigned i = 0; i != NumOptions; ++i) {
2105 StringRef Val = A->getValue(i);
2106
2107 bool IsDisabled = Val.startswith(DisabledPrefixIn);
2108 // Ignore the disablement token for string matching.
2109 if (IsDisabled)
2110 Val = Val.substr(1);
2111
2112 size_t RefStep;
2113 if (!getRefinementStep(Val, D, *A, RefStep))
2114 return;
2115
2116 StringRef ValBase = Val.slice(0, RefStep);
2117 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
2118 if (OptionIter == OptionStrings.end()) {
2119 // Try again specifying float suffix.
2120 OptionIter = OptionStrings.find(ValBase.str() + 'f');
2121 if (OptionIter == OptionStrings.end()) {
2122 // The input name did not match any known option string.
2123 D.Diag(diag::err_drv_unknown_argument) << Val;
2124 return;
2125 }
2126 // The option was specified without a float or double suffix.
2127 // Make sure that the double entry was not already specified.
2128 // The float entry will be checked below.
2129 if (OptionStrings[ValBase.str() + 'd']) {
2130 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2131 return;
2132 }
2133 }
2134
2135 if (OptionIter->second == true) {
2136 // Duplicate option specified.
2137 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
2138 return;
2139 }
2140
2141 // Mark the matched option as found. Do not allow duplicate specifiers.
2142 OptionIter->second = true;
2143
2144 // If the precision was not specified, also mark the double entry as found.
2145 if (ValBase.back() != 'f' && ValBase.back() != 'd')
2146 OptionStrings[ValBase.str() + 'd'] = true;
2147
2148 // Build the output string.
2149 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
2150 Out = Args.MakeArgString(Out + Prefix + Val);
2151 if (i != NumOptions - 1)
2152 Out = Args.MakeArgString(Out + ",");
2153 }
2154
2155 OutStrings.push_back(Args.MakeArgString(Out));
2156 }
2157
getX86TargetFeatures(const Driver & D,const llvm::Triple & Triple,const ArgList & Args,std::vector<const char * > & Features)2158 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
2159 const ArgList &Args,
2160 std::vector<const char *> &Features) {
2161 // If -march=native, autodetect the feature list.
2162 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
2163 if (StringRef(A->getValue()) == "native") {
2164 llvm::StringMap<bool> HostFeatures;
2165 if (llvm::sys::getHostCPUFeatures(HostFeatures))
2166 for (auto &F : HostFeatures)
2167 Features.push_back(
2168 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
2169 }
2170 }
2171
2172 if (Triple.getArchName() == "x86_64h") {
2173 // x86_64h implies quite a few of the more modern subtarget features
2174 // for Haswell class CPUs, but not all of them. Opt-out of a few.
2175 Features.push_back("-rdrnd");
2176 Features.push_back("-aes");
2177 Features.push_back("-pclmul");
2178 Features.push_back("-rtm");
2179 Features.push_back("-hle");
2180 Features.push_back("-fsgsbase");
2181 }
2182
2183 const llvm::Triple::ArchType ArchType = Triple.getArch();
2184 // Add features to be compatible with gcc for Android.
2185 if (Triple.isAndroid()) {
2186 if (ArchType == llvm::Triple::x86_64) {
2187 Features.push_back("+sse4.2");
2188 Features.push_back("+popcnt");
2189 } else
2190 Features.push_back("+ssse3");
2191 }
2192
2193 // Set features according to the -arch flag on MSVC.
2194 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
2195 StringRef Arch = A->getValue();
2196 bool ArchUsed = false;
2197 // First, look for flags that are shared in x86 and x86-64.
2198 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
2199 if (Arch == "AVX" || Arch == "AVX2") {
2200 ArchUsed = true;
2201 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2202 }
2203 }
2204 // Then, look for x86-specific flags.
2205 if (ArchType == llvm::Triple::x86) {
2206 if (Arch == "IA32") {
2207 ArchUsed = true;
2208 } else if (Arch == "SSE" || Arch == "SSE2") {
2209 ArchUsed = true;
2210 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2211 }
2212 }
2213 if (!ArchUsed)
2214 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2215 }
2216
2217 // Now add any that the user explicitly requested on the command line,
2218 // which may override the defaults.
2219 handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2220 }
2221
AddX86TargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2222 void Clang::AddX86TargetArgs(const ArgList &Args,
2223 ArgStringList &CmdArgs) const {
2224 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2225 Args.hasArg(options::OPT_mkernel) ||
2226 Args.hasArg(options::OPT_fapple_kext))
2227 CmdArgs.push_back("-disable-red-zone");
2228
2229 // Default to avoid implicit floating-point for kernel/kext code, but allow
2230 // that to be overridden with -mno-soft-float.
2231 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2232 Args.hasArg(options::OPT_fapple_kext));
2233 if (Arg *A = Args.getLastArg(
2234 options::OPT_msoft_float, options::OPT_mno_soft_float,
2235 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2236 const Option &O = A->getOption();
2237 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2238 O.matches(options::OPT_msoft_float));
2239 }
2240 if (NoImplicitFloat)
2241 CmdArgs.push_back("-no-implicit-float");
2242
2243 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2244 StringRef Value = A->getValue();
2245 if (Value == "intel" || Value == "att") {
2246 CmdArgs.push_back("-mllvm");
2247 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2248 } else {
2249 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2250 << A->getOption().getName() << Value;
2251 }
2252 }
2253
2254 // Set flags to support MCU ABI.
2255 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2256 CmdArgs.push_back("-mfloat-abi");
2257 CmdArgs.push_back("soft");
2258 CmdArgs.push_back("-mstack-alignment=4");
2259 }
2260 }
2261
AddHexagonTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2262 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2263 ArgStringList &CmdArgs) const {
2264 CmdArgs.push_back("-mqdsp6-compat");
2265 CmdArgs.push_back("-Wreturn-type");
2266
2267 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2268 std::string N = llvm::utostr(G.getValue());
2269 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2270 CmdArgs.push_back("-mllvm");
2271 CmdArgs.push_back(Args.MakeArgString(Opt));
2272 }
2273
2274 if (!Args.hasArg(options::OPT_fno_short_enums))
2275 CmdArgs.push_back("-fshort-enums");
2276 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2277 CmdArgs.push_back("-mllvm");
2278 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2279 }
2280 CmdArgs.push_back("-mllvm");
2281 CmdArgs.push_back("-machine-sink-split=0");
2282 }
2283
AddLanaiTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2284 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2285 ArgStringList &CmdArgs) const {
2286 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2287 StringRef CPUName = A->getValue();
2288
2289 CmdArgs.push_back("-target-cpu");
2290 CmdArgs.push_back(Args.MakeArgString(CPUName));
2291 }
2292 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2293 StringRef Value = A->getValue();
2294 // Only support mregparm=4 to support old usage. Report error for all other
2295 // cases.
2296 int Mregparm;
2297 if (Value.getAsInteger(10, Mregparm)) {
2298 if (Mregparm != 4) {
2299 getToolChain().getDriver().Diag(
2300 diag::err_drv_unsupported_option_argument)
2301 << A->getOption().getName() << Value;
2302 }
2303 }
2304 }
2305 }
2306
AddWebAssemblyTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const2307 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2308 ArgStringList &CmdArgs) const {
2309 // Default to "hidden" visibility.
2310 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2311 options::OPT_fvisibility_ms_compat)) {
2312 CmdArgs.push_back("-fvisibility");
2313 CmdArgs.push_back("hidden");
2314 }
2315 }
2316
2317 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
DecodeAArch64Features(const Driver & D,StringRef text,std::vector<const char * > & Features)2318 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2319 std::vector<const char *> &Features) {
2320 SmallVector<StringRef, 8> Split;
2321 text.split(Split, StringRef("+"), -1, false);
2322
2323 for (StringRef Feature : Split) {
2324 const char *result = llvm::StringSwitch<const char *>(Feature)
2325 .Case("fp", "+fp-armv8")
2326 .Case("simd", "+neon")
2327 .Case("crc", "+crc")
2328 .Case("crypto", "+crypto")
2329 .Case("fp16", "+fullfp16")
2330 .Case("profile", "+spe")
2331 .Case("ras", "+ras")
2332 .Case("nofp", "-fp-armv8")
2333 .Case("nosimd", "-neon")
2334 .Case("nocrc", "-crc")
2335 .Case("nocrypto", "-crypto")
2336 .Case("nofp16", "-fullfp16")
2337 .Case("noprofile", "-spe")
2338 .Case("noras", "-ras")
2339 .Default(nullptr);
2340 if (result)
2341 Features.push_back(result);
2342 else if (Feature == "neon" || Feature == "noneon")
2343 D.Diag(diag::err_drv_no_neon_modifier);
2344 else
2345 return false;
2346 }
2347 return true;
2348 }
2349
2350 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2351 // decode CPU and feature.
DecodeAArch64Mcpu(const Driver & D,StringRef Mcpu,StringRef & CPU,std::vector<const char * > & Features)2352 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2353 std::vector<const char *> &Features) {
2354 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2355 CPU = Split.first;
2356 if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
2357 CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
2358 CPU == "kryo" || CPU == "cortex-a73" || CPU == "vulcan") {
2359 Features.push_back("+neon");
2360 Features.push_back("+crc");
2361 Features.push_back("+crypto");
2362 } else if (CPU == "cyclone") {
2363 Features.push_back("+neon");
2364 Features.push_back("+crypto");
2365 } else if (CPU == "generic") {
2366 Features.push_back("+neon");
2367 } else {
2368 return false;
2369 }
2370
2371 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2372 return false;
2373
2374 return true;
2375 }
2376
2377 static bool
getAArch64ArchFeaturesFromMarch(const Driver & D,StringRef March,const ArgList & Args,std::vector<const char * > & Features)2378 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2379 const ArgList &Args,
2380 std::vector<const char *> &Features) {
2381 std::string MarchLowerCase = March.lower();
2382 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2383
2384 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2385 // ok, no additional features.
2386 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2387 Features.push_back("+v8.1a");
2388 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2389 Features.push_back("+v8.2a");
2390 } else {
2391 return false;
2392 }
2393
2394 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2395 return false;
2396
2397 return true;
2398 }
2399
2400 static bool
getAArch64ArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)2401 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2402 const ArgList &Args,
2403 std::vector<const char *> &Features) {
2404 StringRef CPU;
2405 std::string McpuLowerCase = Mcpu.lower();
2406 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2407 return false;
2408
2409 return true;
2410 }
2411
2412 static bool
getAArch64MicroArchFeaturesFromMtune(const Driver & D,StringRef Mtune,const ArgList & Args,std::vector<const char * > & Features)2413 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2414 const ArgList &Args,
2415 std::vector<const char *> &Features) {
2416 std::string MtuneLowerCase = Mtune.lower();
2417 // Handle CPU name is 'native'.
2418 if (MtuneLowerCase == "native")
2419 MtuneLowerCase = llvm::sys::getHostCPUName();
2420 if (MtuneLowerCase == "cyclone") {
2421 Features.push_back("+zcm");
2422 Features.push_back("+zcz");
2423 }
2424 return true;
2425 }
2426
2427 static bool
getAArch64MicroArchFeaturesFromMcpu(const Driver & D,StringRef Mcpu,const ArgList & Args,std::vector<const char * > & Features)2428 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2429 const ArgList &Args,
2430 std::vector<const char *> &Features) {
2431 StringRef CPU;
2432 std::vector<const char *> DecodedFeature;
2433 std::string McpuLowerCase = Mcpu.lower();
2434 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2435 return false;
2436
2437 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2438 }
2439
getAArch64TargetFeatures(const Driver & D,const ArgList & Args,std::vector<const char * > & Features)2440 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2441 std::vector<const char *> &Features) {
2442 Arg *A;
2443 bool success = true;
2444 // Enable NEON by default.
2445 Features.push_back("+neon");
2446 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2447 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2448 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2449 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2450 else if (Args.hasArg(options::OPT_arch))
2451 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2452 Features);
2453
2454 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2455 success =
2456 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2457 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2458 success =
2459 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2460 else if (Args.hasArg(options::OPT_arch))
2461 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2462 Args, Features);
2463
2464 if (!success)
2465 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2466
2467 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2468 Features.push_back("-fp-armv8");
2469 Features.push_back("-crypto");
2470 Features.push_back("-neon");
2471 }
2472
2473 // En/disable crc
2474 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2475 if (A->getOption().matches(options::OPT_mcrc))
2476 Features.push_back("+crc");
2477 else
2478 Features.push_back("-crc");
2479 }
2480
2481 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2482 options::OPT_munaligned_access))
2483 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2484 Features.push_back("+strict-align");
2485
2486 if (Args.hasArg(options::OPT_ffixed_x18))
2487 Features.push_back("+reserve-x18");
2488 }
2489
getHexagonTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)2490 static void getHexagonTargetFeatures(const ArgList &Args,
2491 std::vector<const char *> &Features) {
2492 bool HasHVX = false, HasHVXD = false;
2493
2494 // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2495 // doing dependent option handling here rather than in initFeatureMap or a
2496 // similar handler.
2497 for (auto &A : Args) {
2498 auto &Opt = A->getOption();
2499 if (Opt.matches(options::OPT_mhexagon_hvx))
2500 HasHVX = true;
2501 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2502 HasHVXD = HasHVX = false;
2503 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2504 HasHVXD = HasHVX = true;
2505 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2506 HasHVXD = false;
2507 else
2508 continue;
2509 A->claim();
2510 }
2511
2512 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2513 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2514 }
2515
getWebAssemblyTargetFeatures(const ArgList & Args,std::vector<const char * > & Features)2516 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2517 std::vector<const char *> &Features) {
2518 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2519 }
2520
getAMDGPUTargetFeatures(const Driver & D,const ArgList & Args,std::vector<const char * > & Features)2521 static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
2522 std::vector<const char *> &Features) {
2523 if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
2524 StringRef value = dAbi->getValue();
2525 if (value == "1.0") {
2526 Features.push_back("+amdgpu-debugger-insert-nops");
2527 Features.push_back("+amdgpu-debugger-reserve-regs");
2528 Features.push_back("+amdgpu-debugger-emit-prologue");
2529 } else {
2530 D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
2531 }
2532 }
2533
2534 handleTargetFeaturesGroup(
2535 Args, Features, options::OPT_m_amdgpu_Features_Group);
2536 }
2537
getTargetFeatures(const ToolChain & TC,const llvm::Triple & Triple,const ArgList & Args,ArgStringList & CmdArgs,bool ForAS)2538 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2539 const ArgList &Args, ArgStringList &CmdArgs,
2540 bool ForAS) {
2541 const Driver &D = TC.getDriver();
2542 std::vector<const char *> Features;
2543 switch (Triple.getArch()) {
2544 default:
2545 break;
2546 case llvm::Triple::mips:
2547 case llvm::Triple::mipsel:
2548 case llvm::Triple::mips64:
2549 case llvm::Triple::mips64el:
2550 getMIPSTargetFeatures(D, Triple, Args, Features);
2551 break;
2552
2553 case llvm::Triple::arm:
2554 case llvm::Triple::armeb:
2555 case llvm::Triple::thumb:
2556 case llvm::Triple::thumbeb:
2557 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2558 break;
2559
2560 case llvm::Triple::ppc:
2561 case llvm::Triple::ppc64:
2562 case llvm::Triple::ppc64le:
2563 getPPCTargetFeatures(D, Triple, Args, Features);
2564 break;
2565 case llvm::Triple::systemz:
2566 getSystemZTargetFeatures(Args, Features);
2567 break;
2568 case llvm::Triple::aarch64:
2569 case llvm::Triple::aarch64_be:
2570 getAArch64TargetFeatures(D, Args, Features);
2571 break;
2572 case llvm::Triple::x86:
2573 case llvm::Triple::x86_64:
2574 getX86TargetFeatures(D, Triple, Args, Features);
2575 break;
2576 case llvm::Triple::hexagon:
2577 getHexagonTargetFeatures(Args, Features);
2578 break;
2579 case llvm::Triple::wasm32:
2580 case llvm::Triple::wasm64:
2581 getWebAssemblyTargetFeatures(Args, Features);
2582 break;
2583 case llvm::Triple::sparc:
2584 case llvm::Triple::sparcel:
2585 case llvm::Triple::sparcv9:
2586 getSparcTargetFeatures(D, Args, Features);
2587 break;
2588 case llvm::Triple::r600:
2589 case llvm::Triple::amdgcn:
2590 getAMDGPUTargetFeatures(D, Args, Features);
2591 break;
2592 }
2593
2594 // Find the last of each feature.
2595 llvm::StringMap<unsigned> LastOpt;
2596 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2597 const char *Name = Features[I];
2598 assert(Name[0] == '-' || Name[0] == '+');
2599 LastOpt[Name + 1] = I;
2600 }
2601
2602 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2603 // If this feature was overridden, ignore it.
2604 const char *Name = Features[I];
2605 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2606 assert(LastI != LastOpt.end());
2607 unsigned Last = LastI->second;
2608 if (Last != I)
2609 continue;
2610
2611 CmdArgs.push_back("-target-feature");
2612 CmdArgs.push_back(Name);
2613 }
2614 }
2615
2616 static bool
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime & runtime,const llvm::Triple & Triple)2617 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2618 const llvm::Triple &Triple) {
2619 // We use the zero-cost exception tables for Objective-C if the non-fragile
2620 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2621 // later.
2622 if (runtime.isNonFragile())
2623 return true;
2624
2625 if (!Triple.isMacOSX())
2626 return false;
2627
2628 return (!Triple.isMacOSXVersionLT(10, 5) &&
2629 (Triple.getArch() == llvm::Triple::x86_64 ||
2630 Triple.getArch() == llvm::Triple::arm));
2631 }
2632
2633 /// Adds exception related arguments to the driver command arguments. There's a
2634 /// master flag, -fexceptions and also language specific flags to enable/disable
2635 /// C++ and Objective-C exceptions. This makes it possible to for example
2636 /// disable C++ exceptions but enable Objective-C exceptions.
addExceptionArgs(const ArgList & Args,types::ID InputType,const ToolChain & TC,bool KernelOrKext,const ObjCRuntime & objcRuntime,ArgStringList & CmdArgs)2637 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2638 const ToolChain &TC, bool KernelOrKext,
2639 const ObjCRuntime &objcRuntime,
2640 ArgStringList &CmdArgs) {
2641 const Driver &D = TC.getDriver();
2642 const llvm::Triple &Triple = TC.getTriple();
2643
2644 if (KernelOrKext) {
2645 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2646 // arguments now to avoid warnings about unused arguments.
2647 Args.ClaimAllArgs(options::OPT_fexceptions);
2648 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2649 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2650 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2651 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2652 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2653 return;
2654 }
2655
2656 // See if the user explicitly enabled exceptions.
2657 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2658 false);
2659
2660 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2661 // is not necessarily sensible, but follows GCC.
2662 if (types::isObjC(InputType) &&
2663 Args.hasFlag(options::OPT_fobjc_exceptions,
2664 options::OPT_fno_objc_exceptions, true)) {
2665 CmdArgs.push_back("-fobjc-exceptions");
2666
2667 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2668 }
2669
2670 if (types::isCXX(InputType)) {
2671 // Disable C++ EH by default on XCore and PS4.
2672 bool CXXExceptionsEnabled =
2673 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
2674 Arg *ExceptionArg = Args.getLastArg(
2675 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2676 options::OPT_fexceptions, options::OPT_fno_exceptions);
2677 if (ExceptionArg)
2678 CXXExceptionsEnabled =
2679 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2680 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2681
2682 if (CXXExceptionsEnabled) {
2683 if (Triple.isPS4CPU()) {
2684 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2685 assert(ExceptionArg &&
2686 "On the PS4 exceptions should only be enabled if passing "
2687 "an argument");
2688 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2689 const Arg *RTTIArg = TC.getRTTIArg();
2690 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2691 D.Diag(diag::err_drv_argument_not_allowed_with)
2692 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2693 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2694 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2695 } else
2696 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2697
2698 CmdArgs.push_back("-fcxx-exceptions");
2699
2700 EH = true;
2701 }
2702 }
2703
2704 if (EH)
2705 CmdArgs.push_back("-fexceptions");
2706 }
2707
ShouldDisableAutolink(const ArgList & Args,const ToolChain & TC)2708 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2709 bool Default = true;
2710 if (TC.getTriple().isOSDarwin()) {
2711 // The native darwin assembler doesn't support the linker_option directives,
2712 // so we disable them if we think the .s file will be passed to it.
2713 Default = TC.useIntegratedAs();
2714 }
2715 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2716 Default);
2717 }
2718
ShouldDisableDwarfDirectory(const ArgList & Args,const ToolChain & TC)2719 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2720 const ToolChain &TC) {
2721 bool UseDwarfDirectory =
2722 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2723 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2724 return !UseDwarfDirectory;
2725 }
2726
2727 /// \brief Check whether the given input tree contains any compilation actions.
ContainsCompileAction(const Action * A)2728 static bool ContainsCompileAction(const Action *A) {
2729 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2730 return true;
2731
2732 for (const auto &AI : A->inputs())
2733 if (ContainsCompileAction(AI))
2734 return true;
2735
2736 return false;
2737 }
2738
2739 /// \brief Check if -relax-all should be passed to the internal assembler.
2740 /// This is done by default when compiling non-assembler source with -O0.
UseRelaxAll(Compilation & C,const ArgList & Args)2741 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2742 bool RelaxDefault = true;
2743
2744 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2745 RelaxDefault = A->getOption().matches(options::OPT_O0);
2746
2747 if (RelaxDefault) {
2748 RelaxDefault = false;
2749 for (const auto &Act : C.getActions()) {
2750 if (ContainsCompileAction(Act)) {
2751 RelaxDefault = true;
2752 break;
2753 }
2754 }
2755 }
2756
2757 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2758 RelaxDefault);
2759 }
2760
2761 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2762 // to the corresponding DebugInfoKind.
DebugLevelToInfoKind(const Arg & A)2763 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2764 assert(A.getOption().matches(options::OPT_gN_Group) &&
2765 "Not a -g option that specifies a debug-info level");
2766 if (A.getOption().matches(options::OPT_g0) ||
2767 A.getOption().matches(options::OPT_ggdb0))
2768 return codegenoptions::NoDebugInfo;
2769 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2770 A.getOption().matches(options::OPT_ggdb1))
2771 return codegenoptions::DebugLineTablesOnly;
2772 return codegenoptions::LimitedDebugInfo;
2773 }
2774
2775 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2776 // on mismatch. The StringRef input (rather than an Arg) allows
2777 // for use by the "-Xassembler" option parser.
DwarfVersionNum(StringRef ArgValue)2778 static unsigned DwarfVersionNum(StringRef ArgValue) {
2779 return llvm::StringSwitch<unsigned>(ArgValue)
2780 .Case("-gdwarf-2", 2)
2781 .Case("-gdwarf-3", 3)
2782 .Case("-gdwarf-4", 4)
2783 .Case("-gdwarf-5", 5)
2784 .Default(0);
2785 }
2786
RenderDebugEnablingArgs(const ArgList & Args,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind DebugInfoKind,unsigned DwarfVersion,llvm::DebuggerKind DebuggerTuning)2787 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2788 codegenoptions::DebugInfoKind DebugInfoKind,
2789 unsigned DwarfVersion,
2790 llvm::DebuggerKind DebuggerTuning) {
2791 switch (DebugInfoKind) {
2792 case codegenoptions::DebugLineTablesOnly:
2793 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2794 break;
2795 case codegenoptions::LimitedDebugInfo:
2796 CmdArgs.push_back("-debug-info-kind=limited");
2797 break;
2798 case codegenoptions::FullDebugInfo:
2799 CmdArgs.push_back("-debug-info-kind=standalone");
2800 break;
2801 default:
2802 break;
2803 }
2804 if (DwarfVersion > 0)
2805 CmdArgs.push_back(
2806 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2807 switch (DebuggerTuning) {
2808 case llvm::DebuggerKind::GDB:
2809 CmdArgs.push_back("-debugger-tuning=gdb");
2810 break;
2811 case llvm::DebuggerKind::LLDB:
2812 CmdArgs.push_back("-debugger-tuning=lldb");
2813 break;
2814 case llvm::DebuggerKind::SCE:
2815 CmdArgs.push_back("-debugger-tuning=sce");
2816 break;
2817 default:
2818 break;
2819 }
2820 }
2821
CollectArgsForIntegratedAssembler(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const Driver & D)2822 static void CollectArgsForIntegratedAssembler(Compilation &C,
2823 const ArgList &Args,
2824 ArgStringList &CmdArgs,
2825 const Driver &D) {
2826 if (UseRelaxAll(C, Args))
2827 CmdArgs.push_back("-mrelax-all");
2828
2829 // Only default to -mincremental-linker-compatible if we think we are
2830 // targeting the MSVC linker.
2831 bool DefaultIncrementalLinkerCompatible =
2832 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2833 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2834 options::OPT_mno_incremental_linker_compatible,
2835 DefaultIncrementalLinkerCompatible))
2836 CmdArgs.push_back("-mincremental-linker-compatible");
2837
2838 // When passing -I arguments to the assembler we sometimes need to
2839 // unconditionally take the next argument. For example, when parsing
2840 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2841 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2842 // arg after parsing the '-I' arg.
2843 bool TakeNextArg = false;
2844
2845 // When using an integrated assembler, translate -Wa, and -Xassembler
2846 // options.
2847 bool CompressDebugSections = false;
2848
2849 bool UseRelaxRelocations = ENABLE_X86_RELAX_RELOCATIONS;
2850 const char *MipsTargetFeature = nullptr;
2851 for (const Arg *A :
2852 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2853 A->claim();
2854
2855 for (StringRef Value : A->getValues()) {
2856 if (TakeNextArg) {
2857 CmdArgs.push_back(Value.data());
2858 TakeNextArg = false;
2859 continue;
2860 }
2861
2862 switch (C.getDefaultToolChain().getArch()) {
2863 default:
2864 break;
2865 case llvm::Triple::mips:
2866 case llvm::Triple::mipsel:
2867 case llvm::Triple::mips64:
2868 case llvm::Triple::mips64el:
2869 if (Value == "--trap") {
2870 CmdArgs.push_back("-target-feature");
2871 CmdArgs.push_back("+use-tcc-in-div");
2872 continue;
2873 }
2874 if (Value == "--break") {
2875 CmdArgs.push_back("-target-feature");
2876 CmdArgs.push_back("-use-tcc-in-div");
2877 continue;
2878 }
2879 if (Value.startswith("-msoft-float")) {
2880 CmdArgs.push_back("-target-feature");
2881 CmdArgs.push_back("+soft-float");
2882 continue;
2883 }
2884 if (Value.startswith("-mhard-float")) {
2885 CmdArgs.push_back("-target-feature");
2886 CmdArgs.push_back("-soft-float");
2887 continue;
2888 }
2889
2890 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2891 .Case("-mips1", "+mips1")
2892 .Case("-mips2", "+mips2")
2893 .Case("-mips3", "+mips3")
2894 .Case("-mips4", "+mips4")
2895 .Case("-mips5", "+mips5")
2896 .Case("-mips32", "+mips32")
2897 .Case("-mips32r2", "+mips32r2")
2898 .Case("-mips32r3", "+mips32r3")
2899 .Case("-mips32r5", "+mips32r5")
2900 .Case("-mips32r6", "+mips32r6")
2901 .Case("-mips64", "+mips64")
2902 .Case("-mips64r2", "+mips64r2")
2903 .Case("-mips64r3", "+mips64r3")
2904 .Case("-mips64r5", "+mips64r5")
2905 .Case("-mips64r6", "+mips64r6")
2906 .Default(nullptr);
2907 if (MipsTargetFeature)
2908 continue;
2909 }
2910
2911 if (Value == "-force_cpusubtype_ALL") {
2912 // Do nothing, this is the default and we don't support anything else.
2913 } else if (Value == "-L") {
2914 CmdArgs.push_back("-msave-temp-labels");
2915 } else if (Value == "--fatal-warnings") {
2916 CmdArgs.push_back("-massembler-fatal-warnings");
2917 } else if (Value == "--noexecstack") {
2918 CmdArgs.push_back("-mnoexecstack");
2919 } else if (Value == "-compress-debug-sections" ||
2920 Value == "--compress-debug-sections") {
2921 CompressDebugSections = true;
2922 } else if (Value == "-nocompress-debug-sections" ||
2923 Value == "--nocompress-debug-sections") {
2924 CompressDebugSections = false;
2925 } else if (Value == "-mrelax-relocations=yes" ||
2926 Value == "--mrelax-relocations=yes") {
2927 UseRelaxRelocations = true;
2928 } else if (Value == "-mrelax-relocations=no" ||
2929 Value == "--mrelax-relocations=no") {
2930 UseRelaxRelocations = false;
2931 } else if (Value.startswith("-I")) {
2932 CmdArgs.push_back(Value.data());
2933 // We need to consume the next argument if the current arg is a plain
2934 // -I. The next arg will be the include directory.
2935 if (Value == "-I")
2936 TakeNextArg = true;
2937 } else if (Value.startswith("-gdwarf-")) {
2938 // "-gdwarf-N" options are not cc1as options.
2939 unsigned DwarfVersion = DwarfVersionNum(Value);
2940 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2941 CmdArgs.push_back(Value.data());
2942 } else {
2943 RenderDebugEnablingArgs(Args, CmdArgs,
2944 codegenoptions::LimitedDebugInfo,
2945 DwarfVersion, llvm::DebuggerKind::Default);
2946 }
2947 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2948 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2949 // Do nothing, we'll validate it later.
2950 } else {
2951 D.Diag(diag::err_drv_unsupported_option_argument)
2952 << A->getOption().getName() << Value;
2953 }
2954 }
2955 }
2956 if (CompressDebugSections) {
2957 if (llvm::zlib::isAvailable())
2958 CmdArgs.push_back("-compress-debug-sections");
2959 else
2960 D.Diag(diag::warn_debug_compression_unavailable);
2961 }
2962 if (UseRelaxRelocations)
2963 CmdArgs.push_back("--mrelax-relocations");
2964 if (MipsTargetFeature != nullptr) {
2965 CmdArgs.push_back("-target-feature");
2966 CmdArgs.push_back(MipsTargetFeature);
2967 }
2968 }
2969
2970 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2971 // FIXME: Make sure we can also emit shared objects if they're requested
2972 // and available, check for possible errors, etc.
addClangRT(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)2973 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2974 ArgStringList &CmdArgs) {
2975 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2976 }
2977
2978 namespace {
2979 enum OpenMPRuntimeKind {
2980 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2981 /// without knowing what runtime to target.
2982 OMPRT_Unknown,
2983
2984 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2985 /// the default for Clang.
2986 OMPRT_OMP,
2987
2988 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2989 /// this runtime but can swallow the pragmas, and find and link against the
2990 /// runtime library itself.
2991 OMPRT_GOMP,
2992
2993 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2994 /// OpenMP runtime. We support this mode for users with existing dependencies
2995 /// on this runtime library name.
2996 OMPRT_IOMP5
2997 };
2998 }
2999
3000 /// Compute the desired OpenMP runtime from the flag provided.
getOpenMPRuntime(const ToolChain & TC,const ArgList & Args)3001 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
3002 const ArgList &Args) {
3003 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
3004
3005 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
3006 if (A)
3007 RuntimeName = A->getValue();
3008
3009 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
3010 .Case("libomp", OMPRT_OMP)
3011 .Case("libgomp", OMPRT_GOMP)
3012 .Case("libiomp5", OMPRT_IOMP5)
3013 .Default(OMPRT_Unknown);
3014
3015 if (RT == OMPRT_Unknown) {
3016 if (A)
3017 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
3018 << A->getOption().getName() << A->getValue();
3019 else
3020 // FIXME: We could use a nicer diagnostic here.
3021 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
3022 }
3023
3024 return RT;
3025 }
3026
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args)3027 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
3028 const ArgList &Args) {
3029 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
3030 options::OPT_fno_openmp, false))
3031 return;
3032
3033 switch (getOpenMPRuntime(TC, Args)) {
3034 case OMPRT_OMP:
3035 CmdArgs.push_back("-lomp");
3036 break;
3037 case OMPRT_GOMP:
3038 CmdArgs.push_back("-lgomp");
3039 break;
3040 case OMPRT_IOMP5:
3041 CmdArgs.push_back("-liomp5");
3042 break;
3043 case OMPRT_Unknown:
3044 // Already diagnosed.
3045 break;
3046 }
3047 }
3048
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)3049 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
3050 ArgStringList &CmdArgs, StringRef Sanitizer,
3051 bool IsShared, bool IsWhole) {
3052 // Wrap any static runtimes that must be forced into executable in
3053 // whole-archive.
3054 if (IsWhole) CmdArgs.push_back("-whole-archive");
3055 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
3056 if (IsWhole) CmdArgs.push_back("-no-whole-archive");
3057 }
3058
3059 // Tries to use a file with the list of dynamic symbols that need to be exported
3060 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)3061 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
3062 ArgStringList &CmdArgs,
3063 StringRef Sanitizer) {
3064 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
3065 if (llvm::sys::fs::exists(SanRT + ".syms")) {
3066 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
3067 return true;
3068 }
3069 return false;
3070 }
3071
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)3072 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
3073 ArgStringList &CmdArgs) {
3074 // Force linking against the system libraries sanitizers depends on
3075 // (see PR15823 why this is necessary).
3076 CmdArgs.push_back("--no-as-needed");
3077 CmdArgs.push_back("-lpthread");
3078 CmdArgs.push_back("-lrt");
3079 CmdArgs.push_back("-lm");
3080 // There's no libdl on FreeBSD.
3081 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3082 CmdArgs.push_back("-ldl");
3083 }
3084
3085 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)3086 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3087 SmallVectorImpl<StringRef> &SharedRuntimes,
3088 SmallVectorImpl<StringRef> &StaticRuntimes,
3089 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
3090 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
3091 SmallVectorImpl<StringRef> &RequiredSymbols) {
3092 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
3093 // Collect shared runtimes.
3094 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
3095 SharedRuntimes.push_back("asan");
3096 }
3097 // The stats_client library is also statically linked into DSOs.
3098 if (SanArgs.needsStatsRt())
3099 StaticRuntimes.push_back("stats_client");
3100
3101 // Collect static runtimes.
3102 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
3103 // Don't link static runtimes into DSOs or if compiling for Android.
3104 return;
3105 }
3106 if (SanArgs.needsAsanRt()) {
3107 if (SanArgs.needsSharedAsanRt()) {
3108 HelperStaticRuntimes.push_back("asan-preinit");
3109 } else {
3110 StaticRuntimes.push_back("asan");
3111 if (SanArgs.linkCXXRuntimes())
3112 StaticRuntimes.push_back("asan_cxx");
3113 }
3114 }
3115 if (SanArgs.needsDfsanRt())
3116 StaticRuntimes.push_back("dfsan");
3117 if (SanArgs.needsLsanRt())
3118 StaticRuntimes.push_back("lsan");
3119 if (SanArgs.needsMsanRt()) {
3120 StaticRuntimes.push_back("msan");
3121 if (SanArgs.linkCXXRuntimes())
3122 StaticRuntimes.push_back("msan_cxx");
3123 }
3124 if (SanArgs.needsTsanRt()) {
3125 StaticRuntimes.push_back("tsan");
3126 if (SanArgs.linkCXXRuntimes())
3127 StaticRuntimes.push_back("tsan_cxx");
3128 }
3129 if (SanArgs.needsUbsanRt()) {
3130 StaticRuntimes.push_back("ubsan_standalone");
3131 if (SanArgs.linkCXXRuntimes())
3132 StaticRuntimes.push_back("ubsan_standalone_cxx");
3133 }
3134 if (SanArgs.needsSafeStackRt())
3135 StaticRuntimes.push_back("safestack");
3136 if (SanArgs.needsCfiRt())
3137 StaticRuntimes.push_back("cfi");
3138 if (SanArgs.needsCfiDiagRt()) {
3139 StaticRuntimes.push_back("cfi_diag");
3140 if (SanArgs.linkCXXRuntimes())
3141 StaticRuntimes.push_back("ubsan_standalone_cxx");
3142 }
3143 if (SanArgs.needsStatsRt()) {
3144 NonWholeStaticRuntimes.push_back("stats");
3145 RequiredSymbols.push_back("__sanitizer_stats_register");
3146 }
3147 if (SanArgs.needsEsanRt())
3148 StaticRuntimes.push_back("esan");
3149 }
3150
3151 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
3152 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3153 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
3154 ArgStringList &CmdArgs) {
3155 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
3156 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
3157 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
3158 NonWholeStaticRuntimes, HelperStaticRuntimes,
3159 RequiredSymbols);
3160 for (auto RT : SharedRuntimes)
3161 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
3162 for (auto RT : HelperStaticRuntimes)
3163 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3164 bool AddExportDynamic = false;
3165 for (auto RT : StaticRuntimes) {
3166 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
3167 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3168 }
3169 for (auto RT : NonWholeStaticRuntimes) {
3170 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
3171 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
3172 }
3173 for (auto S : RequiredSymbols) {
3174 CmdArgs.push_back("-u");
3175 CmdArgs.push_back(Args.MakeArgString(S));
3176 }
3177 // If there is a static runtime with no dynamic list, force all the symbols
3178 // to be dynamic to be sure we export sanitizer interface functions.
3179 if (AddExportDynamic)
3180 CmdArgs.push_back("-export-dynamic");
3181 return !StaticRuntimes.empty();
3182 }
3183
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3184 static bool addXRayRuntime(const ToolChain &TC, const ArgList &Args,
3185 ArgStringList &CmdArgs) {
3186 if (Args.hasFlag(options::OPT_fxray_instrument,
3187 options::OPT_fnoxray_instrument, false)) {
3188 CmdArgs.push_back("-whole-archive");
3189 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray", false));
3190 CmdArgs.push_back("-no-whole-archive");
3191 return true;
3192 }
3193 return false;
3194 }
3195
linkXRayRuntimeDeps(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3196 static void linkXRayRuntimeDeps(const ToolChain &TC, const ArgList &Args,
3197 ArgStringList &CmdArgs) {
3198 CmdArgs.push_back("--no-as-needed");
3199 CmdArgs.push_back("-lpthread");
3200 CmdArgs.push_back("-lrt");
3201 CmdArgs.push_back("-lm");
3202 CmdArgs.push_back("-latomic");
3203 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3204 CmdArgs.push_back("-lc++");
3205 else
3206 CmdArgs.push_back("-lstdc++");
3207 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
3208 CmdArgs.push_back("-ldl");
3209 }
3210
areOptimizationsEnabled(const ArgList & Args)3211 static bool areOptimizationsEnabled(const ArgList &Args) {
3212 // Find the last -O arg and see if it is non-zero.
3213 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
3214 return !A->getOption().matches(options::OPT_O0);
3215 // Defaults to -O0.
3216 return false;
3217 }
3218
shouldUseFramePointerForTarget(const ArgList & Args,const llvm::Triple & Triple)3219 static bool shouldUseFramePointerForTarget(const ArgList &Args,
3220 const llvm::Triple &Triple) {
3221 switch (Triple.getArch()) {
3222 case llvm::Triple::xcore:
3223 case llvm::Triple::wasm32:
3224 case llvm::Triple::wasm64:
3225 // XCore never wants frame pointers, regardless of OS.
3226 // WebAssembly never wants frame pointers.
3227 return false;
3228 default:
3229 break;
3230 }
3231
3232 if (Triple.isOSLinux()) {
3233 switch (Triple.getArch()) {
3234 // Don't use a frame pointer on linux if optimizing for certain targets.
3235 case llvm::Triple::mips64:
3236 case llvm::Triple::mips64el:
3237 case llvm::Triple::mips:
3238 case llvm::Triple::mipsel:
3239 case llvm::Triple::systemz:
3240 case llvm::Triple::x86:
3241 case llvm::Triple::x86_64:
3242 return !areOptimizationsEnabled(Args);
3243 default:
3244 return true;
3245 }
3246 }
3247
3248 if (Triple.isOSWindows()) {
3249 switch (Triple.getArch()) {
3250 case llvm::Triple::x86:
3251 return !areOptimizationsEnabled(Args);
3252 case llvm::Triple::x86_64:
3253 return Triple.isOSBinFormatMachO();
3254 case llvm::Triple::arm:
3255 case llvm::Triple::thumb:
3256 // Windows on ARM builds with FPO disabled to aid fast stack walking
3257 return true;
3258 default:
3259 // All other supported Windows ISAs use xdata unwind information, so frame
3260 // pointers are not generally useful.
3261 return false;
3262 }
3263 }
3264
3265 return true;
3266 }
3267
shouldUseFramePointer(const ArgList & Args,const llvm::Triple & Triple)3268 static bool shouldUseFramePointer(const ArgList &Args,
3269 const llvm::Triple &Triple) {
3270 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
3271 options::OPT_fomit_frame_pointer))
3272 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
3273 if (Args.hasArg(options::OPT_pg))
3274 return true;
3275
3276 return shouldUseFramePointerForTarget(Args, Triple);
3277 }
3278
shouldUseLeafFramePointer(const ArgList & Args,const llvm::Triple & Triple)3279 static bool shouldUseLeafFramePointer(const ArgList &Args,
3280 const llvm::Triple &Triple) {
3281 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
3282 options::OPT_momit_leaf_frame_pointer))
3283 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
3284 if (Args.hasArg(options::OPT_pg))
3285 return true;
3286
3287 if (Triple.isPS4CPU())
3288 return false;
3289
3290 return shouldUseFramePointerForTarget(Args, Triple);
3291 }
3292
3293 /// Add a CC1 option to specify the debug compilation directory.
addDebugCompDirArg(const ArgList & Args,ArgStringList & CmdArgs)3294 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
3295 SmallString<128> cwd;
3296 if (!llvm::sys::fs::current_path(cwd)) {
3297 CmdArgs.push_back("-fdebug-compilation-dir");
3298 CmdArgs.push_back(Args.MakeArgString(cwd));
3299 }
3300 }
3301
SplitDebugName(const ArgList & Args,const InputInfo & Input)3302 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
3303 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
3304 if (FinalOutput && Args.hasArg(options::OPT_c)) {
3305 SmallString<128> T(FinalOutput->getValue());
3306 llvm::sys::path::replace_extension(T, "dwo");
3307 return Args.MakeArgString(T);
3308 } else {
3309 // Use the compilation dir.
3310 SmallString<128> T(
3311 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
3312 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
3313 llvm::sys::path::replace_extension(F, "dwo");
3314 T += F;
3315 return Args.MakeArgString(F);
3316 }
3317 }
3318
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)3319 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
3320 const JobAction &JA, const ArgList &Args,
3321 const InputInfo &Output, const char *OutFile) {
3322 ArgStringList ExtractArgs;
3323 ExtractArgs.push_back("--extract-dwo");
3324
3325 ArgStringList StripArgs;
3326 StripArgs.push_back("--strip-dwo");
3327
3328 // Grabbing the output of the earlier compile step.
3329 StripArgs.push_back(Output.getFilename());
3330 ExtractArgs.push_back(Output.getFilename());
3331 ExtractArgs.push_back(OutFile);
3332
3333 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
3334 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
3335
3336 // First extract the dwo sections.
3337 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
3338
3339 // Then remove them from the original .o file.
3340 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
3341 }
3342
3343 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
3344 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
shouldEnableVectorizerAtOLevel(const ArgList & Args,bool isSlpVec)3345 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3346 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3347 if (A->getOption().matches(options::OPT_O4) ||
3348 A->getOption().matches(options::OPT_Ofast))
3349 return true;
3350
3351 if (A->getOption().matches(options::OPT_O0))
3352 return false;
3353
3354 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3355
3356 // Vectorize -Os.
3357 StringRef S(A->getValue());
3358 if (S == "s")
3359 return true;
3360
3361 // Don't vectorize -Oz, unless it's the slp vectorizer.
3362 if (S == "z")
3363 return isSlpVec;
3364
3365 unsigned OptLevel = 0;
3366 if (S.getAsInteger(10, OptLevel))
3367 return false;
3368
3369 return OptLevel > 1;
3370 }
3371
3372 return false;
3373 }
3374
3375 /// Add -x lang to \p CmdArgs for \p Input.
addDashXForInput(const ArgList & Args,const InputInfo & Input,ArgStringList & CmdArgs)3376 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3377 ArgStringList &CmdArgs) {
3378 // When using -verify-pch, we don't want to provide the type
3379 // 'precompiled-header' if it was inferred from the file extension
3380 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3381 return;
3382
3383 CmdArgs.push_back("-x");
3384 if (Args.hasArg(options::OPT_rewrite_objc))
3385 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3386 else
3387 CmdArgs.push_back(types::getTypeName(Input.getType()));
3388 }
3389
getMSCompatibilityVersion(unsigned Version)3390 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3391 if (Version < 100)
3392 return VersionTuple(Version);
3393
3394 if (Version < 10000)
3395 return VersionTuple(Version / 100, Version % 100);
3396
3397 unsigned Build = 0, Factor = 1;
3398 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3399 Build = Build + (Version % 10) * Factor;
3400 return VersionTuple(Version / 100, Version % 100, Build);
3401 }
3402
3403 // Claim options we don't want to warn if they are unused. We do this for
3404 // options that build systems might add but are unused when assembling or only
3405 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)3406 static void claimNoWarnArgs(const ArgList &Args) {
3407 // Don't warn about unused -f(no-)?lto. This can happen when we're
3408 // preprocessing, precompiling or assembling.
3409 Args.ClaimAllArgs(options::OPT_flto_EQ);
3410 Args.ClaimAllArgs(options::OPT_flto);
3411 Args.ClaimAllArgs(options::OPT_fno_lto);
3412 }
3413
appendUserToPath(SmallVectorImpl<char> & Result)3414 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3415 #ifdef LLVM_ON_UNIX
3416 const char *Username = getenv("LOGNAME");
3417 #else
3418 const char *Username = getenv("USERNAME");
3419 #endif
3420 if (Username) {
3421 // Validate that LoginName can be used in a path, and get its length.
3422 size_t Len = 0;
3423 for (const char *P = Username; *P; ++P, ++Len) {
3424 if (!isAlphanumeric(*P) && *P != '_') {
3425 Username = nullptr;
3426 break;
3427 }
3428 }
3429
3430 if (Username && Len > 0) {
3431 Result.append(Username, Username + Len);
3432 return;
3433 }
3434 }
3435
3436 // Fallback to user id.
3437 #ifdef LLVM_ON_UNIX
3438 std::string UID = llvm::utostr(getuid());
3439 #else
3440 // FIXME: Windows seems to have an 'SID' that might work.
3441 std::string UID = "9999";
3442 #endif
3443 Result.append(UID.begin(), UID.end());
3444 }
3445
getMSVCVersion(const Driver * D,const ToolChain & TC,const llvm::Triple & Triple,const llvm::opt::ArgList & Args,bool IsWindowsMSVC)3446 VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
3447 const llvm::Triple &Triple,
3448 const llvm::opt::ArgList &Args,
3449 bool IsWindowsMSVC) {
3450 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3451 IsWindowsMSVC) ||
3452 Args.hasArg(options::OPT_fmsc_version) ||
3453 Args.hasArg(options::OPT_fms_compatibility_version)) {
3454 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3455 const Arg *MSCompatibilityVersion =
3456 Args.getLastArg(options::OPT_fms_compatibility_version);
3457
3458 if (MSCVersion && MSCompatibilityVersion) {
3459 if (D)
3460 D->Diag(diag::err_drv_argument_not_allowed_with)
3461 << MSCVersion->getAsString(Args)
3462 << MSCompatibilityVersion->getAsString(Args);
3463 return VersionTuple();
3464 }
3465
3466 if (MSCompatibilityVersion) {
3467 VersionTuple MSVT;
3468 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3469 D->Diag(diag::err_drv_invalid_value)
3470 << MSCompatibilityVersion->getAsString(Args)
3471 << MSCompatibilityVersion->getValue();
3472 return MSVT;
3473 }
3474
3475 if (MSCVersion) {
3476 unsigned Version = 0;
3477 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3478 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3479 << MSCVersion->getValue();
3480 return getMSCompatibilityVersion(Version);
3481 }
3482
3483 unsigned Major, Minor, Micro;
3484 Triple.getEnvironmentVersion(Major, Minor, Micro);
3485 if (Major || Minor || Micro)
3486 return VersionTuple(Major, Minor, Micro);
3487
3488 if (IsWindowsMSVC) {
3489 VersionTuple MSVT = TC.getMSVCVersionFromExe();
3490 if (!MSVT.empty())
3491 return MSVT;
3492
3493 // FIXME: Consider bumping this to 19 (MSVC2015) soon.
3494 return VersionTuple(18);
3495 }
3496 }
3497 return VersionTuple();
3498 }
3499
addPGOAndCoverageFlags(Compilation & C,const Driver & D,const InputInfo & Output,const ArgList & Args,ArgStringList & CmdArgs)3500 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3501 const InputInfo &Output, const ArgList &Args,
3502 ArgStringList &CmdArgs) {
3503 auto *ProfileGenerateArg = Args.getLastArg(
3504 options::OPT_fprofile_instr_generate,
3505 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3506 options::OPT_fprofile_generate_EQ,
3507 options::OPT_fno_profile_instr_generate);
3508 if (ProfileGenerateArg &&
3509 ProfileGenerateArg->getOption().matches(
3510 options::OPT_fno_profile_instr_generate))
3511 ProfileGenerateArg = nullptr;
3512
3513 auto *ProfileUseArg = Args.getLastArg(
3514 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3515 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3516 options::OPT_fno_profile_instr_use);
3517 if (ProfileUseArg &&
3518 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3519 ProfileUseArg = nullptr;
3520
3521 if (ProfileGenerateArg && ProfileUseArg)
3522 D.Diag(diag::err_drv_argument_not_allowed_with)
3523 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3524
3525 if (ProfileGenerateArg) {
3526 if (ProfileGenerateArg->getOption().matches(
3527 options::OPT_fprofile_instr_generate_EQ))
3528 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
3529 ProfileGenerateArg->getValue()));
3530 else if (ProfileGenerateArg->getOption().matches(
3531 options::OPT_fprofile_generate_EQ)) {
3532 SmallString<128> Path(ProfileGenerateArg->getValue());
3533 llvm::sys::path::append(Path, "default.profraw");
3534 CmdArgs.push_back(
3535 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
3536 }
3537 // The default is to use Clang Instrumentation.
3538 CmdArgs.push_back("-fprofile-instrument=clang");
3539 }
3540
3541 if (ProfileUseArg) {
3542 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3543 CmdArgs.push_back(Args.MakeArgString(
3544 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
3545 else if ((ProfileUseArg->getOption().matches(
3546 options::OPT_fprofile_use_EQ) ||
3547 ProfileUseArg->getOption().matches(
3548 options::OPT_fprofile_instr_use))) {
3549 SmallString<128> Path(
3550 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3551 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3552 llvm::sys::path::append(Path, "default.profdata");
3553 CmdArgs.push_back(
3554 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
3555 }
3556 }
3557
3558 if (Args.hasArg(options::OPT_ftest_coverage) ||
3559 Args.hasArg(options::OPT_coverage))
3560 CmdArgs.push_back("-femit-coverage-notes");
3561 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3562 false) ||
3563 Args.hasArg(options::OPT_coverage))
3564 CmdArgs.push_back("-femit-coverage-data");
3565
3566 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3567 options::OPT_fno_coverage_mapping, false) &&
3568 !ProfileGenerateArg)
3569 D.Diag(diag::err_drv_argument_only_allowed_with)
3570 << "-fcoverage-mapping"
3571 << "-fprofile-instr-generate";
3572
3573 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3574 options::OPT_fno_coverage_mapping, false))
3575 CmdArgs.push_back("-fcoverage-mapping");
3576
3577 if (C.getArgs().hasArg(options::OPT_c) ||
3578 C.getArgs().hasArg(options::OPT_S)) {
3579 if (Output.isFilename()) {
3580 CmdArgs.push_back("-coverage-file");
3581 SmallString<128> CoverageFilename;
3582 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3583 CoverageFilename = FinalOutput->getValue();
3584 } else {
3585 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3586 }
3587 if (llvm::sys::path::is_relative(CoverageFilename)) {
3588 SmallString<128> Pwd;
3589 if (!llvm::sys::fs::current_path(Pwd)) {
3590 llvm::sys::path::append(Pwd, CoverageFilename);
3591 CoverageFilename.swap(Pwd);
3592 }
3593 }
3594 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3595 }
3596 }
3597 }
3598
addPS4ProfileRTArgs(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)3599 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3600 ArgStringList &CmdArgs) {
3601 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3602 false) ||
3603 Args.hasFlag(options::OPT_fprofile_generate,
3604 options::OPT_fno_profile_instr_generate, false) ||
3605 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3606 options::OPT_fno_profile_instr_generate, false) ||
3607 Args.hasFlag(options::OPT_fprofile_instr_generate,
3608 options::OPT_fno_profile_instr_generate, false) ||
3609 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3610 options::OPT_fno_profile_instr_generate, false) ||
3611 Args.hasArg(options::OPT_fcreate_profile) ||
3612 Args.hasArg(options::OPT_coverage)))
3613 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3614 }
3615
3616 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3617 /// smooshes them together with platform defaults, to decide whether
3618 /// this compile should be using PIC mode or not. Returns a tuple of
3619 /// (RelocationModel, PICLevel, IsPIE).
3620 static std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const llvm::Triple & Triple,const ArgList & Args)3621 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3622 const ArgList &Args) {
3623 // FIXME: why does this code...and so much everywhere else, use both
3624 // ToolChain.getTriple() and Triple?
3625 bool PIE = ToolChain.isPIEDefault();
3626 bool PIC = PIE || ToolChain.isPICDefault();
3627 // The Darwin/MachO default to use PIC does not apply when using -static.
3628 if (ToolChain.getTriple().isOSBinFormatMachO() &&
3629 Args.hasArg(options::OPT_static))
3630 PIE = PIC = false;
3631 bool IsPICLevelTwo = PIC;
3632
3633 bool KernelOrKext =
3634 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3635
3636 // Android-specific defaults for PIC/PIE
3637 if (ToolChain.getTriple().isAndroid()) {
3638 switch (ToolChain.getArch()) {
3639 case llvm::Triple::arm:
3640 case llvm::Triple::armeb:
3641 case llvm::Triple::thumb:
3642 case llvm::Triple::thumbeb:
3643 case llvm::Triple::aarch64:
3644 case llvm::Triple::mips:
3645 case llvm::Triple::mipsel:
3646 case llvm::Triple::mips64:
3647 case llvm::Triple::mips64el:
3648 PIC = true; // "-fpic"
3649 break;
3650
3651 case llvm::Triple::x86:
3652 case llvm::Triple::x86_64:
3653 PIC = true; // "-fPIC"
3654 IsPICLevelTwo = true;
3655 break;
3656
3657 default:
3658 break;
3659 }
3660 }
3661
3662 // OpenBSD-specific defaults for PIE
3663 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3664 switch (ToolChain.getArch()) {
3665 case llvm::Triple::mips64:
3666 case llvm::Triple::mips64el:
3667 case llvm::Triple::sparcel:
3668 case llvm::Triple::x86:
3669 case llvm::Triple::x86_64:
3670 IsPICLevelTwo = false; // "-fpie"
3671 break;
3672
3673 case llvm::Triple::ppc:
3674 case llvm::Triple::sparc:
3675 case llvm::Triple::sparcv9:
3676 IsPICLevelTwo = true; // "-fPIE"
3677 break;
3678
3679 default:
3680 break;
3681 }
3682 }
3683
3684 // The last argument relating to either PIC or PIE wins, and no
3685 // other argument is used. If the last argument is any flavor of the
3686 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3687 // option implicitly enables PIC at the same level.
3688 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3689 options::OPT_fpic, options::OPT_fno_pic,
3690 options::OPT_fPIE, options::OPT_fno_PIE,
3691 options::OPT_fpie, options::OPT_fno_pie);
3692 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3693 // is forced, then neither PIC nor PIE flags will have no effect.
3694 if (!ToolChain.isPICDefaultForced()) {
3695 if (LastPICArg) {
3696 Option O = LastPICArg->getOption();
3697 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3698 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3699 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3700 PIC =
3701 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3702 IsPICLevelTwo =
3703 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3704 } else {
3705 PIE = PIC = false;
3706 if (Triple.isPS4CPU()) {
3707 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3708 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3709 if (Model != "kernel") {
3710 PIC = true;
3711 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3712 << LastPICArg->getSpelling();
3713 }
3714 }
3715 }
3716 }
3717 }
3718
3719 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3720 // PIC level would've been set to level 1, force it back to level 2 PIC
3721 // instead.
3722 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3723 IsPICLevelTwo |= ToolChain.isPICDefault();
3724
3725 // This kernel flags are a trump-card: they will disable PIC/PIE
3726 // generation, independent of the argument order.
3727 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3728 !Triple.isWatchOS()))
3729 PIC = PIE = false;
3730
3731 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3732 // This is a very special mode. It trumps the other modes, almost no one
3733 // uses it, and it isn't even valid on any OS but Darwin.
3734 if (!ToolChain.getTriple().isOSDarwin())
3735 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3736 << A->getSpelling() << ToolChain.getTriple().str();
3737
3738 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3739
3740 // Only a forced PIC mode can cause the actual compile to have PIC defines
3741 // etc., no flags are sufficient. This behavior was selected to closely
3742 // match that of llvm-gcc and Apple GCC before that.
3743 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3744
3745 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3746 }
3747
3748 if (PIC)
3749 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3750
3751 return std::make_tuple(llvm::Reloc::Static, 0, false);
3752 }
3753
RelocationModelName(llvm::Reloc::Model Model)3754 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3755 switch (Model) {
3756 case llvm::Reloc::Static:
3757 return "static";
3758 case llvm::Reloc::PIC_:
3759 return "pic";
3760 case llvm::Reloc::DynamicNoPIC:
3761 return "dynamic-no-pic";
3762 }
3763 llvm_unreachable("Unknown Reloc::Model kind");
3764 }
3765
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)3766 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3767 ArgStringList &CmdArgs) {
3768 llvm::Reloc::Model RelocationModel;
3769 unsigned PICLevel;
3770 bool IsPIE;
3771 std::tie(RelocationModel, PICLevel, IsPIE) =
3772 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3773
3774 if (RelocationModel != llvm::Reloc::Static)
3775 CmdArgs.push_back("-KPIC");
3776 }
3777
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const3778 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3779 const InputInfo &Output, const InputInfoList &Inputs,
3780 const ArgList &Args, const char *LinkingOutput) const {
3781 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3782 const llvm::Triple Triple(TripleStr);
3783
3784 bool KernelOrKext =
3785 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3786 const Driver &D = getToolChain().getDriver();
3787 ArgStringList CmdArgs;
3788
3789 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3790 bool IsWindowsCygnus =
3791 getToolChain().getTriple().isWindowsCygwinEnvironment();
3792 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3793 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3794 bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
3795
3796 // Check number of inputs for sanity. We need at least one input.
3797 assert(Inputs.size() >= 1 && "Must have at least one input.");
3798 const InputInfo &Input = Inputs[0];
3799 // CUDA compilation may have multiple inputs (source file + results of
3800 // device-side compilations). All other jobs are expected to have exactly one
3801 // input.
3802 bool IsCuda = types::isCuda(Input.getType());
3803 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3804
3805 // C++ is not supported for IAMCU.
3806 if (IsIAMCU && types::isCXX(Input.getType()))
3807 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3808
3809 // Invoke ourselves in -cc1 mode.
3810 //
3811 // FIXME: Implement custom jobs for internal actions.
3812 CmdArgs.push_back("-cc1");
3813
3814 // Add the "effective" target triple.
3815 CmdArgs.push_back("-triple");
3816 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3817
3818 const ToolChain *AuxToolChain = nullptr;
3819 if (IsCuda) {
3820 // FIXME: We need a (better) way to pass information about
3821 // particular compilation pass we're constructing here. For now we
3822 // can check which toolchain we're using and pick the other one to
3823 // extract the triple.
3824 if (&getToolChain() == C.getSingleOffloadToolChain<Action::OFK_Cuda>())
3825 AuxToolChain = C.getOffloadingHostToolChain();
3826 else if (&getToolChain() == C.getOffloadingHostToolChain())
3827 AuxToolChain = C.getSingleOffloadToolChain<Action::OFK_Cuda>();
3828 else
3829 llvm_unreachable("Can't figure out CUDA compilation mode.");
3830 assert(AuxToolChain != nullptr && "No aux toolchain.");
3831 CmdArgs.push_back("-aux-triple");
3832 CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3833 }
3834
3835 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3836 Triple.getArch() == llvm::Triple::thumb)) {
3837 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3838 unsigned Version;
3839 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3840 if (Version < 7)
3841 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3842 << TripleStr;
3843 }
3844
3845 // Push all default warning arguments that are specific to
3846 // the given target. These come before user provided warning options
3847 // are provided.
3848 getToolChain().addClangWarningOptions(CmdArgs);
3849
3850 // Select the appropriate action.
3851 RewriteKind rewriteKind = RK_None;
3852
3853 if (isa<AnalyzeJobAction>(JA)) {
3854 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3855 CmdArgs.push_back("-analyze");
3856 } else if (isa<MigrateJobAction>(JA)) {
3857 CmdArgs.push_back("-migrate");
3858 } else if (isa<PreprocessJobAction>(JA)) {
3859 if (Output.getType() == types::TY_Dependencies)
3860 CmdArgs.push_back("-Eonly");
3861 else {
3862 CmdArgs.push_back("-E");
3863 if (Args.hasArg(options::OPT_rewrite_objc) &&
3864 !Args.hasArg(options::OPT_g_Group))
3865 CmdArgs.push_back("-P");
3866 }
3867 } else if (isa<AssembleJobAction>(JA)) {
3868 CmdArgs.push_back("-emit-obj");
3869
3870 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3871
3872 // Also ignore explicit -force_cpusubtype_ALL option.
3873 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3874 } else if (isa<PrecompileJobAction>(JA)) {
3875 // Use PCH if the user requested it.
3876 bool UsePCH = D.CCCUsePCH;
3877
3878 if (JA.getType() == types::TY_Nothing)
3879 CmdArgs.push_back("-fsyntax-only");
3880 else if (UsePCH)
3881 CmdArgs.push_back("-emit-pch");
3882 else
3883 CmdArgs.push_back("-emit-pth");
3884 } else if (isa<VerifyPCHJobAction>(JA)) {
3885 CmdArgs.push_back("-verify-pch");
3886 } else {
3887 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3888 "Invalid action for clang tool.");
3889 if (JA.getType() == types::TY_Nothing) {
3890 CmdArgs.push_back("-fsyntax-only");
3891 } else if (JA.getType() == types::TY_LLVM_IR ||
3892 JA.getType() == types::TY_LTO_IR) {
3893 CmdArgs.push_back("-emit-llvm");
3894 } else if (JA.getType() == types::TY_LLVM_BC ||
3895 JA.getType() == types::TY_LTO_BC) {
3896 CmdArgs.push_back("-emit-llvm-bc");
3897 } else if (JA.getType() == types::TY_PP_Asm) {
3898 CmdArgs.push_back("-S");
3899 } else if (JA.getType() == types::TY_AST) {
3900 CmdArgs.push_back("-emit-pch");
3901 } else if (JA.getType() == types::TY_ModuleFile) {
3902 CmdArgs.push_back("-module-file-info");
3903 } else if (JA.getType() == types::TY_RewrittenObjC) {
3904 CmdArgs.push_back("-rewrite-objc");
3905 rewriteKind = RK_NonFragile;
3906 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3907 CmdArgs.push_back("-rewrite-objc");
3908 rewriteKind = RK_Fragile;
3909 } else {
3910 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3911 }
3912
3913 // Preserve use-list order by default when emitting bitcode, so that
3914 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3915 // same result as running passes here. For LTO, we don't need to preserve
3916 // the use-list order, since serialization to bitcode is part of the flow.
3917 if (JA.getType() == types::TY_LLVM_BC)
3918 CmdArgs.push_back("-emit-llvm-uselists");
3919
3920 if (D.isUsingLTO())
3921 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3922 }
3923
3924 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3925 if (!types::isLLVMIR(Input.getType()))
3926 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3927 << "-x ir";
3928 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3929 }
3930
3931 // Embed-bitcode option.
3932 if (C.getDriver().embedBitcodeEnabled() &&
3933 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3934 // Add flags implied by -fembed-bitcode.
3935 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3936 // Disable all llvm IR level optimizations.
3937 CmdArgs.push_back("-disable-llvm-optzns");
3938 }
3939 if (C.getDriver().embedBitcodeMarkerOnly())
3940 CmdArgs.push_back("-fembed-bitcode=marker");
3941
3942 // We normally speed up the clang process a bit by skipping destructors at
3943 // exit, but when we're generating diagnostics we can rely on some of the
3944 // cleanup.
3945 if (!C.isForDiagnostics())
3946 CmdArgs.push_back("-disable-free");
3947
3948 // Disable the verification pass in -asserts builds.
3949 #ifdef NDEBUG
3950 CmdArgs.push_back("-disable-llvm-verifier");
3951 // Discard LLVM value names in -asserts builds.
3952 CmdArgs.push_back("-discard-value-names");
3953 #endif
3954
3955 // Set the main file name, so that debug info works even with
3956 // -save-temps.
3957 CmdArgs.push_back("-main-file-name");
3958 CmdArgs.push_back(getBaseInputName(Args, Input));
3959
3960 // Some flags which affect the language (via preprocessor
3961 // defines).
3962 if (Args.hasArg(options::OPT_static))
3963 CmdArgs.push_back("-static-define");
3964
3965 if (isa<AnalyzeJobAction>(JA)) {
3966 // Enable region store model by default.
3967 CmdArgs.push_back("-analyzer-store=region");
3968
3969 // Treat blocks as analysis entry points.
3970 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3971
3972 CmdArgs.push_back("-analyzer-eagerly-assume");
3973
3974 // Add default argument set.
3975 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3976 CmdArgs.push_back("-analyzer-checker=core");
3977
3978 if (!IsWindowsMSVC) {
3979 CmdArgs.push_back("-analyzer-checker=unix");
3980 } else {
3981 // Enable "unix" checkers that also work on Windows.
3982 CmdArgs.push_back("-analyzer-checker=unix.API");
3983 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3984 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3985 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3986 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3987 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3988 }
3989
3990 // Disable some unix checkers for PS4.
3991 if (IsPS4CPU) {
3992 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3993 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3994 }
3995
3996 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3997 CmdArgs.push_back("-analyzer-checker=osx");
3998
3999 CmdArgs.push_back("-analyzer-checker=deadcode");
4000
4001 if (types::isCXX(Input.getType()))
4002 CmdArgs.push_back("-analyzer-checker=cplusplus");
4003
4004 if (!IsPS4CPU) {
4005 CmdArgs.push_back(
4006 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
4007 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
4008 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
4009 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
4010 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
4011 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
4012 }
4013
4014 // Default nullability checks.
4015 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
4016 CmdArgs.push_back(
4017 "-analyzer-checker=nullability.NullReturnedFromNonnull");
4018 }
4019
4020 // Set the output format. The default is plist, for (lame) historical
4021 // reasons.
4022 CmdArgs.push_back("-analyzer-output");
4023 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
4024 CmdArgs.push_back(A->getValue());
4025 else
4026 CmdArgs.push_back("plist");
4027
4028 // Disable the presentation of standard compiler warnings when
4029 // using --analyze. We only want to show static analyzer diagnostics
4030 // or frontend errors.
4031 CmdArgs.push_back("-w");
4032
4033 // Add -Xanalyzer arguments when running as analyzer.
4034 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
4035 }
4036
4037 CheckCodeGenerationOptions(D, Args);
4038
4039 llvm::Reloc::Model RelocationModel;
4040 unsigned PICLevel;
4041 bool IsPIE;
4042 std::tie(RelocationModel, PICLevel, IsPIE) =
4043 ParsePICArgs(getToolChain(), Triple, Args);
4044
4045 const char *RMName = RelocationModelName(RelocationModel);
4046 if (RMName) {
4047 CmdArgs.push_back("-mrelocation-model");
4048 CmdArgs.push_back(RMName);
4049 }
4050 if (PICLevel > 0) {
4051 CmdArgs.push_back("-pic-level");
4052 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4053 if (IsPIE)
4054 CmdArgs.push_back("-pic-is-pie");
4055 }
4056
4057 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4058 CmdArgs.push_back("-meabi");
4059 CmdArgs.push_back(A->getValue());
4060 }
4061
4062 CmdArgs.push_back("-mthread-model");
4063 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
4064 CmdArgs.push_back(A->getValue());
4065 else
4066 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
4067
4068 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4069
4070 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
4071 options::OPT_fno_merge_all_constants))
4072 CmdArgs.push_back("-fno-merge-all-constants");
4073
4074 // LLVM Code Generator Options.
4075
4076 if (Args.hasArg(options::OPT_frewrite_map_file) ||
4077 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4078 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4079 options::OPT_frewrite_map_file_EQ)) {
4080 CmdArgs.push_back("-frewrite-map-file");
4081 CmdArgs.push_back(A->getValue());
4082 A->claim();
4083 }
4084 }
4085
4086 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4087 StringRef v = A->getValue();
4088 CmdArgs.push_back("-mllvm");
4089 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4090 A->claim();
4091 }
4092
4093 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4094 true))
4095 CmdArgs.push_back("-fno-jump-tables");
4096
4097 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4098 CmdArgs.push_back("-mregparm");
4099 CmdArgs.push_back(A->getValue());
4100 }
4101
4102 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4103 options::OPT_freg_struct_return)) {
4104 if (getToolChain().getArch() != llvm::Triple::x86) {
4105 D.Diag(diag::err_drv_unsupported_opt_for_target)
4106 << A->getSpelling() << getToolChain().getTriple().str();
4107 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4108 CmdArgs.push_back("-fpcc-struct-return");
4109 } else {
4110 assert(A->getOption().matches(options::OPT_freg_struct_return));
4111 CmdArgs.push_back("-freg-struct-return");
4112 }
4113 }
4114
4115 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4116 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4117
4118 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
4119 CmdArgs.push_back("-mdisable-fp-elim");
4120 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4121 options::OPT_fno_zero_initialized_in_bss))
4122 CmdArgs.push_back("-mno-zero-initialized-in-bss");
4123
4124 bool OFastEnabled = isOptimizationLevelFast(Args);
4125 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4126 // enabled. This alias option is being used to simplify the hasFlag logic.
4127 OptSpecifier StrictAliasingAliasOption =
4128 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4129 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4130 // doesn't do any TBAA.
4131 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
4132 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4133 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4134 CmdArgs.push_back("-relaxed-aliasing");
4135 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4136 options::OPT_fno_struct_path_tbaa))
4137 CmdArgs.push_back("-no-struct-path-tbaa");
4138 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4139 false))
4140 CmdArgs.push_back("-fstrict-enums");
4141 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4142 options::OPT_fno_strict_vtable_pointers,
4143 false))
4144 CmdArgs.push_back("-fstrict-vtable-pointers");
4145 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4146 options::OPT_fno_optimize_sibling_calls))
4147 CmdArgs.push_back("-mdisable-tail-calls");
4148
4149 // Handle segmented stacks.
4150 if (Args.hasArg(options::OPT_fsplit_stack))
4151 CmdArgs.push_back("-split-stacks");
4152
4153 // If -Ofast is the optimization level, then -ffast-math should be enabled.
4154 // This alias option is being used to simplify the getLastArg logic.
4155 OptSpecifier FastMathAliasOption =
4156 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
4157
4158 // Handle various floating point optimization flags, mapping them to the
4159 // appropriate LLVM code generation flags. The pattern for all of these is to
4160 // default off the codegen optimizations, and if any flag enables them and no
4161 // flag disables them after the flag enabling them, enable the codegen
4162 // optimization. This is complicated by several "umbrella" flags.
4163 if (Arg *A = Args.getLastArg(
4164 options::OPT_ffast_math, FastMathAliasOption,
4165 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4166 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
4167 options::OPT_fno_honor_infinities))
4168 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4169 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4170 A->getOption().getID() != options::OPT_fhonor_infinities)
4171 CmdArgs.push_back("-menable-no-infs");
4172 if (Arg *A = Args.getLastArg(
4173 options::OPT_ffast_math, FastMathAliasOption,
4174 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
4175 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
4176 options::OPT_fno_honor_nans))
4177 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4178 A->getOption().getID() != options::OPT_fno_finite_math_only &&
4179 A->getOption().getID() != options::OPT_fhonor_nans)
4180 CmdArgs.push_back("-menable-no-nans");
4181
4182 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
4183 bool MathErrno = getToolChain().IsMathErrnoDefault();
4184 if (Arg *A =
4185 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4186 options::OPT_fno_fast_math, options::OPT_fmath_errno,
4187 options::OPT_fno_math_errno)) {
4188 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
4189 // However, turning *off* -ffast_math merely restores the toolchain default
4190 // (which may be false).
4191 if (A->getOption().getID() == options::OPT_fno_math_errno ||
4192 A->getOption().getID() == options::OPT_ffast_math ||
4193 A->getOption().getID() == options::OPT_Ofast)
4194 MathErrno = false;
4195 else if (A->getOption().getID() == options::OPT_fmath_errno)
4196 MathErrno = true;
4197 }
4198 if (MathErrno)
4199 CmdArgs.push_back("-fmath-errno");
4200
4201 // There are several flags which require disabling very specific
4202 // optimizations. Any of these being disabled forces us to turn off the
4203 // entire set of LLVM optimizations, so collect them through all the flag
4204 // madness.
4205 bool AssociativeMath = false;
4206 if (Arg *A = Args.getLastArg(
4207 options::OPT_ffast_math, FastMathAliasOption,
4208 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4209 options::OPT_fno_unsafe_math_optimizations,
4210 options::OPT_fassociative_math, options::OPT_fno_associative_math))
4211 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4212 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4213 A->getOption().getID() != options::OPT_fno_associative_math)
4214 AssociativeMath = true;
4215 bool ReciprocalMath = false;
4216 if (Arg *A = Args.getLastArg(
4217 options::OPT_ffast_math, FastMathAliasOption,
4218 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4219 options::OPT_fno_unsafe_math_optimizations,
4220 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
4221 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4222 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4223 A->getOption().getID() != options::OPT_fno_reciprocal_math)
4224 ReciprocalMath = true;
4225 bool SignedZeros = true;
4226 if (Arg *A = Args.getLastArg(
4227 options::OPT_ffast_math, FastMathAliasOption,
4228 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4229 options::OPT_fno_unsafe_math_optimizations,
4230 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
4231 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4232 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4233 A->getOption().getID() != options::OPT_fsigned_zeros)
4234 SignedZeros = false;
4235 bool TrappingMath = true;
4236 if (Arg *A = Args.getLastArg(
4237 options::OPT_ffast_math, FastMathAliasOption,
4238 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
4239 options::OPT_fno_unsafe_math_optimizations,
4240 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
4241 if (A->getOption().getID() != options::OPT_fno_fast_math &&
4242 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
4243 A->getOption().getID() != options::OPT_ftrapping_math)
4244 TrappingMath = false;
4245 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
4246 !TrappingMath)
4247 CmdArgs.push_back("-menable-unsafe-fp-math");
4248
4249 if (!SignedZeros)
4250 CmdArgs.push_back("-fno-signed-zeros");
4251
4252 if (ReciprocalMath)
4253 CmdArgs.push_back("-freciprocal-math");
4254
4255 // Validate and pass through -fp-contract option.
4256 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4257 options::OPT_fno_fast_math,
4258 options::OPT_ffp_contract)) {
4259 if (A->getOption().getID() == options::OPT_ffp_contract) {
4260 StringRef Val = A->getValue();
4261 if (Val == "fast" || Val == "on" || Val == "off") {
4262 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
4263 } else {
4264 D.Diag(diag::err_drv_unsupported_option_argument)
4265 << A->getOption().getName() << Val;
4266 }
4267 } else if (A->getOption().matches(options::OPT_ffast_math) ||
4268 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
4269 // If fast-math is set then set the fp-contract mode to fast.
4270 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
4271 }
4272 }
4273
4274 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
4275
4276 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
4277 // and if we find them, tell the frontend to provide the appropriate
4278 // preprocessor macros. This is distinct from enabling any optimizations as
4279 // these options induce language changes which must survive serialization
4280 // and deserialization, etc.
4281 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
4282 options::OPT_fno_fast_math))
4283 if (!A->getOption().matches(options::OPT_fno_fast_math))
4284 CmdArgs.push_back("-ffast-math");
4285 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
4286 options::OPT_fno_fast_math))
4287 if (A->getOption().matches(options::OPT_ffinite_math_only))
4288 CmdArgs.push_back("-ffinite-math-only");
4289
4290 // Decide whether to use verbose asm. Verbose assembly is the default on
4291 // toolchains which have the integrated assembler on by default.
4292 bool IsIntegratedAssemblerDefault =
4293 getToolChain().IsIntegratedAssemblerDefault();
4294 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4295 IsIntegratedAssemblerDefault) ||
4296 Args.hasArg(options::OPT_dA))
4297 CmdArgs.push_back("-masm-verbose");
4298
4299 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
4300 IsIntegratedAssemblerDefault))
4301 CmdArgs.push_back("-no-integrated-as");
4302
4303 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4304 CmdArgs.push_back("-mdebug-pass");
4305 CmdArgs.push_back("Structure");
4306 }
4307 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4308 CmdArgs.push_back("-mdebug-pass");
4309 CmdArgs.push_back("Arguments");
4310 }
4311
4312 // Enable -mconstructor-aliases except on darwin, where we have to work around
4313 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4314 // aliases aren't supported.
4315 if (!getToolChain().getTriple().isOSDarwin() &&
4316 !getToolChain().getTriple().isNVPTX())
4317 CmdArgs.push_back("-mconstructor-aliases");
4318
4319 // Darwin's kernel doesn't support guard variables; just die if we
4320 // try to use them.
4321 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
4322 CmdArgs.push_back("-fforbid-guard-variables");
4323
4324 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4325 false)) {
4326 CmdArgs.push_back("-mms-bitfields");
4327 }
4328
4329 // This is a coarse approximation of what llvm-gcc actually does, both
4330 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4331 // complicated ways.
4332 bool AsynchronousUnwindTables =
4333 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4334 options::OPT_fno_asynchronous_unwind_tables,
4335 (getToolChain().IsUnwindTablesDefault() ||
4336 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
4337 !KernelOrKext);
4338 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4339 AsynchronousUnwindTables))
4340 CmdArgs.push_back("-munwind-tables");
4341
4342 getToolChain().addClangTargetOptions(Args, CmdArgs);
4343
4344 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
4345 CmdArgs.push_back("-mlimit-float-precision");
4346 CmdArgs.push_back(A->getValue());
4347 }
4348
4349 // FIXME: Handle -mtune=.
4350 (void)Args.hasArg(options::OPT_mtune_EQ);
4351
4352 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4353 CmdArgs.push_back("-mcode-model");
4354 CmdArgs.push_back(A->getValue());
4355 }
4356
4357 // Add the target cpu
4358 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4359 if (!CPU.empty()) {
4360 CmdArgs.push_back("-target-cpu");
4361 CmdArgs.push_back(Args.MakeArgString(CPU));
4362 }
4363
4364 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
4365 CmdArgs.push_back("-mfpmath");
4366 CmdArgs.push_back(A->getValue());
4367 }
4368
4369 // Add the target features
4370 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
4371
4372 // Add target specific flags.
4373 switch (getToolChain().getArch()) {
4374 default:
4375 break;
4376
4377 case llvm::Triple::arm:
4378 case llvm::Triple::armeb:
4379 case llvm::Triple::thumb:
4380 case llvm::Triple::thumbeb:
4381 // Use the effective triple, which takes into account the deployment target.
4382 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
4383 break;
4384
4385 case llvm::Triple::aarch64:
4386 case llvm::Triple::aarch64_be:
4387 AddAArch64TargetArgs(Args, CmdArgs);
4388 break;
4389
4390 case llvm::Triple::mips:
4391 case llvm::Triple::mipsel:
4392 case llvm::Triple::mips64:
4393 case llvm::Triple::mips64el:
4394 AddMIPSTargetArgs(Args, CmdArgs);
4395 break;
4396
4397 case llvm::Triple::ppc:
4398 case llvm::Triple::ppc64:
4399 case llvm::Triple::ppc64le:
4400 AddPPCTargetArgs(Args, CmdArgs);
4401 break;
4402
4403 case llvm::Triple::sparc:
4404 case llvm::Triple::sparcel:
4405 case llvm::Triple::sparcv9:
4406 AddSparcTargetArgs(Args, CmdArgs);
4407 break;
4408
4409 case llvm::Triple::systemz:
4410 AddSystemZTargetArgs(Args, CmdArgs);
4411 break;
4412
4413 case llvm::Triple::x86:
4414 case llvm::Triple::x86_64:
4415 AddX86TargetArgs(Args, CmdArgs);
4416 break;
4417
4418 case llvm::Triple::lanai:
4419 AddLanaiTargetArgs(Args, CmdArgs);
4420 break;
4421
4422 case llvm::Triple::hexagon:
4423 AddHexagonTargetArgs(Args, CmdArgs);
4424 break;
4425
4426 case llvm::Triple::wasm32:
4427 case llvm::Triple::wasm64:
4428 AddWebAssemblyTargetArgs(Args, CmdArgs);
4429 break;
4430 }
4431
4432 // The 'g' groups options involve a somewhat intricate sequence of decisions
4433 // about what to pass from the driver to the frontend, but by the time they
4434 // reach cc1 they've been factored into three well-defined orthogonal choices:
4435 // * what level of debug info to generate
4436 // * what dwarf version to write
4437 // * what debugger tuning to use
4438 // This avoids having to monkey around further in cc1 other than to disable
4439 // codeview if not running in a Windows environment. Perhaps even that
4440 // decision should be made in the driver as well though.
4441 unsigned DwarfVersion = 0;
4442 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4443 // These two are potentially updated by AddClangCLArgs.
4444 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4445 bool EmitCodeView = false;
4446
4447 // Add clang-cl arguments.
4448 types::ID InputType = Input.getType();
4449 if (getToolChain().getDriver().IsCLMode())
4450 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4451
4452 // Pass the linker version in use.
4453 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4454 CmdArgs.push_back("-target-linker-version");
4455 CmdArgs.push_back(A->getValue());
4456 }
4457
4458 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4459 CmdArgs.push_back("-momit-leaf-frame-pointer");
4460
4461 // Explicitly error on some things we know we don't support and can't just
4462 // ignore.
4463 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4464 Arg *Unsupported;
4465 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4466 getToolChain().getArch() == llvm::Triple::x86) {
4467 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4468 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4469 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4470 << Unsupported->getOption().getName();
4471 }
4472 }
4473
4474 Args.AddAllArgs(CmdArgs, options::OPT_v);
4475 Args.AddLastArg(CmdArgs, options::OPT_H);
4476 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4477 CmdArgs.push_back("-header-include-file");
4478 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4479 : "-");
4480 }
4481 Args.AddLastArg(CmdArgs, options::OPT_P);
4482 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4483
4484 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4485 CmdArgs.push_back("-diagnostic-log-file");
4486 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4487 : "-");
4488 }
4489
4490 Args.ClaimAllArgs(options::OPT_g_Group);
4491 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4492 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4493 // If the last option explicitly specified a debug-info level, use it.
4494 if (A->getOption().matches(options::OPT_gN_Group)) {
4495 DebugInfoKind = DebugLevelToInfoKind(*A);
4496 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4497 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4498 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4499 if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
4500 A->getIndex() > SplitDwarfArg->getIndex())
4501 SplitDwarfArg = nullptr;
4502 } else
4503 // For any other 'g' option, use Limited.
4504 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4505 }
4506
4507 // If a debugger tuning argument appeared, remember it.
4508 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4509 options::OPT_ggdbN_Group)) {
4510 if (A->getOption().matches(options::OPT_glldb))
4511 DebuggerTuning = llvm::DebuggerKind::LLDB;
4512 else if (A->getOption().matches(options::OPT_gsce))
4513 DebuggerTuning = llvm::DebuggerKind::SCE;
4514 else
4515 DebuggerTuning = llvm::DebuggerKind::GDB;
4516 }
4517
4518 // If a -gdwarf argument appeared, remember it.
4519 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4520 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4521 DwarfVersion = DwarfVersionNum(A->getSpelling());
4522
4523 // Forward -gcodeview.
4524 // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4525 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4526 // DwarfVersion remains at 0 if no explicit choice was made.
4527 CmdArgs.push_back("-gcodeview");
4528 } else if (DwarfVersion == 0 &&
4529 DebugInfoKind != codegenoptions::NoDebugInfo) {
4530 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4531 }
4532
4533 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4534 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4535
4536 // PS4 defaults to no column info
4537 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4538 /*Default=*/ !IsPS4CPU))
4539 CmdArgs.push_back("-dwarf-column-info");
4540
4541 // FIXME: Move backend command line options to the module.
4542 if (Args.hasArg(options::OPT_gmodules)) {
4543 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4544 CmdArgs.push_back("-dwarf-ext-refs");
4545 CmdArgs.push_back("-fmodule-format=obj");
4546 }
4547
4548 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4549 // splitting and extraction.
4550 // FIXME: Currently only works on Linux.
4551 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4552 DebugInfoKind = codegenoptions::LimitedDebugInfo;
4553 CmdArgs.push_back("-backend-option");
4554 CmdArgs.push_back("-split-dwarf=Enable");
4555 }
4556
4557 // After we've dealt with all combinations of things that could
4558 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4559 // figure out if we need to "upgrade" it to standalone debug info.
4560 // We parse these two '-f' options whether or not they will be used,
4561 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4562 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4563 options::OPT_fno_standalone_debug,
4564 getToolChain().GetDefaultStandaloneDebug());
4565 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
4566 DebugInfoKind = codegenoptions::FullDebugInfo;
4567 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4568 DebuggerTuning);
4569
4570 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4571 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4572 CmdArgs.push_back("-backend-option");
4573 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4574 }
4575
4576 // -gdwarf-aranges turns on the emission of the aranges section in the
4577 // backend.
4578 // Always enabled on the PS4.
4579 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4580 CmdArgs.push_back("-backend-option");
4581 CmdArgs.push_back("-generate-arange-section");
4582 }
4583
4584 if (Args.hasFlag(options::OPT_fdebug_types_section,
4585 options::OPT_fno_debug_types_section, false)) {
4586 CmdArgs.push_back("-backend-option");
4587 CmdArgs.push_back("-generate-type-units");
4588 }
4589
4590 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4591 // default.
4592 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4593 Triple.getArch() == llvm::Triple::wasm32 ||
4594 Triple.getArch() == llvm::Triple::wasm64;
4595
4596 if (Args.hasFlag(options::OPT_ffunction_sections,
4597 options::OPT_fno_function_sections, UseSeparateSections)) {
4598 CmdArgs.push_back("-ffunction-sections");
4599 }
4600
4601 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4602 UseSeparateSections)) {
4603 CmdArgs.push_back("-fdata-sections");
4604 }
4605
4606 if (!Args.hasFlag(options::OPT_funique_section_names,
4607 options::OPT_fno_unique_section_names, true))
4608 CmdArgs.push_back("-fno-unique-section-names");
4609
4610 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4611
4612 if (Args.hasFlag(options::OPT_fxray_instrument,
4613 options::OPT_fnoxray_instrument, false)) {
4614 CmdArgs.push_back("-fxray-instrument");
4615 if (Arg *A = Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4616 options::OPT_fxray_instruction_threshold_EQ)) {
4617 CmdArgs.push_back("-fxray-instruction-threshold");
4618 CmdArgs.push_back(A->getValue());
4619 }
4620 }
4621
4622 if (Args.hasFlag(options::OPT_fxray_instrument,
4623 options::OPT_fnoxray_instrument, false)) {
4624 CmdArgs.push_back("-fxray-instrument");
4625 if (const Arg *A =
4626 Args.getLastArg(options::OPT_fxray_instruction_threshold_,
4627 options::OPT_fxray_instruction_threshold_EQ)) {
4628 CmdArgs.push_back("-fxray-instruction-threshold");
4629 CmdArgs.push_back(A->getValue());
4630 }
4631 }
4632
4633 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4634
4635 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4636 if (getToolChain().getTriple().isPS4CPU())
4637 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4638
4639 // Pass options for controlling the default header search paths.
4640 if (Args.hasArg(options::OPT_nostdinc)) {
4641 CmdArgs.push_back("-nostdsysteminc");
4642 CmdArgs.push_back("-nobuiltininc");
4643 } else {
4644 if (Args.hasArg(options::OPT_nostdlibinc))
4645 CmdArgs.push_back("-nostdsysteminc");
4646 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4647 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4648 }
4649
4650 // Pass the path to compiler resource files.
4651 CmdArgs.push_back("-resource-dir");
4652 CmdArgs.push_back(D.ResourceDir.c_str());
4653
4654 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4655
4656 bool ARCMTEnabled = false;
4657 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4658 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4659 options::OPT_ccc_arcmt_modify,
4660 options::OPT_ccc_arcmt_migrate)) {
4661 ARCMTEnabled = true;
4662 switch (A->getOption().getID()) {
4663 default:
4664 llvm_unreachable("missed a case");
4665 case options::OPT_ccc_arcmt_check:
4666 CmdArgs.push_back("-arcmt-check");
4667 break;
4668 case options::OPT_ccc_arcmt_modify:
4669 CmdArgs.push_back("-arcmt-modify");
4670 break;
4671 case options::OPT_ccc_arcmt_migrate:
4672 CmdArgs.push_back("-arcmt-migrate");
4673 CmdArgs.push_back("-mt-migrate-directory");
4674 CmdArgs.push_back(A->getValue());
4675
4676 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4677 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4678 break;
4679 }
4680 }
4681 } else {
4682 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4683 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4684 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4685 }
4686
4687 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4688 if (ARCMTEnabled) {
4689 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4690 << "-ccc-arcmt-migrate";
4691 }
4692 CmdArgs.push_back("-mt-migrate-directory");
4693 CmdArgs.push_back(A->getValue());
4694
4695 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4696 options::OPT_objcmt_migrate_subscripting,
4697 options::OPT_objcmt_migrate_property)) {
4698 // None specified, means enable them all.
4699 CmdArgs.push_back("-objcmt-migrate-literals");
4700 CmdArgs.push_back("-objcmt-migrate-subscripting");
4701 CmdArgs.push_back("-objcmt-migrate-property");
4702 } else {
4703 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4704 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4705 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4706 }
4707 } else {
4708 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4709 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4710 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4711 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4712 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4713 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4714 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4715 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4716 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4717 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4718 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4719 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4720 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4721 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4722 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4723 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4724 }
4725
4726 // Add preprocessing options like -I, -D, etc. if we are using the
4727 // preprocessor.
4728 //
4729 // FIXME: Support -fpreprocessed
4730 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4731 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4732 AuxToolChain);
4733
4734 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4735 // that "The compiler can only warn and ignore the option if not recognized".
4736 // When building with ccache, it will pass -D options to clang even on
4737 // preprocessed inputs and configure concludes that -fPIC is not supported.
4738 Args.ClaimAllArgs(options::OPT_D);
4739
4740 // Manually translate -O4 to -O3; let clang reject others.
4741 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4742 if (A->getOption().matches(options::OPT_O4)) {
4743 CmdArgs.push_back("-O3");
4744 D.Diag(diag::warn_O4_is_O3);
4745 } else {
4746 A->render(Args, CmdArgs);
4747 }
4748 }
4749
4750 // Warn about ignored options to clang.
4751 for (const Arg *A :
4752 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4753 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4754 A->claim();
4755 }
4756
4757 claimNoWarnArgs(Args);
4758
4759 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4760 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4761 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4762 CmdArgs.push_back("-pedantic");
4763 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4764 Args.AddLastArg(CmdArgs, options::OPT_w);
4765
4766 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4767 // (-ansi is equivalent to -std=c89 or -std=c++98).
4768 //
4769 // If a std is supplied, only add -trigraphs if it follows the
4770 // option.
4771 bool ImplyVCPPCXXVer = false;
4772 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4773 if (Std->getOption().matches(options::OPT_ansi))
4774 if (types::isCXX(InputType))
4775 CmdArgs.push_back("-std=c++98");
4776 else
4777 CmdArgs.push_back("-std=c89");
4778 else
4779 Std->render(Args, CmdArgs);
4780
4781 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4782 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4783 options::OPT_ftrigraphs,
4784 options::OPT_fno_trigraphs))
4785 if (A != Std)
4786 A->render(Args, CmdArgs);
4787 } else {
4788 // Honor -std-default.
4789 //
4790 // FIXME: Clang doesn't correctly handle -std= when the input language
4791 // doesn't match. For the time being just ignore this for C++ inputs;
4792 // eventually we want to do all the standard defaulting here instead of
4793 // splitting it between the driver and clang -cc1.
4794 if (!types::isCXX(InputType))
4795 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4796 /*Joined=*/true);
4797 else if (IsWindowsMSVC)
4798 ImplyVCPPCXXVer = true;
4799
4800 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4801 options::OPT_fno_trigraphs);
4802 }
4803
4804 // GCC's behavior for -Wwrite-strings is a bit strange:
4805 // * In C, this "warning flag" changes the types of string literals from
4806 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4807 // for the discarded qualifier.
4808 // * In C++, this is just a normal warning flag.
4809 //
4810 // Implementing this warning correctly in C is hard, so we follow GCC's
4811 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4812 // a non-const char* in C, rather than using this crude hack.
4813 if (!types::isCXX(InputType)) {
4814 // FIXME: This should behave just like a warning flag, and thus should also
4815 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4816 Arg *WriteStrings =
4817 Args.getLastArg(options::OPT_Wwrite_strings,
4818 options::OPT_Wno_write_strings, options::OPT_w);
4819 if (WriteStrings &&
4820 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4821 CmdArgs.push_back("-fconst-strings");
4822 }
4823
4824 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4825 // during C++ compilation, which it is by default. GCC keeps this define even
4826 // in the presence of '-w', match this behavior bug-for-bug.
4827 if (types::isCXX(InputType) &&
4828 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4829 true)) {
4830 CmdArgs.push_back("-fdeprecated-macro");
4831 }
4832
4833 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4834 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4835 if (Asm->getOption().matches(options::OPT_fasm))
4836 CmdArgs.push_back("-fgnu-keywords");
4837 else
4838 CmdArgs.push_back("-fno-gnu-keywords");
4839 }
4840
4841 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4842 CmdArgs.push_back("-fno-dwarf-directory-asm");
4843
4844 if (ShouldDisableAutolink(Args, getToolChain()))
4845 CmdArgs.push_back("-fno-autolink");
4846
4847 // Add in -fdebug-compilation-dir if necessary.
4848 addDebugCompDirArg(Args, CmdArgs);
4849
4850 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4851 StringRef Map = A->getValue();
4852 if (Map.find('=') == StringRef::npos)
4853 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4854 else
4855 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4856 A->claim();
4857 }
4858
4859 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4860 options::OPT_ftemplate_depth_EQ)) {
4861 CmdArgs.push_back("-ftemplate-depth");
4862 CmdArgs.push_back(A->getValue());
4863 }
4864
4865 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4866 CmdArgs.push_back("-foperator-arrow-depth");
4867 CmdArgs.push_back(A->getValue());
4868 }
4869
4870 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4871 CmdArgs.push_back("-fconstexpr-depth");
4872 CmdArgs.push_back(A->getValue());
4873 }
4874
4875 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4876 CmdArgs.push_back("-fconstexpr-steps");
4877 CmdArgs.push_back(A->getValue());
4878 }
4879
4880 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4881 CmdArgs.push_back("-fbracket-depth");
4882 CmdArgs.push_back(A->getValue());
4883 }
4884
4885 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4886 options::OPT_Wlarge_by_value_copy_def)) {
4887 if (A->getNumValues()) {
4888 StringRef bytes = A->getValue();
4889 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4890 } else
4891 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4892 }
4893
4894 if (Args.hasArg(options::OPT_relocatable_pch))
4895 CmdArgs.push_back("-relocatable-pch");
4896
4897 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4898 CmdArgs.push_back("-fconstant-string-class");
4899 CmdArgs.push_back(A->getValue());
4900 }
4901
4902 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4903 CmdArgs.push_back("-ftabstop");
4904 CmdArgs.push_back(A->getValue());
4905 }
4906
4907 CmdArgs.push_back("-ferror-limit");
4908 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4909 CmdArgs.push_back(A->getValue());
4910 else
4911 CmdArgs.push_back("19");
4912
4913 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4914 CmdArgs.push_back("-fmacro-backtrace-limit");
4915 CmdArgs.push_back(A->getValue());
4916 }
4917
4918 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4919 CmdArgs.push_back("-ftemplate-backtrace-limit");
4920 CmdArgs.push_back(A->getValue());
4921 }
4922
4923 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4924 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4925 CmdArgs.push_back(A->getValue());
4926 }
4927
4928 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4929 CmdArgs.push_back("-fspell-checking-limit");
4930 CmdArgs.push_back(A->getValue());
4931 }
4932
4933 // Pass -fmessage-length=.
4934 CmdArgs.push_back("-fmessage-length");
4935 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4936 CmdArgs.push_back(A->getValue());
4937 } else {
4938 // If -fmessage-length=N was not specified, determine whether this is a
4939 // terminal and, if so, implicitly define -fmessage-length appropriately.
4940 unsigned N = llvm::sys::Process::StandardErrColumns();
4941 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4942 }
4943
4944 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4945 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4946 options::OPT_fvisibility_ms_compat)) {
4947 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4948 CmdArgs.push_back("-fvisibility");
4949 CmdArgs.push_back(A->getValue());
4950 } else {
4951 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4952 CmdArgs.push_back("-fvisibility");
4953 CmdArgs.push_back("hidden");
4954 CmdArgs.push_back("-ftype-visibility");
4955 CmdArgs.push_back("default");
4956 }
4957 }
4958
4959 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4960
4961 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4962
4963 // -fhosted is default.
4964 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4965 KernelOrKext)
4966 CmdArgs.push_back("-ffreestanding");
4967
4968 // Forward -f (flag) options which we can pass directly.
4969 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4970 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4971 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4972 // Emulated TLS is enabled by default on Android, and can be enabled manually
4973 // with -femulated-tls.
4974 bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
4975 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4976 EmulatedTLSDefault))
4977 CmdArgs.push_back("-femulated-tls");
4978 // AltiVec-like language extensions aren't relevant for assembling.
4979 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4980 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4981 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4982 }
4983 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4984 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4985
4986 // Forward flags for OpenMP
4987 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4988 options::OPT_fno_openmp, false)) {
4989 switch (getOpenMPRuntime(getToolChain(), Args)) {
4990 case OMPRT_OMP:
4991 case OMPRT_IOMP5:
4992 // Clang can generate useful OpenMP code for these two runtime libraries.
4993 CmdArgs.push_back("-fopenmp");
4994
4995 // If no option regarding the use of TLS in OpenMP codegeneration is
4996 // given, decide a default based on the target. Otherwise rely on the
4997 // options and pass the right information to the frontend.
4998 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4999 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5000 CmdArgs.push_back("-fnoopenmp-use-tls");
5001 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5002 break;
5003 default:
5004 // By default, if Clang doesn't know how to generate useful OpenMP code
5005 // for a specific runtime library, we just don't pass the '-fopenmp' flag
5006 // down to the actual compilation.
5007 // FIXME: It would be better to have a mode which *only* omits IR
5008 // generation based on the OpenMP support so that we get consistent
5009 // semantic analysis, etc.
5010 break;
5011 }
5012 }
5013
5014 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
5015 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
5016
5017 // Report an error for -faltivec on anything other than PowerPC.
5018 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
5019 const llvm::Triple::ArchType Arch = getToolChain().getArch();
5020 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
5021 Arch == llvm::Triple::ppc64le))
5022 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
5023 << "ppc/ppc64/ppc64le";
5024 }
5025
5026 // -fzvector is incompatible with -faltivec.
5027 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
5028 if (Args.hasArg(options::OPT_faltivec))
5029 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
5030 << "-faltivec";
5031
5032 if (getToolChain().SupportsProfiling())
5033 Args.AddLastArg(CmdArgs, options::OPT_pg);
5034
5035 // -flax-vector-conversions is default.
5036 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
5037 options::OPT_fno_lax_vector_conversions))
5038 CmdArgs.push_back("-fno-lax-vector-conversions");
5039
5040 if (Args.getLastArg(options::OPT_fapple_kext) ||
5041 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5042 CmdArgs.push_back("-fapple-kext");
5043
5044 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5045 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5046 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5047 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5048 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5049
5050 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5051 CmdArgs.push_back("-ftrapv-handler");
5052 CmdArgs.push_back(A->getValue());
5053 }
5054
5055 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5056
5057 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5058 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5059 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5060 if (A->getOption().matches(options::OPT_fwrapv))
5061 CmdArgs.push_back("-fwrapv");
5062 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5063 options::OPT_fno_strict_overflow)) {
5064 if (A->getOption().matches(options::OPT_fno_strict_overflow))
5065 CmdArgs.push_back("-fwrapv");
5066 }
5067
5068 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5069 options::OPT_fno_reroll_loops))
5070 if (A->getOption().matches(options::OPT_freroll_loops))
5071 CmdArgs.push_back("-freroll-loops");
5072
5073 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5074 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5075 options::OPT_fno_unroll_loops);
5076
5077 Args.AddLastArg(CmdArgs, options::OPT_pthread);
5078
5079 // -stack-protector=0 is default.
5080 unsigned StackProtectorLevel = 0;
5081 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
5082 options::OPT_fstack_protector_all,
5083 options::OPT_fstack_protector_strong,
5084 options::OPT_fstack_protector)) {
5085 if (A->getOption().matches(options::OPT_fstack_protector)) {
5086 StackProtectorLevel = std::max<unsigned>(
5087 LangOptions::SSPOn,
5088 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
5089 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
5090 StackProtectorLevel = LangOptions::SSPStrong;
5091 else if (A->getOption().matches(options::OPT_fstack_protector_all))
5092 StackProtectorLevel = LangOptions::SSPReq;
5093 } else {
5094 StackProtectorLevel =
5095 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
5096 }
5097 if (StackProtectorLevel) {
5098 CmdArgs.push_back("-stack-protector");
5099 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
5100 }
5101
5102 // --param ssp-buffer-size=
5103 for (const Arg *A : Args.filtered(options::OPT__param)) {
5104 StringRef Str(A->getValue());
5105 if (Str.startswith("ssp-buffer-size=")) {
5106 if (StackProtectorLevel) {
5107 CmdArgs.push_back("-stack-protector-buffer-size");
5108 // FIXME: Verify the argument is a valid integer.
5109 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
5110 }
5111 A->claim();
5112 }
5113 }
5114
5115 // Translate -mstackrealign
5116 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5117 false))
5118 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5119
5120 if (Args.hasArg(options::OPT_mstack_alignment)) {
5121 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5122 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5123 }
5124
5125 if (Args.hasArg(options::OPT_mstack_probe_size)) {
5126 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5127
5128 if (!Size.empty())
5129 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5130 else
5131 CmdArgs.push_back("-mstack-probe-size=0");
5132 }
5133
5134 switch (getToolChain().getArch()) {
5135 case llvm::Triple::aarch64:
5136 case llvm::Triple::aarch64_be:
5137 case llvm::Triple::arm:
5138 case llvm::Triple::armeb:
5139 case llvm::Triple::thumb:
5140 case llvm::Triple::thumbeb:
5141 CmdArgs.push_back("-fallow-half-arguments-and-returns");
5142 break;
5143
5144 default:
5145 break;
5146 }
5147
5148 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5149 options::OPT_mno_restrict_it)) {
5150 if (A->getOption().matches(options::OPT_mrestrict_it)) {
5151 CmdArgs.push_back("-backend-option");
5152 CmdArgs.push_back("-arm-restrict-it");
5153 } else {
5154 CmdArgs.push_back("-backend-option");
5155 CmdArgs.push_back("-arm-no-restrict-it");
5156 }
5157 } else if (Triple.isOSWindows() &&
5158 (Triple.getArch() == llvm::Triple::arm ||
5159 Triple.getArch() == llvm::Triple::thumb)) {
5160 // Windows on ARM expects restricted IT blocks
5161 CmdArgs.push_back("-backend-option");
5162 CmdArgs.push_back("-arm-restrict-it");
5163 }
5164
5165 // Forward -cl options to -cc1
5166 if (Args.getLastArg(options::OPT_cl_opt_disable)) {
5167 CmdArgs.push_back("-cl-opt-disable");
5168 }
5169 if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
5170 CmdArgs.push_back("-cl-strict-aliasing");
5171 }
5172 if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
5173 CmdArgs.push_back("-cl-single-precision-constant");
5174 }
5175 if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
5176 CmdArgs.push_back("-cl-finite-math-only");
5177 }
5178 if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
5179 CmdArgs.push_back("-cl-kernel-arg-info");
5180 }
5181 if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
5182 CmdArgs.push_back("-cl-unsafe-math-optimizations");
5183 }
5184 if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
5185 CmdArgs.push_back("-cl-fast-relaxed-math");
5186 }
5187 if (Args.getLastArg(options::OPT_cl_mad_enable)) {
5188 CmdArgs.push_back("-cl-mad-enable");
5189 }
5190 if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
5191 CmdArgs.push_back("-cl-no-signed-zeros");
5192 }
5193 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
5194 std::string CLStdStr = "-cl-std=";
5195 CLStdStr += A->getValue();
5196 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
5197 }
5198 if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
5199 CmdArgs.push_back("-cl-denorms-are-zero");
5200 }
5201
5202 // Forward -f options with positive and negative forms; we translate
5203 // these by hand.
5204 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
5205 StringRef fname = A->getValue();
5206 if (!llvm::sys::fs::exists(fname))
5207 D.Diag(diag::err_drv_no_such_file) << fname;
5208 else
5209 A->render(Args, CmdArgs);
5210 }
5211
5212 // -fbuiltin is default unless -mkernel is used.
5213 bool UseBuiltins =
5214 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
5215 !Args.hasArg(options::OPT_mkernel));
5216 if (!UseBuiltins)
5217 CmdArgs.push_back("-fno-builtin");
5218
5219 // -ffreestanding implies -fno-builtin.
5220 if (Args.hasArg(options::OPT_ffreestanding))
5221 UseBuiltins = false;
5222
5223 // Process the -fno-builtin-* options.
5224 for (const auto &Arg : Args) {
5225 const Option &O = Arg->getOption();
5226 if (!O.matches(options::OPT_fno_builtin_))
5227 continue;
5228
5229 Arg->claim();
5230 // If -fno-builtin is specified, then there's no need to pass the option to
5231 // the frontend.
5232 if (!UseBuiltins)
5233 continue;
5234
5235 StringRef FuncName = Arg->getValue();
5236 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
5237 }
5238
5239 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5240 options::OPT_fno_assume_sane_operator_new))
5241 CmdArgs.push_back("-fno-assume-sane-operator-new");
5242
5243 // -fblocks=0 is default.
5244 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
5245 getToolChain().IsBlocksDefault()) ||
5246 (Args.hasArg(options::OPT_fgnu_runtime) &&
5247 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
5248 !Args.hasArg(options::OPT_fno_blocks))) {
5249 CmdArgs.push_back("-fblocks");
5250
5251 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
5252 !getToolChain().hasBlocksRuntime())
5253 CmdArgs.push_back("-fblocks-runtime-optional");
5254 }
5255
5256 // -fmodules enables the use of precompiled modules (off by default).
5257 // Users can pass -fno-cxx-modules to turn off modules support for
5258 // C++/Objective-C++ programs.
5259 bool HaveModules = false;
5260 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
5261 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
5262 options::OPT_fno_cxx_modules, true);
5263 if (AllowedInCXX || !types::isCXX(InputType)) {
5264 CmdArgs.push_back("-fmodules");
5265 HaveModules = true;
5266 }
5267 }
5268
5269 // -fmodule-maps enables implicit reading of module map files. By default,
5270 // this is enabled if we are using precompiled modules.
5271 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
5272 options::OPT_fno_implicit_module_maps, HaveModules)) {
5273 CmdArgs.push_back("-fimplicit-module-maps");
5274 }
5275
5276 // -fmodules-decluse checks that modules used are declared so (off by
5277 // default).
5278 if (Args.hasFlag(options::OPT_fmodules_decluse,
5279 options::OPT_fno_modules_decluse, false)) {
5280 CmdArgs.push_back("-fmodules-decluse");
5281 }
5282
5283 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
5284 // all #included headers are part of modules.
5285 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
5286 options::OPT_fno_modules_strict_decluse, false)) {
5287 CmdArgs.push_back("-fmodules-strict-decluse");
5288 }
5289
5290 // -fno-implicit-modules turns off implicitly compiling modules on demand.
5291 if (!Args.hasFlag(options::OPT_fimplicit_modules,
5292 options::OPT_fno_implicit_modules)) {
5293 CmdArgs.push_back("-fno-implicit-modules");
5294 } else if (HaveModules) {
5295 // -fmodule-cache-path specifies where our implicitly-built module files
5296 // should be written.
5297 SmallString<128> Path;
5298 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
5299 Path = A->getValue();
5300 if (C.isForDiagnostics()) {
5301 // When generating crash reports, we want to emit the modules along with
5302 // the reproduction sources, so we ignore any provided module path.
5303 Path = Output.getFilename();
5304 llvm::sys::path::replace_extension(Path, ".cache");
5305 llvm::sys::path::append(Path, "modules");
5306 } else if (Path.empty()) {
5307 // No module path was provided: use the default.
5308 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
5309 llvm::sys::path::append(Path, "org.llvm.clang.");
5310 appendUserToPath(Path);
5311 llvm::sys::path::append(Path, "ModuleCache");
5312 }
5313 const char Arg[] = "-fmodules-cache-path=";
5314 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
5315 CmdArgs.push_back(Args.MakeArgString(Path));
5316 }
5317
5318 // -fmodule-name specifies the module that is currently being built (or
5319 // used for header checking by -fmodule-maps).
5320 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
5321
5322 // -fmodule-map-file can be used to specify files containing module
5323 // definitions.
5324 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
5325
5326 // -fmodule-file can be used to specify files containing precompiled modules.
5327 if (HaveModules)
5328 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
5329 else
5330 Args.ClaimAllArgs(options::OPT_fmodule_file);
5331
5332 // When building modules and generating crashdumps, we need to dump a module
5333 // dependency VFS alongside the output.
5334 if (HaveModules && C.isForDiagnostics()) {
5335 SmallString<128> VFSDir(Output.getFilename());
5336 llvm::sys::path::replace_extension(VFSDir, ".cache");
5337 // Add the cache directory as a temp so the crash diagnostics pick it up.
5338 C.addTempFile(Args.MakeArgString(VFSDir));
5339
5340 llvm::sys::path::append(VFSDir, "vfs");
5341 CmdArgs.push_back("-module-dependency-dir");
5342 CmdArgs.push_back(Args.MakeArgString(VFSDir));
5343 }
5344
5345 if (HaveModules)
5346 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
5347
5348 // Pass through all -fmodules-ignore-macro arguments.
5349 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
5350 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
5351 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
5352
5353 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
5354
5355 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
5356 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
5357 D.Diag(diag::err_drv_argument_not_allowed_with)
5358 << A->getAsString(Args) << "-fbuild-session-timestamp";
5359
5360 llvm::sys::fs::file_status Status;
5361 if (llvm::sys::fs::status(A->getValue(), Status))
5362 D.Diag(diag::err_drv_no_such_file) << A->getValue();
5363 CmdArgs.push_back(Args.MakeArgString(
5364 "-fbuild-session-timestamp=" +
5365 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
5366 }
5367
5368 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
5369 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
5370 options::OPT_fbuild_session_file))
5371 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
5372
5373 Args.AddLastArg(CmdArgs,
5374 options::OPT_fmodules_validate_once_per_build_session);
5375 }
5376
5377 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
5378
5379 // -faccess-control is default.
5380 if (Args.hasFlag(options::OPT_fno_access_control,
5381 options::OPT_faccess_control, false))
5382 CmdArgs.push_back("-fno-access-control");
5383
5384 // -felide-constructors is the default.
5385 if (Args.hasFlag(options::OPT_fno_elide_constructors,
5386 options::OPT_felide_constructors, false))
5387 CmdArgs.push_back("-fno-elide-constructors");
5388
5389 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
5390
5391 if (KernelOrKext || (types::isCXX(InputType) &&
5392 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
5393 RTTIMode == ToolChain::RM_DisabledImplicitly)))
5394 CmdArgs.push_back("-fno-rtti");
5395
5396 // -fshort-enums=0 is default for all architectures except Hexagon.
5397 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
5398 getToolChain().getArch() == llvm::Triple::hexagon))
5399 CmdArgs.push_back("-fshort-enums");
5400
5401 // -fsigned-char is default.
5402 if (Arg *A = Args.getLastArg(
5403 options::OPT_fsigned_char, options::OPT_fno_signed_char,
5404 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
5405 if (A->getOption().matches(options::OPT_funsigned_char) ||
5406 A->getOption().matches(options::OPT_fno_signed_char)) {
5407 CmdArgs.push_back("-fno-signed-char");
5408 }
5409 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
5410 CmdArgs.push_back("-fno-signed-char");
5411 }
5412
5413 // -fuse-cxa-atexit is default.
5414 if (!Args.hasFlag(
5415 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
5416 !IsWindowsCygnus && !IsWindowsGNU &&
5417 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
5418 getToolChain().getArch() != llvm::Triple::hexagon &&
5419 getToolChain().getArch() != llvm::Triple::xcore &&
5420 ((getToolChain().getTriple().getVendor() !=
5421 llvm::Triple::MipsTechnologies) ||
5422 getToolChain().getTriple().hasEnvironment())) ||
5423 KernelOrKext)
5424 CmdArgs.push_back("-fno-use-cxa-atexit");
5425
5426 // -fms-extensions=0 is default.
5427 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
5428 IsWindowsMSVC))
5429 CmdArgs.push_back("-fms-extensions");
5430
5431 // -fno-use-line-directives is default.
5432 if (Args.hasFlag(options::OPT_fuse_line_directives,
5433 options::OPT_fno_use_line_directives, false))
5434 CmdArgs.push_back("-fuse-line-directives");
5435
5436 // -fms-compatibility=0 is default.
5437 if (Args.hasFlag(options::OPT_fms_compatibility,
5438 options::OPT_fno_ms_compatibility,
5439 (IsWindowsMSVC &&
5440 Args.hasFlag(options::OPT_fms_extensions,
5441 options::OPT_fno_ms_extensions, true))))
5442 CmdArgs.push_back("-fms-compatibility");
5443
5444 // -fms-compatibility-version=18.00 is default.
5445 VersionTuple MSVT = visualstudio::getMSVCVersion(
5446 &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
5447 if (!MSVT.empty())
5448 CmdArgs.push_back(
5449 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5450
5451 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5452 if (ImplyVCPPCXXVer) {
5453 StringRef LanguageStandard;
5454 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
5455 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
5456 .Case("c++14", "-std=c++14")
5457 .Case("c++latest", "-std=c++1z")
5458 .Default("");
5459 if (LanguageStandard.empty())
5460 D.Diag(clang::diag::warn_drv_unused_argument)
5461 << StdArg->getAsString(Args);
5462 }
5463
5464 if (LanguageStandard.empty()) {
5465 if (IsMSVC2015Compatible)
5466 LanguageStandard = "-std=c++14";
5467 else
5468 LanguageStandard = "-std=c++11";
5469 }
5470
5471 CmdArgs.push_back(LanguageStandard.data());
5472 }
5473
5474 // -fno-borland-extensions is default.
5475 if (Args.hasFlag(options::OPT_fborland_extensions,
5476 options::OPT_fno_borland_extensions, false))
5477 CmdArgs.push_back("-fborland-extensions");
5478
5479 // -fno-declspec is default, except for PS4.
5480 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5481 getToolChain().getTriple().isPS4()))
5482 CmdArgs.push_back("-fdeclspec");
5483 else if (Args.hasArg(options::OPT_fno_declspec))
5484 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5485
5486 // -fthreadsafe-static is default, except for MSVC compatibility versions less
5487 // than 19.
5488 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5489 options::OPT_fno_threadsafe_statics,
5490 !IsWindowsMSVC || IsMSVC2015Compatible))
5491 CmdArgs.push_back("-fno-threadsafe-statics");
5492
5493 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5494 // needs it.
5495 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5496 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5497 CmdArgs.push_back("-fdelayed-template-parsing");
5498
5499 // -fgnu-keywords default varies depending on language; only pass if
5500 // specified.
5501 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5502 options::OPT_fno_gnu_keywords))
5503 A->render(Args, CmdArgs);
5504
5505 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5506 false))
5507 CmdArgs.push_back("-fgnu89-inline");
5508
5509 if (Args.hasArg(options::OPT_fno_inline))
5510 CmdArgs.push_back("-fno-inline");
5511
5512 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
5513 options::OPT_finline_hint_functions,
5514 options::OPT_fno_inline_functions))
5515 InlineArg->render(Args, CmdArgs);
5516
5517 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5518
5519 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5520 // legacy is the default. Except for deployment taget of 10.5,
5521 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5522 // gets ignored silently.
5523 if (objcRuntime.isNonFragile()) {
5524 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5525 options::OPT_fno_objc_legacy_dispatch,
5526 objcRuntime.isLegacyDispatchDefaultForArch(
5527 getToolChain().getArch()))) {
5528 if (getToolChain().UseObjCMixedDispatch())
5529 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5530 else
5531 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5532 }
5533 }
5534
5535 // When ObjectiveC legacy runtime is in effect on MacOSX,
5536 // turn on the option to do Array/Dictionary subscripting
5537 // by default.
5538 if (getToolChain().getArch() == llvm::Triple::x86 &&
5539 getToolChain().getTriple().isMacOSX() &&
5540 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5541 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5542 objcRuntime.isNeXTFamily())
5543 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5544
5545 // -fencode-extended-block-signature=1 is default.
5546 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5547 CmdArgs.push_back("-fencode-extended-block-signature");
5548 }
5549
5550 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5551 // NOTE: This logic is duplicated in ToolChains.cpp.
5552 bool ARC = isObjCAutoRefCount(Args);
5553 if (ARC) {
5554 getToolChain().CheckObjCARC();
5555
5556 CmdArgs.push_back("-fobjc-arc");
5557
5558 // FIXME: It seems like this entire block, and several around it should be
5559 // wrapped in isObjC, but for now we just use it here as this is where it
5560 // was being used previously.
5561 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5562 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5563 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5564 else
5565 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5566 }
5567
5568 // Allow the user to enable full exceptions code emission.
5569 // We define off for Objective-CC, on for Objective-C++.
5570 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5571 options::OPT_fno_objc_arc_exceptions,
5572 /*default*/ types::isCXX(InputType)))
5573 CmdArgs.push_back("-fobjc-arc-exceptions");
5574
5575 }
5576
5577 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5578 // rewriter.
5579 if (rewriteKind != RK_None)
5580 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5581
5582 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5583 // takes precedence.
5584 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5585 if (!GCArg)
5586 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5587 if (GCArg) {
5588 if (ARC) {
5589 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5590 } else if (getToolChain().SupportsObjCGC()) {
5591 GCArg->render(Args, CmdArgs);
5592 } else {
5593 // FIXME: We should move this to a hard error.
5594 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5595 }
5596 }
5597
5598 // Pass down -fobjc-weak or -fno-objc-weak if present.
5599 if (types::isObjC(InputType)) {
5600 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5601 options::OPT_fno_objc_weak);
5602 if (!WeakArg) {
5603 // nothing to do
5604 } else if (GCArg) {
5605 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5606 D.Diag(diag::err_objc_weak_with_gc);
5607 } else if (!objcRuntime.allowsWeak()) {
5608 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5609 D.Diag(diag::err_objc_weak_unsupported);
5610 } else {
5611 WeakArg->render(Args, CmdArgs);
5612 }
5613 }
5614
5615 if (Args.hasFlag(options::OPT_fapplication_extension,
5616 options::OPT_fno_application_extension, false))
5617 CmdArgs.push_back("-fapplication-extension");
5618
5619 // Handle GCC-style exception args.
5620 if (!C.getDriver().IsCLMode())
5621 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5622 CmdArgs);
5623
5624 if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
5625 getToolChain().UseSjLjExceptions(Args))
5626 CmdArgs.push_back("-fsjlj-exceptions");
5627
5628 // C++ "sane" operator new.
5629 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5630 options::OPT_fno_assume_sane_operator_new))
5631 CmdArgs.push_back("-fno-assume-sane-operator-new");
5632
5633 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5634 // most platforms.
5635 if (Args.hasFlag(options::OPT_fsized_deallocation,
5636 options::OPT_fno_sized_deallocation, false))
5637 CmdArgs.push_back("-fsized-deallocation");
5638
5639 // -fconstant-cfstrings is default, and may be subject to argument translation
5640 // on Darwin.
5641 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5642 options::OPT_fno_constant_cfstrings) ||
5643 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5644 options::OPT_mno_constant_cfstrings))
5645 CmdArgs.push_back("-fno-constant-cfstrings");
5646
5647 // -fshort-wchar default varies depending on platform; only
5648 // pass if specified.
5649 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5650 options::OPT_fno_short_wchar))
5651 A->render(Args, CmdArgs);
5652
5653 // -fno-pascal-strings is default, only pass non-default.
5654 if (Args.hasFlag(options::OPT_fpascal_strings,
5655 options::OPT_fno_pascal_strings, false))
5656 CmdArgs.push_back("-fpascal-strings");
5657
5658 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5659 // -fno-pack-struct doesn't apply to -fpack-struct=.
5660 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5661 std::string PackStructStr = "-fpack-struct=";
5662 PackStructStr += A->getValue();
5663 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5664 } else if (Args.hasFlag(options::OPT_fpack_struct,
5665 options::OPT_fno_pack_struct, false)) {
5666 CmdArgs.push_back("-fpack-struct=1");
5667 }
5668
5669 // Handle -fmax-type-align=N and -fno-type-align
5670 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5671 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5672 if (!SkipMaxTypeAlign) {
5673 std::string MaxTypeAlignStr = "-fmax-type-align=";
5674 MaxTypeAlignStr += A->getValue();
5675 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5676 }
5677 } else if (getToolChain().getTriple().isOSDarwin()) {
5678 if (!SkipMaxTypeAlign) {
5679 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5680 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5681 }
5682 }
5683
5684 // -fcommon is the default unless compiling kernel code or the target says so
5685 bool NoCommonDefault =
5686 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5687 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5688 !NoCommonDefault))
5689 CmdArgs.push_back("-fno-common");
5690
5691 // -fsigned-bitfields is default, and clang doesn't yet support
5692 // -funsigned-bitfields.
5693 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5694 options::OPT_funsigned_bitfields))
5695 D.Diag(diag::warn_drv_clang_unsupported)
5696 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5697
5698 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5699 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5700 D.Diag(diag::err_drv_clang_unsupported)
5701 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5702
5703 // -finput_charset=UTF-8 is default. Reject others
5704 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5705 StringRef value = inputCharset->getValue();
5706 if (value != "UTF-8")
5707 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5708 << value;
5709 }
5710
5711 // -fexec_charset=UTF-8 is default. Reject others
5712 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5713 StringRef value = execCharset->getValue();
5714 if (value != "UTF-8")
5715 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5716 << value;
5717 }
5718
5719 // -fcaret-diagnostics is default.
5720 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5721 options::OPT_fno_caret_diagnostics, true))
5722 CmdArgs.push_back("-fno-caret-diagnostics");
5723
5724 // -fdiagnostics-fixit-info is default, only pass non-default.
5725 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5726 options::OPT_fno_diagnostics_fixit_info))
5727 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5728
5729 // Enable -fdiagnostics-show-option by default.
5730 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5731 options::OPT_fno_diagnostics_show_option))
5732 CmdArgs.push_back("-fdiagnostics-show-option");
5733
5734 if (const Arg *A =
5735 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5736 CmdArgs.push_back("-fdiagnostics-show-category");
5737 CmdArgs.push_back(A->getValue());
5738 }
5739
5740 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5741 CmdArgs.push_back("-fdiagnostics-format");
5742 CmdArgs.push_back(A->getValue());
5743 }
5744
5745 if (Arg *A = Args.getLastArg(
5746 options::OPT_fdiagnostics_show_note_include_stack,
5747 options::OPT_fno_diagnostics_show_note_include_stack)) {
5748 if (A->getOption().matches(
5749 options::OPT_fdiagnostics_show_note_include_stack))
5750 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5751 else
5752 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5753 }
5754
5755 // Color diagnostics are parsed by the driver directly from argv
5756 // and later re-parsed to construct this job; claim any possible
5757 // color diagnostic here to avoid warn_drv_unused_argument and
5758 // diagnose bad OPT_fdiagnostics_color_EQ values.
5759 for (Arg *A : Args) {
5760 const Option &O = A->getOption();
5761 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5762 !O.matches(options::OPT_fdiagnostics_color) &&
5763 !O.matches(options::OPT_fno_color_diagnostics) &&
5764 !O.matches(options::OPT_fno_diagnostics_color) &&
5765 !O.matches(options::OPT_fdiagnostics_color_EQ))
5766 continue;
5767 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
5768 StringRef Value(A->getValue());
5769 if (Value != "always" && Value != "never" && Value != "auto")
5770 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5771 << ("-fdiagnostics-color=" + Value).str();
5772 }
5773 A->claim();
5774 }
5775 if (D.getDiags().getDiagnosticOptions().ShowColors)
5776 CmdArgs.push_back("-fcolor-diagnostics");
5777
5778 if (Args.hasArg(options::OPT_fansi_escape_codes))
5779 CmdArgs.push_back("-fansi-escape-codes");
5780
5781 if (!Args.hasFlag(options::OPT_fshow_source_location,
5782 options::OPT_fno_show_source_location))
5783 CmdArgs.push_back("-fno-show-source-location");
5784
5785 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5786 true))
5787 CmdArgs.push_back("-fno-show-column");
5788
5789 if (!Args.hasFlag(options::OPT_fspell_checking,
5790 options::OPT_fno_spell_checking))
5791 CmdArgs.push_back("-fno-spell-checking");
5792
5793 // -fno-asm-blocks is default.
5794 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5795 false))
5796 CmdArgs.push_back("-fasm-blocks");
5797
5798 // -fgnu-inline-asm is default.
5799 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5800 options::OPT_fno_gnu_inline_asm, true))
5801 CmdArgs.push_back("-fno-gnu-inline-asm");
5802
5803 // Enable vectorization per default according to the optimization level
5804 // selected. For optimization levels that want vectorization we use the alias
5805 // option to simplify the hasFlag logic.
5806 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5807 OptSpecifier VectorizeAliasOption =
5808 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5809 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5810 options::OPT_fno_vectorize, EnableVec))
5811 CmdArgs.push_back("-vectorize-loops");
5812
5813 // -fslp-vectorize is enabled based on the optimization level selected.
5814 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5815 OptSpecifier SLPVectAliasOption =
5816 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5817 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5818 options::OPT_fno_slp_vectorize, EnableSLPVec))
5819 CmdArgs.push_back("-vectorize-slp");
5820
5821 // -fno-slp-vectorize-aggressive is default.
5822 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5823 options::OPT_fno_slp_vectorize_aggressive, false))
5824 CmdArgs.push_back("-vectorize-slp-aggressive");
5825
5826 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5827 A->render(Args, CmdArgs);
5828
5829 if (Arg *A = Args.getLastArg(
5830 options::OPT_fsanitize_undefined_strip_path_components_EQ))
5831 A->render(Args, CmdArgs);
5832
5833 // -fdollars-in-identifiers default varies depending on platform and
5834 // language; only pass if specified.
5835 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5836 options::OPT_fno_dollars_in_identifiers)) {
5837 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5838 CmdArgs.push_back("-fdollars-in-identifiers");
5839 else
5840 CmdArgs.push_back("-fno-dollars-in-identifiers");
5841 }
5842
5843 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5844 // practical purposes.
5845 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5846 options::OPT_fno_unit_at_a_time)) {
5847 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5848 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5849 }
5850
5851 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5852 options::OPT_fno_apple_pragma_pack, false))
5853 CmdArgs.push_back("-fapple-pragma-pack");
5854
5855 // le32-specific flags:
5856 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5857 // by default.
5858 if (getToolChain().getArch() == llvm::Triple::le32) {
5859 CmdArgs.push_back("-fno-math-builtin");
5860 }
5861
5862 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5863 //
5864 // FIXME: Now that PR4941 has been fixed this can be enabled.
5865 #if 0
5866 if (getToolChain().getTriple().isOSDarwin() &&
5867 (getToolChain().getArch() == llvm::Triple::arm ||
5868 getToolChain().getArch() == llvm::Triple::thumb)) {
5869 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5870 CmdArgs.push_back("-fno-builtin-strcat");
5871 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5872 CmdArgs.push_back("-fno-builtin-strcpy");
5873 }
5874 #endif
5875
5876 // Enable rewrite includes if the user's asked for it or if we're generating
5877 // diagnostics.
5878 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5879 // nice to enable this when doing a crashdump for modules as well.
5880 if (Args.hasFlag(options::OPT_frewrite_includes,
5881 options::OPT_fno_rewrite_includes, false) ||
5882 (C.isForDiagnostics() && !HaveModules))
5883 CmdArgs.push_back("-frewrite-includes");
5884
5885 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5886 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5887 options::OPT_traditional_cpp)) {
5888 if (isa<PreprocessJobAction>(JA))
5889 CmdArgs.push_back("-traditional-cpp");
5890 else
5891 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5892 }
5893
5894 Args.AddLastArg(CmdArgs, options::OPT_dM);
5895 Args.AddLastArg(CmdArgs, options::OPT_dD);
5896
5897 // Handle serialized diagnostics.
5898 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5899 CmdArgs.push_back("-serialize-diagnostic-file");
5900 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5901 }
5902
5903 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5904 CmdArgs.push_back("-fretain-comments-from-system-headers");
5905
5906 // Forward -fcomment-block-commands to -cc1.
5907 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5908 // Forward -fparse-all-comments to -cc1.
5909 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5910
5911 // Turn -fplugin=name.so into -load name.so
5912 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5913 CmdArgs.push_back("-load");
5914 CmdArgs.push_back(A->getValue());
5915 A->claim();
5916 }
5917
5918 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5919 // parser.
5920 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5921 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5922 A->claim();
5923
5924 // We translate this by hand to the -cc1 argument, since nightly test uses
5925 // it and developers have been trained to spell it with -mllvm.
5926 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5927 CmdArgs.push_back("-disable-llvm-optzns");
5928 } else
5929 A->render(Args, CmdArgs);
5930 }
5931
5932 // With -save-temps, we want to save the unoptimized bitcode output from the
5933 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5934 // by the frontend.
5935 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5936 // has slightly different breakdown between stages.
5937 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5938 // pristine IR generated by the frontend. Ideally, a new compile action should
5939 // be added so both IR can be captured.
5940 if (C.getDriver().isSaveTempsEnabled() &&
5941 !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
5942 CmdArgs.push_back("-disable-llvm-passes");
5943
5944 if (Output.getType() == types::TY_Dependencies) {
5945 // Handled with other dependency code.
5946 } else if (Output.isFilename()) {
5947 CmdArgs.push_back("-o");
5948 CmdArgs.push_back(Output.getFilename());
5949 } else {
5950 assert(Output.isNothing() && "Invalid output.");
5951 }
5952
5953 addDashXForInput(Args, Input, CmdArgs);
5954
5955 if (Input.isFilename())
5956 CmdArgs.push_back(Input.getFilename());
5957 else
5958 Input.getInputArg().renderAsInput(Args, CmdArgs);
5959
5960 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5961
5962 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5963
5964 // Optionally embed the -cc1 level arguments into the debug info, for build
5965 // analysis.
5966 if (getToolChain().UseDwarfDebugFlags()) {
5967 ArgStringList OriginalArgs;
5968 for (const auto &Arg : Args)
5969 Arg->render(Args, OriginalArgs);
5970
5971 SmallString<256> Flags;
5972 Flags += Exec;
5973 for (const char *OriginalArg : OriginalArgs) {
5974 SmallString<128> EscapedArg;
5975 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5976 Flags += " ";
5977 Flags += EscapedArg;
5978 }
5979 CmdArgs.push_back("-dwarf-debug-flags");
5980 CmdArgs.push_back(Args.MakeArgString(Flags));
5981 }
5982
5983 // Add the split debug info name to the command lines here so we
5984 // can propagate it to the backend.
5985 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5986 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5987 isa<BackendJobAction>(JA));
5988 const char *SplitDwarfOut;
5989 if (SplitDwarf) {
5990 CmdArgs.push_back("-split-dwarf-file");
5991 SplitDwarfOut = SplitDebugName(Args, Input);
5992 CmdArgs.push_back(SplitDwarfOut);
5993 }
5994
5995 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5996 // Include them with -fcuda-include-gpubinary.
5997 if (IsCuda && Inputs.size() > 1)
5998 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5999 CmdArgs.push_back("-fcuda-include-gpubinary");
6000 CmdArgs.push_back(I->getFilename());
6001 }
6002
6003 bool WholeProgramVTables =
6004 Args.hasFlag(options::OPT_fwhole_program_vtables,
6005 options::OPT_fno_whole_program_vtables, false);
6006 if (WholeProgramVTables) {
6007 if (!D.isUsingLTO())
6008 D.Diag(diag::err_drv_argument_only_allowed_with)
6009 << "-fwhole-program-vtables"
6010 << "-flto";
6011 CmdArgs.push_back("-fwhole-program-vtables");
6012 }
6013
6014 // Finally add the compile command to the compilation.
6015 if (Args.hasArg(options::OPT__SLASH_fallback) &&
6016 Output.getType() == types::TY_Object &&
6017 (InputType == types::TY_C || InputType == types::TY_CXX)) {
6018 auto CLCommand =
6019 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
6020 C.addCommand(llvm::make_unique<FallbackCommand>(
6021 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
6022 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
6023 isa<PrecompileJobAction>(JA)) {
6024 // In /fallback builds, run the main compilation even if the pch generation
6025 // fails, so that the main compilation's fallback to cl.exe runs.
6026 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
6027 CmdArgs, Inputs));
6028 } else {
6029 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6030 }
6031
6032 // Handle the debug info splitting at object creation time if we're
6033 // creating an object.
6034 // TODO: Currently only works on linux with newer objcopy.
6035 if (SplitDwarf && Output.getType() == types::TY_Object)
6036 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
6037
6038 if (Arg *A = Args.getLastArg(options::OPT_pg))
6039 if (Args.hasArg(options::OPT_fomit_frame_pointer))
6040 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6041 << A->getAsString(Args);
6042
6043 // Claim some arguments which clang supports automatically.
6044
6045 // -fpch-preprocess is used with gcc to add a special marker in the output to
6046 // include the PCH file. Clang's PTH solution is completely transparent, so we
6047 // do not need to deal with it at all.
6048 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6049
6050 // Claim some arguments which clang doesn't support, but we don't
6051 // care to warn the user about.
6052 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6053 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6054
6055 // Disable warnings for clang -E -emit-llvm foo.c
6056 Args.ClaimAllArgs(options::OPT_emit_llvm);
6057 }
6058
6059 /// Add options related to the Objective-C runtime/ABI.
6060 ///
6061 /// Returns true if the runtime is non-fragile.
AddObjCRuntimeArgs(const ArgList & args,ArgStringList & cmdArgs,RewriteKind rewriteKind) const6062 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6063 ArgStringList &cmdArgs,
6064 RewriteKind rewriteKind) const {
6065 // Look for the controlling runtime option.
6066 Arg *runtimeArg =
6067 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6068 options::OPT_fobjc_runtime_EQ);
6069
6070 // Just forward -fobjc-runtime= to the frontend. This supercedes
6071 // options about fragility.
6072 if (runtimeArg &&
6073 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6074 ObjCRuntime runtime;
6075 StringRef value = runtimeArg->getValue();
6076 if (runtime.tryParse(value)) {
6077 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6078 << value;
6079 }
6080
6081 runtimeArg->render(args, cmdArgs);
6082 return runtime;
6083 }
6084
6085 // Otherwise, we'll need the ABI "version". Version numbers are
6086 // slightly confusing for historical reasons:
6087 // 1 - Traditional "fragile" ABI
6088 // 2 - Non-fragile ABI, version 1
6089 // 3 - Non-fragile ABI, version 2
6090 unsigned objcABIVersion = 1;
6091 // If -fobjc-abi-version= is present, use that to set the version.
6092 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6093 StringRef value = abiArg->getValue();
6094 if (value == "1")
6095 objcABIVersion = 1;
6096 else if (value == "2")
6097 objcABIVersion = 2;
6098 else if (value == "3")
6099 objcABIVersion = 3;
6100 else
6101 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6102 } else {
6103 // Otherwise, determine if we are using the non-fragile ABI.
6104 bool nonFragileABIIsDefault =
6105 (rewriteKind == RK_NonFragile ||
6106 (rewriteKind == RK_None &&
6107 getToolChain().IsObjCNonFragileABIDefault()));
6108 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6109 options::OPT_fno_objc_nonfragile_abi,
6110 nonFragileABIIsDefault)) {
6111 // Determine the non-fragile ABI version to use.
6112 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6113 unsigned nonFragileABIVersion = 1;
6114 #else
6115 unsigned nonFragileABIVersion = 2;
6116 #endif
6117
6118 if (Arg *abiArg =
6119 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6120 StringRef value = abiArg->getValue();
6121 if (value == "1")
6122 nonFragileABIVersion = 1;
6123 else if (value == "2")
6124 nonFragileABIVersion = 2;
6125 else
6126 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6127 << value;
6128 }
6129
6130 objcABIVersion = 1 + nonFragileABIVersion;
6131 } else {
6132 objcABIVersion = 1;
6133 }
6134 }
6135
6136 // We don't actually care about the ABI version other than whether
6137 // it's non-fragile.
6138 bool isNonFragile = objcABIVersion != 1;
6139
6140 // If we have no runtime argument, ask the toolchain for its default runtime.
6141 // However, the rewriter only really supports the Mac runtime, so assume that.
6142 ObjCRuntime runtime;
6143 if (!runtimeArg) {
6144 switch (rewriteKind) {
6145 case RK_None:
6146 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6147 break;
6148 case RK_Fragile:
6149 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
6150 break;
6151 case RK_NonFragile:
6152 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6153 break;
6154 }
6155
6156 // -fnext-runtime
6157 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
6158 // On Darwin, make this use the default behavior for the toolchain.
6159 if (getToolChain().getTriple().isOSDarwin()) {
6160 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
6161
6162 // Otherwise, build for a generic macosx port.
6163 } else {
6164 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
6165 }
6166
6167 // -fgnu-runtime
6168 } else {
6169 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
6170 // Legacy behaviour is to target the gnustep runtime if we are in
6171 // non-fragile mode or the GCC runtime in fragile mode.
6172 if (isNonFragile)
6173 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
6174 else
6175 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
6176 }
6177
6178 cmdArgs.push_back(
6179 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
6180 return runtime;
6181 }
6182
maybeConsumeDash(const std::string & EH,size_t & I)6183 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
6184 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
6185 I += HaveDash;
6186 return !HaveDash;
6187 }
6188
6189 namespace {
6190 struct EHFlags {
6191 bool Synch = false;
6192 bool Asynch = false;
6193 bool NoUnwindC = false;
6194 };
6195 } // end anonymous namespace
6196
6197 /// /EH controls whether to run destructor cleanups when exceptions are
6198 /// thrown. There are three modifiers:
6199 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
6200 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
6201 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
6202 /// - c: Assume that extern "C" functions are implicitly nounwind.
6203 /// The default is /EHs-c-, meaning cleanups are disabled.
parseClangCLEHFlags(const Driver & D,const ArgList & Args)6204 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
6205 EHFlags EH;
6206
6207 std::vector<std::string> EHArgs =
6208 Args.getAllArgValues(options::OPT__SLASH_EH);
6209 for (auto EHVal : EHArgs) {
6210 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
6211 switch (EHVal[I]) {
6212 case 'a':
6213 EH.Asynch = maybeConsumeDash(EHVal, I);
6214 if (EH.Asynch)
6215 EH.Synch = false;
6216 continue;
6217 case 'c':
6218 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
6219 continue;
6220 case 's':
6221 EH.Synch = maybeConsumeDash(EHVal, I);
6222 if (EH.Synch)
6223 EH.Asynch = false;
6224 continue;
6225 default:
6226 break;
6227 }
6228 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
6229 break;
6230 }
6231 }
6232 // The /GX, /GX- flags are only processed if there are not /EH flags.
6233 // The default is that /GX is not specified.
6234 if (EHArgs.empty() &&
6235 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
6236 /*default=*/false)) {
6237 EH.Synch = true;
6238 EH.NoUnwindC = true;
6239 }
6240
6241 return EH;
6242 }
6243
AddClangCLArgs(const ArgList & Args,types::ID InputType,ArgStringList & CmdArgs,codegenoptions::DebugInfoKind * DebugInfoKind,bool * EmitCodeView) const6244 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
6245 ArgStringList &CmdArgs,
6246 codegenoptions::DebugInfoKind *DebugInfoKind,
6247 bool *EmitCodeView) const {
6248 unsigned RTOptionID = options::OPT__SLASH_MT;
6249
6250 if (Args.hasArg(options::OPT__SLASH_LDd))
6251 // The /LDd option implies /MTd. The dependent lib part can be overridden,
6252 // but defining _DEBUG is sticky.
6253 RTOptionID = options::OPT__SLASH_MTd;
6254
6255 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
6256 RTOptionID = A->getOption().getID();
6257
6258 StringRef FlagForCRT;
6259 switch (RTOptionID) {
6260 case options::OPT__SLASH_MD:
6261 if (Args.hasArg(options::OPT__SLASH_LDd))
6262 CmdArgs.push_back("-D_DEBUG");
6263 CmdArgs.push_back("-D_MT");
6264 CmdArgs.push_back("-D_DLL");
6265 FlagForCRT = "--dependent-lib=msvcrt";
6266 break;
6267 case options::OPT__SLASH_MDd:
6268 CmdArgs.push_back("-D_DEBUG");
6269 CmdArgs.push_back("-D_MT");
6270 CmdArgs.push_back("-D_DLL");
6271 FlagForCRT = "--dependent-lib=msvcrtd";
6272 break;
6273 case options::OPT__SLASH_MT:
6274 if (Args.hasArg(options::OPT__SLASH_LDd))
6275 CmdArgs.push_back("-D_DEBUG");
6276 CmdArgs.push_back("-D_MT");
6277 CmdArgs.push_back("-flto-visibility-public-std");
6278 FlagForCRT = "--dependent-lib=libcmt";
6279 break;
6280 case options::OPT__SLASH_MTd:
6281 CmdArgs.push_back("-D_DEBUG");
6282 CmdArgs.push_back("-D_MT");
6283 CmdArgs.push_back("-flto-visibility-public-std");
6284 FlagForCRT = "--dependent-lib=libcmtd";
6285 break;
6286 default:
6287 llvm_unreachable("Unexpected option ID.");
6288 }
6289
6290 if (Args.hasArg(options::OPT__SLASH_Zl)) {
6291 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
6292 } else {
6293 CmdArgs.push_back(FlagForCRT.data());
6294
6295 // This provides POSIX compatibility (maps 'open' to '_open'), which most
6296 // users want. The /Za flag to cl.exe turns this off, but it's not
6297 // implemented in clang.
6298 CmdArgs.push_back("--dependent-lib=oldnames");
6299 }
6300
6301 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
6302 // would produce interleaved output, so ignore /showIncludes in such cases.
6303 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
6304 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
6305 A->render(Args, CmdArgs);
6306
6307 // This controls whether or not we emit RTTI data for polymorphic types.
6308 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
6309 /*default=*/false))
6310 CmdArgs.push_back("-fno-rtti-data");
6311
6312 // This controls whether or not we emit stack-protector instrumentation.
6313 // In MSVC, Buffer Security Check (/GS) is on by default.
6314 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
6315 /*default=*/true)) {
6316 CmdArgs.push_back("-stack-protector");
6317 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
6318 }
6319
6320 // Emit CodeView if -Z7 or -Zd are present.
6321 if (Arg *DebugInfoArg =
6322 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd)) {
6323 *EmitCodeView = true;
6324 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
6325 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
6326 else
6327 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
6328 CmdArgs.push_back("-gcodeview");
6329 } else {
6330 *EmitCodeView = false;
6331 }
6332
6333 const Driver &D = getToolChain().getDriver();
6334 EHFlags EH = parseClangCLEHFlags(D, Args);
6335 if (EH.Synch || EH.Asynch) {
6336 if (types::isCXX(InputType))
6337 CmdArgs.push_back("-fcxx-exceptions");
6338 CmdArgs.push_back("-fexceptions");
6339 }
6340 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
6341 CmdArgs.push_back("-fexternc-nounwind");
6342
6343 // /EP should expand to -E -P.
6344 if (Args.hasArg(options::OPT__SLASH_EP)) {
6345 CmdArgs.push_back("-E");
6346 CmdArgs.push_back("-P");
6347 }
6348
6349 unsigned VolatileOptionID;
6350 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
6351 getToolChain().getArch() == llvm::Triple::x86)
6352 VolatileOptionID = options::OPT__SLASH_volatile_ms;
6353 else
6354 VolatileOptionID = options::OPT__SLASH_volatile_iso;
6355
6356 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
6357 VolatileOptionID = A->getOption().getID();
6358
6359 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
6360 CmdArgs.push_back("-fms-volatile");
6361
6362 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
6363 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
6364 if (MostGeneralArg && BestCaseArg)
6365 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6366 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
6367
6368 if (MostGeneralArg) {
6369 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
6370 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
6371 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
6372
6373 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
6374 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
6375 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
6376 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
6377 << FirstConflict->getAsString(Args)
6378 << SecondConflict->getAsString(Args);
6379
6380 if (SingleArg)
6381 CmdArgs.push_back("-fms-memptr-rep=single");
6382 else if (MultipleArg)
6383 CmdArgs.push_back("-fms-memptr-rep=multiple");
6384 else
6385 CmdArgs.push_back("-fms-memptr-rep=virtual");
6386 }
6387
6388 if (Args.getLastArg(options::OPT__SLASH_Gd))
6389 CmdArgs.push_back("-fdefault-calling-conv=cdecl");
6390 else if (Args.getLastArg(options::OPT__SLASH_Gr))
6391 CmdArgs.push_back("-fdefault-calling-conv=fastcall");
6392 else if (Args.getLastArg(options::OPT__SLASH_Gz))
6393 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
6394 else if (Args.getLastArg(options::OPT__SLASH_Gv))
6395 CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
6396
6397 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
6398 A->render(Args, CmdArgs);
6399
6400 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
6401 CmdArgs.push_back("-fdiagnostics-format");
6402 if (Args.hasArg(options::OPT__SLASH_fallback))
6403 CmdArgs.push_back("msvc-fallback");
6404 else
6405 CmdArgs.push_back("msvc");
6406 }
6407 }
6408
getCLFallback() const6409 visualstudio::Compiler *Clang::getCLFallback() const {
6410 if (!CLFallback)
6411 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
6412 return CLFallback.get();
6413 }
6414
AddMIPSTargetArgs(const ArgList & Args,ArgStringList & CmdArgs) const6415 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6416 ArgStringList &CmdArgs) const {
6417 StringRef CPUName;
6418 StringRef ABIName;
6419 const llvm::Triple &Triple = getToolChain().getTriple();
6420 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6421
6422 CmdArgs.push_back("-target-abi");
6423 CmdArgs.push_back(ABIName.data());
6424 }
6425
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6426 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6427 const InputInfo &Output, const InputInfoList &Inputs,
6428 const ArgList &Args,
6429 const char *LinkingOutput) const {
6430 ArgStringList CmdArgs;
6431
6432 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6433 const InputInfo &Input = Inputs[0];
6434
6435 std::string TripleStr =
6436 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
6437 const llvm::Triple Triple(TripleStr);
6438
6439 // Don't warn about "clang -w -c foo.s"
6440 Args.ClaimAllArgs(options::OPT_w);
6441 // and "clang -emit-llvm -c foo.s"
6442 Args.ClaimAllArgs(options::OPT_emit_llvm);
6443
6444 claimNoWarnArgs(Args);
6445
6446 // Invoke ourselves in -cc1as mode.
6447 //
6448 // FIXME: Implement custom jobs for internal actions.
6449 CmdArgs.push_back("-cc1as");
6450
6451 // Add the "effective" target triple.
6452 CmdArgs.push_back("-triple");
6453 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6454
6455 // Set the output mode, we currently only expect to be used as a real
6456 // assembler.
6457 CmdArgs.push_back("-filetype");
6458 CmdArgs.push_back("obj");
6459
6460 // Set the main file name, so that debug info works even with
6461 // -save-temps or preprocessed assembly.
6462 CmdArgs.push_back("-main-file-name");
6463 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6464
6465 // Add the target cpu
6466 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6467 if (!CPU.empty()) {
6468 CmdArgs.push_back("-target-cpu");
6469 CmdArgs.push_back(Args.MakeArgString(CPU));
6470 }
6471
6472 // Add the target features
6473 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6474
6475 // Ignore explicit -force_cpusubtype_ALL option.
6476 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6477
6478 // Pass along any -I options so we get proper .include search paths.
6479 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6480
6481 // Determine the original source input.
6482 const Action *SourceAction = &JA;
6483 while (SourceAction->getKind() != Action::InputClass) {
6484 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6485 SourceAction = SourceAction->getInputs()[0];
6486 }
6487
6488 // Forward -g and handle debug info related flags, assuming we are dealing
6489 // with an actual assembly file.
6490 bool WantDebug = false;
6491 unsigned DwarfVersion = 0;
6492 Args.ClaimAllArgs(options::OPT_g_Group);
6493 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6494 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6495 !A->getOption().matches(options::OPT_ggdb0);
6496 if (WantDebug)
6497 DwarfVersion = DwarfVersionNum(A->getSpelling());
6498 }
6499 if (DwarfVersion == 0)
6500 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6501
6502 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6503
6504 if (SourceAction->getType() == types::TY_Asm ||
6505 SourceAction->getType() == types::TY_PP_Asm) {
6506 // You might think that it would be ok to set DebugInfoKind outside of
6507 // the guard for source type, however there is a test which asserts
6508 // that some assembler invocation receives no -debug-info-kind,
6509 // and it's not clear whether that test is just overly restrictive.
6510 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6511 : codegenoptions::NoDebugInfo);
6512 // Add the -fdebug-compilation-dir flag if needed.
6513 addDebugCompDirArg(Args, CmdArgs);
6514
6515 // Set the AT_producer to the clang version when using the integrated
6516 // assembler on assembly source files.
6517 CmdArgs.push_back("-dwarf-debug-producer");
6518 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6519
6520 // And pass along -I options
6521 Args.AddAllArgs(CmdArgs, options::OPT_I);
6522 }
6523 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6524 llvm::DebuggerKind::Default);
6525
6526 // Handle -fPIC et al -- the relocation-model affects the assembler
6527 // for some targets.
6528 llvm::Reloc::Model RelocationModel;
6529 unsigned PICLevel;
6530 bool IsPIE;
6531 std::tie(RelocationModel, PICLevel, IsPIE) =
6532 ParsePICArgs(getToolChain(), Triple, Args);
6533
6534 const char *RMName = RelocationModelName(RelocationModel);
6535 if (RMName) {
6536 CmdArgs.push_back("-mrelocation-model");
6537 CmdArgs.push_back(RMName);
6538 }
6539
6540 // Optionally embed the -cc1as level arguments into the debug info, for build
6541 // analysis.
6542 if (getToolChain().UseDwarfDebugFlags()) {
6543 ArgStringList OriginalArgs;
6544 for (const auto &Arg : Args)
6545 Arg->render(Args, OriginalArgs);
6546
6547 SmallString<256> Flags;
6548 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6549 Flags += Exec;
6550 for (const char *OriginalArg : OriginalArgs) {
6551 SmallString<128> EscapedArg;
6552 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6553 Flags += " ";
6554 Flags += EscapedArg;
6555 }
6556 CmdArgs.push_back("-dwarf-debug-flags");
6557 CmdArgs.push_back(Args.MakeArgString(Flags));
6558 }
6559
6560 // FIXME: Add -static support, once we have it.
6561
6562 // Add target specific flags.
6563 switch (getToolChain().getArch()) {
6564 default:
6565 break;
6566
6567 case llvm::Triple::mips:
6568 case llvm::Triple::mipsel:
6569 case llvm::Triple::mips64:
6570 case llvm::Triple::mips64el:
6571 AddMIPSTargetArgs(Args, CmdArgs);
6572 break;
6573 }
6574
6575 // Consume all the warning flags. Usually this would be handled more
6576 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6577 // doesn't handle that so rather than warning about unused flags that are
6578 // actually used, we'll lie by omission instead.
6579 // FIXME: Stop lying and consume only the appropriate driver flags
6580 Args.ClaimAllArgs(options::OPT_W_Group);
6581
6582 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6583 getToolChain().getDriver());
6584
6585 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6586
6587 assert(Output.isFilename() && "Unexpected lipo output.");
6588 CmdArgs.push_back("-o");
6589 CmdArgs.push_back(Output.getFilename());
6590
6591 assert(Input.isFilename() && "Invalid input.");
6592 CmdArgs.push_back(Input.getFilename());
6593
6594 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6595 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6596
6597 // Handle the debug info splitting at object creation time if we're
6598 // creating an object.
6599 // TODO: Currently only works on linux with newer objcopy.
6600 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6601 getToolChain().getTriple().isOSLinux())
6602 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6603 SplitDebugName(Args, Input));
6604 }
6605
anchor()6606 void GnuTool::anchor() {}
6607
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6608 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6609 const InputInfo &Output,
6610 const InputInfoList &Inputs, const ArgList &Args,
6611 const char *LinkingOutput) const {
6612 const Driver &D = getToolChain().getDriver();
6613 ArgStringList CmdArgs;
6614
6615 for (const auto &A : Args) {
6616 if (forwardToGCC(A->getOption())) {
6617 // It is unfortunate that we have to claim here, as this means
6618 // we will basically never report anything interesting for
6619 // platforms using a generic gcc, even if we are just using gcc
6620 // to get to the assembler.
6621 A->claim();
6622
6623 // Don't forward any -g arguments to assembly steps.
6624 if (isa<AssembleJobAction>(JA) &&
6625 A->getOption().matches(options::OPT_g_Group))
6626 continue;
6627
6628 // Don't forward any -W arguments to assembly and link steps.
6629 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6630 A->getOption().matches(options::OPT_W_Group))
6631 continue;
6632
6633 A->render(Args, CmdArgs);
6634 }
6635 }
6636
6637 RenderExtraToolArgs(JA, CmdArgs);
6638
6639 // If using a driver driver, force the arch.
6640 if (getToolChain().getTriple().isOSDarwin()) {
6641 CmdArgs.push_back("-arch");
6642 CmdArgs.push_back(
6643 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6644 }
6645
6646 // Try to force gcc to match the tool chain we want, if we recognize
6647 // the arch.
6648 //
6649 // FIXME: The triple class should directly provide the information we want
6650 // here.
6651 switch (getToolChain().getArch()) {
6652 default:
6653 break;
6654 case llvm::Triple::x86:
6655 case llvm::Triple::ppc:
6656 CmdArgs.push_back("-m32");
6657 break;
6658 case llvm::Triple::x86_64:
6659 case llvm::Triple::ppc64:
6660 case llvm::Triple::ppc64le:
6661 CmdArgs.push_back("-m64");
6662 break;
6663 case llvm::Triple::sparcel:
6664 CmdArgs.push_back("-EL");
6665 break;
6666 }
6667
6668 if (Output.isFilename()) {
6669 CmdArgs.push_back("-o");
6670 CmdArgs.push_back(Output.getFilename());
6671 } else {
6672 assert(Output.isNothing() && "Unexpected output");
6673 CmdArgs.push_back("-fsyntax-only");
6674 }
6675
6676 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6677
6678 // Only pass -x if gcc will understand it; otherwise hope gcc
6679 // understands the suffix correctly. The main use case this would go
6680 // wrong in is for linker inputs if they happened to have an odd
6681 // suffix; really the only way to get this to happen is a command
6682 // like '-x foobar a.c' which will treat a.c like a linker input.
6683 //
6684 // FIXME: For the linker case specifically, can we safely convert
6685 // inputs into '-Wl,' options?
6686 for (const auto &II : Inputs) {
6687 // Don't try to pass LLVM or AST inputs to a generic gcc.
6688 if (types::isLLVMIR(II.getType()))
6689 D.Diag(diag::err_drv_no_linker_llvm_support)
6690 << getToolChain().getTripleString();
6691 else if (II.getType() == types::TY_AST)
6692 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6693 else if (II.getType() == types::TY_ModuleFile)
6694 D.Diag(diag::err_drv_no_module_support)
6695 << getToolChain().getTripleString();
6696
6697 if (types::canTypeBeUserSpecified(II.getType())) {
6698 CmdArgs.push_back("-x");
6699 CmdArgs.push_back(types::getTypeName(II.getType()));
6700 }
6701
6702 if (II.isFilename())
6703 CmdArgs.push_back(II.getFilename());
6704 else {
6705 const Arg &A = II.getInputArg();
6706
6707 // Reverse translate some rewritten options.
6708 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6709 CmdArgs.push_back("-lstdc++");
6710 continue;
6711 }
6712
6713 // Don't render as input, we need gcc to do the translations.
6714 A.render(Args, CmdArgs);
6715 }
6716 }
6717
6718 const std::string &customGCCName = D.getCCCGenericGCCName();
6719 const char *GCCName;
6720 if (!customGCCName.empty())
6721 GCCName = customGCCName.c_str();
6722 else if (D.CCCIsCXX()) {
6723 GCCName = "g++";
6724 } else
6725 GCCName = "gcc";
6726
6727 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6728 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6729 }
6730
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6731 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6732 ArgStringList &CmdArgs) const {
6733 CmdArgs.push_back("-E");
6734 }
6735
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6736 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6737 ArgStringList &CmdArgs) const {
6738 const Driver &D = getToolChain().getDriver();
6739
6740 switch (JA.getType()) {
6741 // If -flto, etc. are present then make sure not to force assembly output.
6742 case types::TY_LLVM_IR:
6743 case types::TY_LTO_IR:
6744 case types::TY_LLVM_BC:
6745 case types::TY_LTO_BC:
6746 CmdArgs.push_back("-c");
6747 break;
6748 // We assume we've got an "integrated" assembler in that gcc will produce an
6749 // object file itself.
6750 case types::TY_Object:
6751 CmdArgs.push_back("-c");
6752 break;
6753 case types::TY_PP_Asm:
6754 CmdArgs.push_back("-S");
6755 break;
6756 case types::TY_Nothing:
6757 CmdArgs.push_back("-fsyntax-only");
6758 break;
6759 default:
6760 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6761 }
6762 }
6763
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6764 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6765 ArgStringList &CmdArgs) const {
6766 // The types are (hopefully) good enough.
6767 }
6768
6769 // Hexagon tools start.
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6770 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6771 ArgStringList &CmdArgs) const {
6772 }
6773
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const6774 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6775 const InputInfo &Output,
6776 const InputInfoList &Inputs,
6777 const ArgList &Args,
6778 const char *LinkingOutput) const {
6779 claimNoWarnArgs(Args);
6780
6781 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6782 const Driver &D = HTC.getDriver();
6783 ArgStringList CmdArgs;
6784
6785 std::string MArchString = "-march=hexagon";
6786 CmdArgs.push_back(Args.MakeArgString(MArchString));
6787
6788 RenderExtraToolArgs(JA, CmdArgs);
6789
6790 std::string AsName = "hexagon-llvm-mc";
6791 std::string MCpuString = "-mcpu=hexagon" +
6792 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6793 CmdArgs.push_back("-filetype=obj");
6794 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6795
6796 if (Output.isFilename()) {
6797 CmdArgs.push_back("-o");
6798 CmdArgs.push_back(Output.getFilename());
6799 } else {
6800 assert(Output.isNothing() && "Unexpected output");
6801 CmdArgs.push_back("-fsyntax-only");
6802 }
6803
6804 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6805 std::string N = llvm::utostr(G.getValue());
6806 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6807 }
6808
6809 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6810
6811 // Only pass -x if gcc will understand it; otherwise hope gcc
6812 // understands the suffix correctly. The main use case this would go
6813 // wrong in is for linker inputs if they happened to have an odd
6814 // suffix; really the only way to get this to happen is a command
6815 // like '-x foobar a.c' which will treat a.c like a linker input.
6816 //
6817 // FIXME: For the linker case specifically, can we safely convert
6818 // inputs into '-Wl,' options?
6819 for (const auto &II : Inputs) {
6820 // Don't try to pass LLVM or AST inputs to a generic gcc.
6821 if (types::isLLVMIR(II.getType()))
6822 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6823 << HTC.getTripleString();
6824 else if (II.getType() == types::TY_AST)
6825 D.Diag(clang::diag::err_drv_no_ast_support)
6826 << HTC.getTripleString();
6827 else if (II.getType() == types::TY_ModuleFile)
6828 D.Diag(diag::err_drv_no_module_support)
6829 << HTC.getTripleString();
6830
6831 if (II.isFilename())
6832 CmdArgs.push_back(II.getFilename());
6833 else
6834 // Don't render as input, we need gcc to do the translations.
6835 // FIXME: What is this?
6836 II.getInputArg().render(Args, CmdArgs);
6837 }
6838
6839 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6840 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6841 }
6842
RenderExtraToolArgs(const JobAction & JA,ArgStringList & CmdArgs) const6843 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6844 ArgStringList &CmdArgs) const {
6845 }
6846
6847 static void
constructHexagonLinkArgs(Compilation & C,const JobAction & JA,const toolchains::HexagonToolChain & HTC,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const char * LinkingOutput)6848 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6849 const toolchains::HexagonToolChain &HTC,
6850 const InputInfo &Output, const InputInfoList &Inputs,
6851 const ArgList &Args, ArgStringList &CmdArgs,
6852 const char *LinkingOutput) {
6853
6854 const Driver &D = HTC.getDriver();
6855
6856 //----------------------------------------------------------------------------
6857 //
6858 //----------------------------------------------------------------------------
6859 bool IsStatic = Args.hasArg(options::OPT_static);
6860 bool IsShared = Args.hasArg(options::OPT_shared);
6861 bool IsPIE = Args.hasArg(options::OPT_pie);
6862 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6863 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6864 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6865 bool UseG0 = false;
6866 bool UseShared = IsShared && !IsStatic;
6867
6868 //----------------------------------------------------------------------------
6869 // Silence warnings for various options
6870 //----------------------------------------------------------------------------
6871 Args.ClaimAllArgs(options::OPT_g_Group);
6872 Args.ClaimAllArgs(options::OPT_emit_llvm);
6873 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6874 // handled somewhere else.
6875 Args.ClaimAllArgs(options::OPT_static_libgcc);
6876
6877 //----------------------------------------------------------------------------
6878 //
6879 //----------------------------------------------------------------------------
6880 if (Args.hasArg(options::OPT_s))
6881 CmdArgs.push_back("-s");
6882
6883 if (Args.hasArg(options::OPT_r))
6884 CmdArgs.push_back("-r");
6885
6886 for (const auto &Opt : HTC.ExtraOpts)
6887 CmdArgs.push_back(Opt.c_str());
6888
6889 CmdArgs.push_back("-march=hexagon");
6890 std::string CpuVer =
6891 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6892 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6893 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6894
6895 if (IsShared) {
6896 CmdArgs.push_back("-shared");
6897 // The following should be the default, but doing as hexagon-gcc does.
6898 CmdArgs.push_back("-call_shared");
6899 }
6900
6901 if (IsStatic)
6902 CmdArgs.push_back("-static");
6903
6904 if (IsPIE && !IsShared)
6905 CmdArgs.push_back("-pie");
6906
6907 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6908 std::string N = llvm::utostr(G.getValue());
6909 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6910 UseG0 = G.getValue() == 0;
6911 }
6912
6913 //----------------------------------------------------------------------------
6914 //
6915 //----------------------------------------------------------------------------
6916 CmdArgs.push_back("-o");
6917 CmdArgs.push_back(Output.getFilename());
6918
6919 //----------------------------------------------------------------------------
6920 // moslib
6921 //----------------------------------------------------------------------------
6922 std::vector<std::string> OsLibs;
6923 bool HasStandalone = false;
6924
6925 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6926 A->claim();
6927 OsLibs.emplace_back(A->getValue());
6928 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6929 }
6930 if (OsLibs.empty()) {
6931 OsLibs.push_back("standalone");
6932 HasStandalone = true;
6933 }
6934
6935 //----------------------------------------------------------------------------
6936 // Start Files
6937 //----------------------------------------------------------------------------
6938 const std::string MCpuSuffix = "/" + CpuVer;
6939 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6940 const std::string RootDir =
6941 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6942 const std::string StartSubDir =
6943 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6944
6945 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6946 const char *Name) -> std::string {
6947 std::string RelName = SubDir + Name;
6948 std::string P = HTC.GetFilePath(RelName.c_str());
6949 if (llvm::sys::fs::exists(P))
6950 return P;
6951 return RootDir + RelName;
6952 };
6953
6954 if (IncStdLib && IncStartFiles) {
6955 if (!IsShared) {
6956 if (HasStandalone) {
6957 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6958 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6959 }
6960 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6961 CmdArgs.push_back(Args.MakeArgString(Crt0));
6962 }
6963 std::string Init = UseShared
6964 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6965 : Find(RootDir, StartSubDir, "/init.o");
6966 CmdArgs.push_back(Args.MakeArgString(Init));
6967 }
6968
6969 //----------------------------------------------------------------------------
6970 // Library Search Paths
6971 //----------------------------------------------------------------------------
6972 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6973 for (const auto &LibPath : LibPaths)
6974 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6975
6976 //----------------------------------------------------------------------------
6977 //
6978 //----------------------------------------------------------------------------
6979 Args.AddAllArgs(CmdArgs,
6980 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6981 options::OPT_t, options::OPT_u_Group});
6982
6983 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6984
6985 //----------------------------------------------------------------------------
6986 // Libraries
6987 //----------------------------------------------------------------------------
6988 if (IncStdLib && IncDefLibs) {
6989 if (D.CCCIsCXX()) {
6990 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6991 CmdArgs.push_back("-lm");
6992 }
6993
6994 CmdArgs.push_back("--start-group");
6995
6996 if (!IsShared) {
6997 for (const std::string &Lib : OsLibs)
6998 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6999 CmdArgs.push_back("-lc");
7000 }
7001 CmdArgs.push_back("-lgcc");
7002
7003 CmdArgs.push_back("--end-group");
7004 }
7005
7006 //----------------------------------------------------------------------------
7007 // End files
7008 //----------------------------------------------------------------------------
7009 if (IncStdLib && IncStartFiles) {
7010 std::string Fini = UseShared
7011 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
7012 : Find(RootDir, StartSubDir, "/fini.o");
7013 CmdArgs.push_back(Args.MakeArgString(Fini));
7014 }
7015 }
7016
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7017 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7018 const InputInfo &Output,
7019 const InputInfoList &Inputs,
7020 const ArgList &Args,
7021 const char *LinkingOutput) const {
7022 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
7023
7024 ArgStringList CmdArgs;
7025 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
7026 LinkingOutput);
7027
7028 std::string Linker = HTC.GetProgramPath("hexagon-link");
7029 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7030 CmdArgs, Inputs));
7031 }
7032 // Hexagon tools end.
7033
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7034 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7035 const InputInfo &Output,
7036 const InputInfoList &Inputs,
7037 const ArgList &Args,
7038 const char *LinkingOutput) const {
7039
7040 std::string Linker = getToolChain().GetProgramPath(getShortName());
7041 ArgStringList CmdArgs;
7042 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7043 CmdArgs.push_back("-shared");
7044 CmdArgs.push_back("-o");
7045 CmdArgs.push_back(Output.getFilename());
7046 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
7047 CmdArgs, Inputs));
7048 }
7049 // AMDGPU tools end.
7050
Linker(const ToolChain & TC)7051 wasm::Linker::Linker(const ToolChain &TC)
7052 : GnuTool("wasm::Linker", "lld", TC) {}
7053
isLinkJob() const7054 bool wasm::Linker::isLinkJob() const {
7055 return true;
7056 }
7057
hasIntegratedCPP() const7058 bool wasm::Linker::hasIntegratedCPP() const {
7059 return false;
7060 }
7061
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7062 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7063 const InputInfo &Output,
7064 const InputInfoList &Inputs,
7065 const ArgList &Args,
7066 const char *LinkingOutput) const {
7067
7068 const ToolChain &ToolChain = getToolChain();
7069 const Driver &D = ToolChain.getDriver();
7070 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
7071 ArgStringList CmdArgs;
7072 CmdArgs.push_back("-flavor");
7073 CmdArgs.push_back("ld");
7074
7075 // Enable garbage collection of unused input sections by default, since code
7076 // size is of particular importance. This is significantly facilitated by
7077 // the enabling of -ffunction-sections and -fdata-sections in
7078 // Clang::ConstructJob.
7079 if (areOptimizationsEnabled(Args))
7080 CmdArgs.push_back("--gc-sections");
7081
7082 if (Args.hasArg(options::OPT_rdynamic))
7083 CmdArgs.push_back("-export-dynamic");
7084 if (Args.hasArg(options::OPT_s))
7085 CmdArgs.push_back("--strip-all");
7086 if (Args.hasArg(options::OPT_shared))
7087 CmdArgs.push_back("-shared");
7088 if (Args.hasArg(options::OPT_static))
7089 CmdArgs.push_back("-Bstatic");
7090
7091 Args.AddAllArgs(CmdArgs, options::OPT_L);
7092 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7093
7094 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7095 if (Args.hasArg(options::OPT_shared))
7096 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
7097 else if (Args.hasArg(options::OPT_pie))
7098 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
7099 else
7100 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
7101
7102 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7103 }
7104
7105 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7106
7107 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7108 if (D.CCCIsCXX())
7109 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7110
7111 if (Args.hasArg(options::OPT_pthread))
7112 CmdArgs.push_back("-lpthread");
7113
7114 CmdArgs.push_back("-lc");
7115 CmdArgs.push_back("-lcompiler_rt");
7116 }
7117
7118 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7119 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
7120
7121 CmdArgs.push_back("-o");
7122 CmdArgs.push_back(Output.getFilename());
7123
7124 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
7125 }
7126
getARMArch(StringRef Arch,const llvm::Triple & Triple)7127 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
7128 std::string MArch;
7129 if (!Arch.empty())
7130 MArch = Arch;
7131 else
7132 MArch = Triple.getArchName();
7133 MArch = StringRef(MArch).split("+").first.lower();
7134
7135 // Handle -march=native.
7136 if (MArch == "native") {
7137 std::string CPU = llvm::sys::getHostCPUName();
7138 if (CPU != "generic") {
7139 // Translate the native cpu into the architecture suffix for that CPU.
7140 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
7141 // If there is no valid architecture suffix for this CPU we don't know how
7142 // to handle it, so return no architecture.
7143 if (Suffix.empty())
7144 MArch = "";
7145 else
7146 MArch = std::string("arm") + Suffix.str();
7147 }
7148 }
7149
7150 return MArch;
7151 }
7152
7153 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
getARMCPUForMArch(StringRef Arch,const llvm::Triple & Triple)7154 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
7155 std::string MArch = getARMArch(Arch, Triple);
7156 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
7157 // here means an -march=native that we can't handle, so instead return no CPU.
7158 if (MArch.empty())
7159 return StringRef();
7160
7161 // We need to return an empty string here on invalid MArch values as the
7162 // various places that call this function can't cope with a null result.
7163 return Triple.getARMCPUForArch(MArch);
7164 }
7165
7166 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
getARMTargetCPU(StringRef CPU,StringRef Arch,const llvm::Triple & Triple)7167 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
7168 const llvm::Triple &Triple) {
7169 // FIXME: Warn on inconsistent use of -mcpu and -march.
7170 // If we have -mcpu=, use that.
7171 if (!CPU.empty()) {
7172 std::string MCPU = StringRef(CPU).split("+").first.lower();
7173 // Handle -mcpu=native.
7174 if (MCPU == "native")
7175 return llvm::sys::getHostCPUName();
7176 else
7177 return MCPU;
7178 }
7179
7180 return getARMCPUForMArch(Arch, Triple);
7181 }
7182
7183 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
7184 /// CPU (or Arch, if CPU is generic).
7185 // FIXME: This is redundant with -mcpu, why does LLVM use this.
getLLVMArchSuffixForARM(StringRef CPU,StringRef Arch,const llvm::Triple & Triple)7186 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
7187 const llvm::Triple &Triple) {
7188 unsigned ArchKind;
7189 if (CPU == "generic") {
7190 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
7191 ArchKind = llvm::ARM::parseArch(ARMArch);
7192 if (ArchKind == llvm::ARM::AK_INVALID)
7193 // In case of generic Arch, i.e. "arm",
7194 // extract arch from default cpu of the Triple
7195 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
7196 } else {
7197 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
7198 // armv7k triple if it's actually been specified via "-arch armv7k".
7199 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
7200 ? (unsigned)llvm::ARM::AK_ARMV7K
7201 : llvm::ARM::parseCPUArch(CPU);
7202 }
7203 if (ArchKind == llvm::ARM::AK_INVALID)
7204 return "";
7205 return llvm::ARM::getSubArch(ArchKind);
7206 }
7207
appendEBLinkFlags(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple)7208 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
7209 const llvm::Triple &Triple) {
7210 if (Args.hasArg(options::OPT_r))
7211 return;
7212
7213 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
7214 // to generate BE-8 executables.
7215 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
7216 CmdArgs.push_back("--be8");
7217 }
7218
getSupportedNanEncoding(StringRef & CPU)7219 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
7220 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
7221 // was first introduced in Release 3. However, other compilers have
7222 // traditionally allowed it for Release 2 so we should do the same.
7223 return (NanEncoding)llvm::StringSwitch<int>(CPU)
7224 .Case("mips1", NanLegacy)
7225 .Case("mips2", NanLegacy)
7226 .Case("mips3", NanLegacy)
7227 .Case("mips4", NanLegacy)
7228 .Case("mips5", NanLegacy)
7229 .Case("mips32", NanLegacy)
7230 .Case("mips32r2", NanLegacy | Nan2008)
7231 .Case("mips32r3", NanLegacy | Nan2008)
7232 .Case("mips32r5", NanLegacy | Nan2008)
7233 .Case("mips32r6", Nan2008)
7234 .Case("mips64", NanLegacy)
7235 .Case("mips64r2", NanLegacy | Nan2008)
7236 .Case("mips64r3", NanLegacy | Nan2008)
7237 .Case("mips64r5", NanLegacy | Nan2008)
7238 .Case("mips64r6", Nan2008)
7239 .Default(NanLegacy);
7240 }
7241
hasCompactBranches(StringRef & CPU)7242 bool mips::hasCompactBranches(StringRef &CPU) {
7243 // mips32r6 and mips64r6 have compact branches.
7244 return llvm::StringSwitch<bool>(CPU)
7245 .Case("mips32r6", true)
7246 .Case("mips64r6", true)
7247 .Default(false);
7248 }
7249
hasMipsAbiArg(const ArgList & Args,const char * Value)7250 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
7251 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
7252 return A && (A->getValue() == StringRef(Value));
7253 }
7254
isUCLibc(const ArgList & Args)7255 bool mips::isUCLibc(const ArgList &Args) {
7256 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
7257 return A && A->getOption().matches(options::OPT_muclibc);
7258 }
7259
isNaN2008(const ArgList & Args,const llvm::Triple & Triple)7260 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
7261 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
7262 return llvm::StringSwitch<bool>(NaNArg->getValue())
7263 .Case("2008", true)
7264 .Case("legacy", false)
7265 .Default(false);
7266
7267 // NaN2008 is the default for MIPS32r6/MIPS64r6.
7268 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
7269 .Cases("mips32r6", "mips64r6", true)
7270 .Default(false);
7271
7272 return false;
7273 }
7274
isFP64ADefault(const llvm::Triple & Triple,StringRef CPUName)7275 bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
7276 if (!Triple.isAndroid())
7277 return false;
7278
7279 // Android MIPS32R6 defaults to FP64A.
7280 return llvm::StringSwitch<bool>(CPUName)
7281 .Case("mips32r6", true)
7282 .Default(false);
7283 }
7284
isFPXXDefault(const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,mips::FloatABI FloatABI)7285 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
7286 StringRef ABIName, mips::FloatABI FloatABI) {
7287 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
7288 Triple.getVendor() != llvm::Triple::MipsTechnologies &&
7289 !Triple.isAndroid())
7290 return false;
7291
7292 if (ABIName != "32")
7293 return false;
7294
7295 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
7296 // present.
7297 if (FloatABI == mips::FloatABI::Soft)
7298 return false;
7299
7300 return llvm::StringSwitch<bool>(CPUName)
7301 .Cases("mips2", "mips3", "mips4", "mips5", true)
7302 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
7303 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
7304 .Default(false);
7305 }
7306
shouldUseFPXX(const ArgList & Args,const llvm::Triple & Triple,StringRef CPUName,StringRef ABIName,mips::FloatABI FloatABI)7307 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
7308 StringRef CPUName, StringRef ABIName,
7309 mips::FloatABI FloatABI) {
7310 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
7311
7312 // FPXX shouldn't be used if -msingle-float is present.
7313 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
7314 options::OPT_mdouble_float))
7315 if (A->getOption().matches(options::OPT_msingle_float))
7316 UseFPXX = false;
7317
7318 return UseFPXX;
7319 }
7320
getArchTypeForMachOArchName(StringRef Str)7321 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
7322 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
7323 // archs which Darwin doesn't use.
7324
7325 // The matching this routine does is fairly pointless, since it is neither the
7326 // complete architecture list, nor a reasonable subset. The problem is that
7327 // historically the driver driver accepts this and also ties its -march=
7328 // handling to the architecture name, so we need to be careful before removing
7329 // support for it.
7330
7331 // This code must be kept in sync with Clang's Darwin specific argument
7332 // translation.
7333
7334 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
7335 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
7336 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
7337 .Case("ppc64", llvm::Triple::ppc64)
7338 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
7339 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
7340 llvm::Triple::x86)
7341 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
7342 // This is derived from the driver driver.
7343 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
7344 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
7345 .Cases("armv7s", "xscale", llvm::Triple::arm)
7346 .Case("arm64", llvm::Triple::aarch64)
7347 .Case("r600", llvm::Triple::r600)
7348 .Case("amdgcn", llvm::Triple::amdgcn)
7349 .Case("nvptx", llvm::Triple::nvptx)
7350 .Case("nvptx64", llvm::Triple::nvptx64)
7351 .Case("amdil", llvm::Triple::amdil)
7352 .Case("spir", llvm::Triple::spir)
7353 .Default(llvm::Triple::UnknownArch);
7354 }
7355
setTripleTypeForMachOArchName(llvm::Triple & T,StringRef Str)7356 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
7357 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
7358 T.setArch(Arch);
7359
7360 if (Str == "x86_64h")
7361 T.setArchName(Str);
7362 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
7363 T.setOS(llvm::Triple::UnknownOS);
7364 T.setObjectFormat(llvm::Triple::MachO);
7365 }
7366 }
7367
getBaseInputName(const ArgList & Args,const InputInfo & Input)7368 const char *Clang::getBaseInputName(const ArgList &Args,
7369 const InputInfo &Input) {
7370 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7371 }
7372
getBaseInputStem(const ArgList & Args,const InputInfoList & Inputs)7373 const char *Clang::getBaseInputStem(const ArgList &Args,
7374 const InputInfoList &Inputs) {
7375 const char *Str = getBaseInputName(Args, Inputs[0]);
7376
7377 if (const char *End = strrchr(Str, '.'))
7378 return Args.MakeArgString(std::string(Str, End));
7379
7380 return Str;
7381 }
7382
getDependencyFileName(const ArgList & Args,const InputInfoList & Inputs)7383 const char *Clang::getDependencyFileName(const ArgList &Args,
7384 const InputInfoList &Inputs) {
7385 // FIXME: Think about this more.
7386 std::string Res;
7387
7388 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7389 std::string Str(OutputOpt->getValue());
7390 Res = Str.substr(0, Str.rfind('.'));
7391 } else {
7392 Res = getBaseInputStem(Args, Inputs);
7393 }
7394 return Args.MakeArgString(Res + ".d");
7395 }
7396
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7397 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7398 const InputInfo &Output,
7399 const InputInfoList &Inputs,
7400 const ArgList &Args,
7401 const char *LinkingOutput) const {
7402 const ToolChain &ToolChain = getToolChain();
7403 const Driver &D = ToolChain.getDriver();
7404 ArgStringList CmdArgs;
7405
7406 // Silence warning for "clang -g foo.o -o foo"
7407 Args.ClaimAllArgs(options::OPT_g_Group);
7408 // and "clang -emit-llvm foo.o -o foo"
7409 Args.ClaimAllArgs(options::OPT_emit_llvm);
7410 // and for "clang -w foo.o -o foo". Other warning options are already
7411 // handled somewhere else.
7412 Args.ClaimAllArgs(options::OPT_w);
7413
7414 if (!D.SysRoot.empty())
7415 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7416
7417 // CloudABI only supports static linkage.
7418 CmdArgs.push_back("-Bstatic");
7419
7420 // CloudABI uses Position Independent Executables exclusively.
7421 CmdArgs.push_back("-pie");
7422 CmdArgs.push_back("--no-dynamic-linker");
7423 CmdArgs.push_back("-zrelro");
7424
7425 CmdArgs.push_back("--eh-frame-hdr");
7426 CmdArgs.push_back("--gc-sections");
7427
7428 if (Output.isFilename()) {
7429 CmdArgs.push_back("-o");
7430 CmdArgs.push_back(Output.getFilename());
7431 } else {
7432 assert(Output.isNothing() && "Invalid output.");
7433 }
7434
7435 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7436 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
7437 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
7438 }
7439
7440 Args.AddAllArgs(CmdArgs, options::OPT_L);
7441 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
7442 Args.AddAllArgs(CmdArgs,
7443 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
7444 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
7445
7446 if (D.isUsingLTO())
7447 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
7448
7449 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
7450
7451 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7452 if (D.CCCIsCXX())
7453 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
7454 CmdArgs.push_back("-lc");
7455 CmdArgs.push_back("-lcompiler_rt");
7456 }
7457
7458 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7459 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
7460
7461 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
7462 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7463 }
7464
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7465 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7466 const InputInfo &Output,
7467 const InputInfoList &Inputs,
7468 const ArgList &Args,
7469 const char *LinkingOutput) const {
7470 ArgStringList CmdArgs;
7471
7472 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7473 const InputInfo &Input = Inputs[0];
7474
7475 // Determine the original source input.
7476 const Action *SourceAction = &JA;
7477 while (SourceAction->getKind() != Action::InputClass) {
7478 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7479 SourceAction = SourceAction->getInputs()[0];
7480 }
7481
7482 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
7483 // sure it runs its system assembler not clang's integrated assembler.
7484 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
7485 // FIXME: at run-time detect assembler capabilities or rely on version
7486 // information forwarded by -target-assembler-version.
7487 if (Args.hasArg(options::OPT_fno_integrated_as)) {
7488 const llvm::Triple &T(getToolChain().getTriple());
7489 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
7490 CmdArgs.push_back("-Q");
7491 }
7492
7493 // Forward -g, assuming we are dealing with an actual assembly file.
7494 if (SourceAction->getType() == types::TY_Asm ||
7495 SourceAction->getType() == types::TY_PP_Asm) {
7496 if (Args.hasArg(options::OPT_gstabs))
7497 CmdArgs.push_back("--gstabs");
7498 else if (Args.hasArg(options::OPT_g_Group))
7499 CmdArgs.push_back("-g");
7500 }
7501
7502 // Derived from asm spec.
7503 AddMachOArch(Args, CmdArgs);
7504
7505 // Use -force_cpusubtype_ALL on x86 by default.
7506 if (getToolChain().getArch() == llvm::Triple::x86 ||
7507 getToolChain().getArch() == llvm::Triple::x86_64 ||
7508 Args.hasArg(options::OPT_force__cpusubtype__ALL))
7509 CmdArgs.push_back("-force_cpusubtype_ALL");
7510
7511 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
7512 (((Args.hasArg(options::OPT_mkernel) ||
7513 Args.hasArg(options::OPT_fapple_kext)) &&
7514 getMachOToolChain().isKernelStatic()) ||
7515 Args.hasArg(options::OPT_static)))
7516 CmdArgs.push_back("-static");
7517
7518 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7519
7520 assert(Output.isFilename() && "Unexpected lipo output.");
7521 CmdArgs.push_back("-o");
7522 CmdArgs.push_back(Output.getFilename());
7523
7524 assert(Input.isFilename() && "Invalid input.");
7525 CmdArgs.push_back(Input.getFilename());
7526
7527 // asm_final spec is empty.
7528
7529 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7530 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7531 }
7532
anchor()7533 void darwin::MachOTool::anchor() {}
7534
AddMachOArch(const ArgList & Args,ArgStringList & CmdArgs) const7535 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
7536 ArgStringList &CmdArgs) const {
7537 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
7538
7539 // Derived from darwin_arch spec.
7540 CmdArgs.push_back("-arch");
7541 CmdArgs.push_back(Args.MakeArgString(ArchName));
7542
7543 // FIXME: Is this needed anymore?
7544 if (ArchName == "arm")
7545 CmdArgs.push_back("-force_cpusubtype_ALL");
7546 }
7547
NeedsTempPath(const InputInfoList & Inputs) const7548 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
7549 // We only need to generate a temp path for LTO if we aren't compiling object
7550 // files. When compiling source files, we run 'dsymutil' after linking. We
7551 // don't run 'dsymutil' when compiling object files.
7552 for (const auto &Input : Inputs)
7553 if (Input.getType() != types::TY_Object)
7554 return true;
7555
7556 return false;
7557 }
7558
AddLinkArgs(Compilation & C,const ArgList & Args,ArgStringList & CmdArgs,const InputInfoList & Inputs) const7559 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
7560 ArgStringList &CmdArgs,
7561 const InputInfoList &Inputs) const {
7562 const Driver &D = getToolChain().getDriver();
7563 const toolchains::MachO &MachOTC = getMachOToolChain();
7564
7565 unsigned Version[5] = {0, 0, 0, 0, 0};
7566 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
7567 if (!Driver::GetReleaseVersion(A->getValue(), Version))
7568 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
7569 }
7570
7571 // Newer linkers support -demangle. Pass it if supported and not disabled by
7572 // the user.
7573 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
7574 CmdArgs.push_back("-demangle");
7575
7576 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7577 CmdArgs.push_back("-export_dynamic");
7578
7579 // If we are using App Extension restrictions, pass a flag to the linker
7580 // telling it that the compiled code has been audited.
7581 if (Args.hasFlag(options::OPT_fapplication_extension,
7582 options::OPT_fno_application_extension, false))
7583 CmdArgs.push_back("-application_extension");
7584
7585 if (D.isUsingLTO()) {
7586 // If we are using LTO, then automatically create a temporary file path for
7587 // the linker to use, so that it's lifetime will extend past a possible
7588 // dsymutil step.
7589 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7590 const char *TmpPath = C.getArgs().MakeArgString(
7591 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7592 C.addTempFile(TmpPath);
7593 CmdArgs.push_back("-object_path_lto");
7594 CmdArgs.push_back(TmpPath);
7595 }
7596
7597 // Use -lto_library option to specify the libLTO.dylib path. Try to find
7598 // it in clang installed libraries. If not found, the option is not used
7599 // and 'ld' will use its default mechanism to search for libLTO.dylib.
7600 if (Version[0] >= 133) {
7601 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7602 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7603 SmallString<128> LibLTOPath(P);
7604 llvm::sys::path::append(LibLTOPath, "lib");
7605 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7606 if (llvm::sys::fs::exists(LibLTOPath)) {
7607 CmdArgs.push_back("-lto_library");
7608 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7609 } else {
7610 D.Diag(diag::warn_drv_lto_libpath);
7611 }
7612 }
7613 }
7614
7615 // Derived from the "link" spec.
7616 Args.AddAllArgs(CmdArgs, options::OPT_static);
7617 if (!Args.hasArg(options::OPT_static))
7618 CmdArgs.push_back("-dynamic");
7619 if (Args.hasArg(options::OPT_fgnu_runtime)) {
7620 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7621 // here. How do we wish to handle such things?
7622 }
7623
7624 if (!Args.hasArg(options::OPT_dynamiclib)) {
7625 AddMachOArch(Args, CmdArgs);
7626 // FIXME: Why do this only on this path?
7627 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7628
7629 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7630 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7631 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7632
7633 Arg *A;
7634 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7635 (A = Args.getLastArg(options::OPT_current__version)) ||
7636 (A = Args.getLastArg(options::OPT_install__name)))
7637 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7638 << "-dynamiclib";
7639
7640 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7641 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7642 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7643 } else {
7644 CmdArgs.push_back("-dylib");
7645
7646 Arg *A;
7647 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7648 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7649 (A = Args.getLastArg(options::OPT_client__name)) ||
7650 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7651 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7652 (A = Args.getLastArg(options::OPT_private__bundle)))
7653 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7654 << "-dynamiclib";
7655
7656 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7657 "-dylib_compatibility_version");
7658 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7659 "-dylib_current_version");
7660
7661 AddMachOArch(Args, CmdArgs);
7662
7663 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7664 "-dylib_install_name");
7665 }
7666
7667 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7668 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7669 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7670 if (MachOTC.isTargetIOSBased())
7671 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7672 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7673 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7674 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7675 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7676 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7677 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7678 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7679 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7680 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7681 Args.AddAllArgs(CmdArgs, options::OPT_init);
7682
7683 // Add the deployment target.
7684 MachOTC.addMinVersionArgs(Args, CmdArgs);
7685
7686 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7687 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7688 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7689 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7690 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7691
7692 if (const Arg *A =
7693 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7694 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7695 if (A->getOption().matches(options::OPT_fpie) ||
7696 A->getOption().matches(options::OPT_fPIE))
7697 CmdArgs.push_back("-pie");
7698 else
7699 CmdArgs.push_back("-no_pie");
7700 }
7701 // for embed-bitcode, use -bitcode_bundle in linker command
7702 if (C.getDriver().embedBitcodeEnabled() ||
7703 C.getDriver().embedBitcodeMarkerOnly()) {
7704 // Check if the toolchain supports bitcode build flow.
7705 if (MachOTC.SupportsEmbeddedBitcode())
7706 CmdArgs.push_back("-bitcode_bundle");
7707 else
7708 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
7709 }
7710
7711 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7712 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7713 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7714 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7715 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7716 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7717 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7718 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7719 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7720 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7721 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7722 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7723 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7724 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7725 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7726 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7727
7728 // Give --sysroot= preference, over the Apple specific behavior to also use
7729 // --isysroot as the syslibroot.
7730 StringRef sysroot = C.getSysRoot();
7731 if (sysroot != "") {
7732 CmdArgs.push_back("-syslibroot");
7733 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7734 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7735 CmdArgs.push_back("-syslibroot");
7736 CmdArgs.push_back(A->getValue());
7737 }
7738
7739 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7740 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7741 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7742 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7743 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7744 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7745 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7746 Args.AddAllArgs(CmdArgs, options::OPT_y);
7747 Args.AddLastArg(CmdArgs, options::OPT_w);
7748 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7749 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7750 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7751 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7752 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7753 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7754 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7755 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7756 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7757 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7758 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7759 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7760 }
7761
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7762 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7763 const InputInfo &Output,
7764 const InputInfoList &Inputs,
7765 const ArgList &Args,
7766 const char *LinkingOutput) const {
7767 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7768
7769 // If the number of arguments surpasses the system limits, we will encode the
7770 // input files in a separate file, shortening the command line. To this end,
7771 // build a list of input file names that can be passed via a file with the
7772 // -filelist linker option.
7773 llvm::opt::ArgStringList InputFileList;
7774
7775 // The logic here is derived from gcc's behavior; most of which
7776 // comes from specs (starting with link_command). Consult gcc for
7777 // more information.
7778 ArgStringList CmdArgs;
7779
7780 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7781 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7782 options::OPT_ccc_arcmt_migrate)) {
7783 for (const auto &Arg : Args)
7784 Arg->claim();
7785 const char *Exec =
7786 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7787 CmdArgs.push_back(Output.getFilename());
7788 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7789 return;
7790 }
7791
7792 // I'm not sure why this particular decomposition exists in gcc, but
7793 // we follow suite for ease of comparison.
7794 AddLinkArgs(C, Args, CmdArgs, Inputs);
7795
7796 // It seems that the 'e' option is completely ignored for dynamic executables
7797 // (the default), and with static executables, the last one wins, as expected.
7798 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7799 options::OPT_Z_Flag, options::OPT_u_Group,
7800 options::OPT_e, options::OPT_r});
7801
7802 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7803 // members of static archive libraries which implement Objective-C classes or
7804 // categories.
7805 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7806 CmdArgs.push_back("-ObjC");
7807
7808 CmdArgs.push_back("-o");
7809 CmdArgs.push_back(Output.getFilename());
7810
7811 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7812 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7813
7814 // SafeStack requires its own runtime libraries
7815 // These libraries should be linked first, to make sure the
7816 // __safestack_init constructor executes before everything else
7817 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7818 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7819 "libclang_rt.safestack_osx.a",
7820 /*AlwaysLink=*/true);
7821 }
7822
7823 Args.AddAllArgs(CmdArgs, options::OPT_L);
7824
7825 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7826 // Build the input file for -filelist (list of linker input files) in case we
7827 // need it later
7828 for (const auto &II : Inputs) {
7829 if (!II.isFilename()) {
7830 // This is a linker input argument.
7831 // We cannot mix input arguments and file names in a -filelist input, thus
7832 // we prematurely stop our list (remaining files shall be passed as
7833 // arguments).
7834 if (InputFileList.size() > 0)
7835 break;
7836
7837 continue;
7838 }
7839
7840 InputFileList.push_back(II.getFilename());
7841 }
7842
7843 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7844 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7845
7846 if (isObjCRuntimeLinked(Args) &&
7847 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7848 // We use arclite library for both ARC and subscripting support.
7849 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7850
7851 CmdArgs.push_back("-framework");
7852 CmdArgs.push_back("Foundation");
7853 // Link libobj.
7854 CmdArgs.push_back("-lobjc");
7855 }
7856
7857 if (LinkingOutput) {
7858 CmdArgs.push_back("-arch_multiple");
7859 CmdArgs.push_back("-final_output");
7860 CmdArgs.push_back(LinkingOutput);
7861 }
7862
7863 if (Args.hasArg(options::OPT_fnested_functions))
7864 CmdArgs.push_back("-allow_stack_execute");
7865
7866 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7867
7868 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7869 if (getToolChain().getDriver().CCCIsCXX())
7870 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7871
7872 // link_ssp spec is empty.
7873
7874 // Let the tool chain choose which runtime library to link.
7875 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7876 }
7877
7878 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7879 // endfile_spec is empty.
7880 }
7881
7882 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7883 Args.AddAllArgs(CmdArgs, options::OPT_F);
7884
7885 // -iframework should be forwarded as -F.
7886 for (const Arg *A : Args.filtered(options::OPT_iframework))
7887 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7888
7889 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7890 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7891 if (A->getValue() == StringRef("Accelerate")) {
7892 CmdArgs.push_back("-framework");
7893 CmdArgs.push_back("Accelerate");
7894 }
7895 }
7896 }
7897
7898 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7899 std::unique_ptr<Command> Cmd =
7900 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7901 Cmd->setInputFileList(std::move(InputFileList));
7902 C.addCommand(std::move(Cmd));
7903 }
7904
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7905 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7906 const InputInfo &Output,
7907 const InputInfoList &Inputs,
7908 const ArgList &Args,
7909 const char *LinkingOutput) const {
7910 ArgStringList CmdArgs;
7911
7912 CmdArgs.push_back("-create");
7913 assert(Output.isFilename() && "Unexpected lipo output.");
7914
7915 CmdArgs.push_back("-output");
7916 CmdArgs.push_back(Output.getFilename());
7917
7918 for (const auto &II : Inputs) {
7919 assert(II.isFilename() && "Unexpected lipo input.");
7920 CmdArgs.push_back(II.getFilename());
7921 }
7922
7923 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7924 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7925 }
7926
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7927 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7928 const InputInfo &Output,
7929 const InputInfoList &Inputs,
7930 const ArgList &Args,
7931 const char *LinkingOutput) const {
7932 ArgStringList CmdArgs;
7933
7934 CmdArgs.push_back("-o");
7935 CmdArgs.push_back(Output.getFilename());
7936
7937 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7938 const InputInfo &Input = Inputs[0];
7939 assert(Input.isFilename() && "Unexpected dsymutil input.");
7940 CmdArgs.push_back(Input.getFilename());
7941
7942 const char *Exec =
7943 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7944 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7945 }
7946
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7947 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7948 const InputInfo &Output,
7949 const InputInfoList &Inputs,
7950 const ArgList &Args,
7951 const char *LinkingOutput) const {
7952 ArgStringList CmdArgs;
7953 CmdArgs.push_back("--verify");
7954 CmdArgs.push_back("--debug-info");
7955 CmdArgs.push_back("--eh-frame");
7956 CmdArgs.push_back("--quiet");
7957
7958 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7959 const InputInfo &Input = Inputs[0];
7960 assert(Input.isFilename() && "Unexpected verify input");
7961
7962 // Grabbing the output of the earlier dsymutil run.
7963 CmdArgs.push_back(Input.getFilename());
7964
7965 const char *Exec =
7966 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7967 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7968 }
7969
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7970 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7971 const InputInfo &Output,
7972 const InputInfoList &Inputs,
7973 const ArgList &Args,
7974 const char *LinkingOutput) const {
7975 claimNoWarnArgs(Args);
7976 ArgStringList CmdArgs;
7977
7978 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7979
7980 CmdArgs.push_back("-o");
7981 CmdArgs.push_back(Output.getFilename());
7982
7983 for (const auto &II : Inputs)
7984 CmdArgs.push_back(II.getFilename());
7985
7986 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7987 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7988 }
7989
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const7990 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7991 const InputInfo &Output,
7992 const InputInfoList &Inputs,
7993 const ArgList &Args,
7994 const char *LinkingOutput) const {
7995 ArgStringList CmdArgs;
7996
7997 // Demangle C++ names in errors
7998 CmdArgs.push_back("-C");
7999
8000 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8001 CmdArgs.push_back("-e");
8002 CmdArgs.push_back("_start");
8003 }
8004
8005 if (Args.hasArg(options::OPT_static)) {
8006 CmdArgs.push_back("-Bstatic");
8007 CmdArgs.push_back("-dn");
8008 } else {
8009 CmdArgs.push_back("-Bdynamic");
8010 if (Args.hasArg(options::OPT_shared)) {
8011 CmdArgs.push_back("-shared");
8012 } else {
8013 CmdArgs.push_back("--dynamic-linker");
8014 CmdArgs.push_back(
8015 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
8016 }
8017 }
8018
8019 if (Output.isFilename()) {
8020 CmdArgs.push_back("-o");
8021 CmdArgs.push_back(Output.getFilename());
8022 } else {
8023 assert(Output.isNothing() && "Invalid output.");
8024 }
8025
8026 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8027 if (!Args.hasArg(options::OPT_shared))
8028 CmdArgs.push_back(
8029 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
8030
8031 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8032 CmdArgs.push_back(
8033 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
8034 CmdArgs.push_back(
8035 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8036 }
8037
8038 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
8039
8040 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8041 options::OPT_e, options::OPT_r});
8042
8043 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8044
8045 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8046 if (getToolChain().getDriver().CCCIsCXX())
8047 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8048 CmdArgs.push_back("-lgcc_s");
8049 CmdArgs.push_back("-lc");
8050 if (!Args.hasArg(options::OPT_shared)) {
8051 CmdArgs.push_back("-lgcc");
8052 CmdArgs.push_back("-lm");
8053 }
8054 }
8055
8056 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8057 CmdArgs.push_back(
8058 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8059 }
8060 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8061
8062 getToolChain().addProfileRTLibs(Args, CmdArgs);
8063
8064 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8065 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8066 }
8067
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8068 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8069 const InputInfo &Output,
8070 const InputInfoList &Inputs,
8071 const ArgList &Args,
8072 const char *LinkingOutput) const {
8073 claimNoWarnArgs(Args);
8074 ArgStringList CmdArgs;
8075
8076 switch (getToolChain().getArch()) {
8077 case llvm::Triple::x86:
8078 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
8079 // instruct as in the base system to assemble 32-bit code.
8080 CmdArgs.push_back("--32");
8081 break;
8082
8083 case llvm::Triple::ppc:
8084 CmdArgs.push_back("-mppc");
8085 CmdArgs.push_back("-many");
8086 break;
8087
8088 case llvm::Triple::sparc:
8089 case llvm::Triple::sparcel: {
8090 CmdArgs.push_back("-32");
8091 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8092 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8093 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8094 break;
8095 }
8096
8097 case llvm::Triple::sparcv9: {
8098 CmdArgs.push_back("-64");
8099 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8100 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8101 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8102 break;
8103 }
8104
8105 case llvm::Triple::mips64:
8106 case llvm::Triple::mips64el: {
8107 StringRef CPUName;
8108 StringRef ABIName;
8109 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8110
8111 CmdArgs.push_back("-mabi");
8112 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8113
8114 if (getToolChain().getArch() == llvm::Triple::mips64)
8115 CmdArgs.push_back("-EB");
8116 else
8117 CmdArgs.push_back("-EL");
8118
8119 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8120 break;
8121 }
8122
8123 default:
8124 break;
8125 }
8126
8127 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8128
8129 CmdArgs.push_back("-o");
8130 CmdArgs.push_back(Output.getFilename());
8131
8132 for (const auto &II : Inputs)
8133 CmdArgs.push_back(II.getFilename());
8134
8135 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8136 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8137 }
8138
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8139 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8140 const InputInfo &Output,
8141 const InputInfoList &Inputs,
8142 const ArgList &Args,
8143 const char *LinkingOutput) const {
8144 const Driver &D = getToolChain().getDriver();
8145 ArgStringList CmdArgs;
8146
8147 // Silence warning for "clang -g foo.o -o foo"
8148 Args.ClaimAllArgs(options::OPT_g_Group);
8149 // and "clang -emit-llvm foo.o -o foo"
8150 Args.ClaimAllArgs(options::OPT_emit_llvm);
8151 // and for "clang -w foo.o -o foo". Other warning options are already
8152 // handled somewhere else.
8153 Args.ClaimAllArgs(options::OPT_w);
8154
8155 if (getToolChain().getArch() == llvm::Triple::mips64)
8156 CmdArgs.push_back("-EB");
8157 else if (getToolChain().getArch() == llvm::Triple::mips64el)
8158 CmdArgs.push_back("-EL");
8159
8160 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8161 CmdArgs.push_back("-e");
8162 CmdArgs.push_back("__start");
8163 }
8164
8165 if (Args.hasArg(options::OPT_static)) {
8166 CmdArgs.push_back("-Bstatic");
8167 } else {
8168 if (Args.hasArg(options::OPT_rdynamic))
8169 CmdArgs.push_back("-export-dynamic");
8170 CmdArgs.push_back("--eh-frame-hdr");
8171 CmdArgs.push_back("-Bdynamic");
8172 if (Args.hasArg(options::OPT_shared)) {
8173 CmdArgs.push_back("-shared");
8174 } else {
8175 CmdArgs.push_back("-dynamic-linker");
8176 CmdArgs.push_back("/usr/libexec/ld.so");
8177 }
8178 }
8179
8180 if (Args.hasArg(options::OPT_nopie))
8181 CmdArgs.push_back("-nopie");
8182
8183 if (Output.isFilename()) {
8184 CmdArgs.push_back("-o");
8185 CmdArgs.push_back(Output.getFilename());
8186 } else {
8187 assert(Output.isNothing() && "Invalid output.");
8188 }
8189
8190 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8191 if (!Args.hasArg(options::OPT_shared)) {
8192 if (Args.hasArg(options::OPT_pg))
8193 CmdArgs.push_back(
8194 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8195 else
8196 CmdArgs.push_back(
8197 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8198 CmdArgs.push_back(
8199 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8200 } else {
8201 CmdArgs.push_back(
8202 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8203 }
8204 }
8205
8206 std::string Triple = getToolChain().getTripleString();
8207 if (Triple.substr(0, 6) == "x86_64")
8208 Triple.replace(0, 6, "amd64");
8209 CmdArgs.push_back(
8210 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
8211
8212 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
8213 options::OPT_e, options::OPT_s, options::OPT_t,
8214 options::OPT_Z_Flag, options::OPT_r});
8215
8216 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8217
8218 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8219 if (D.CCCIsCXX()) {
8220 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8221 if (Args.hasArg(options::OPT_pg))
8222 CmdArgs.push_back("-lm_p");
8223 else
8224 CmdArgs.push_back("-lm");
8225 }
8226
8227 // FIXME: For some reason GCC passes -lgcc before adding
8228 // the default system libraries. Just mimic this for now.
8229 CmdArgs.push_back("-lgcc");
8230
8231 if (Args.hasArg(options::OPT_pthread)) {
8232 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8233 CmdArgs.push_back("-lpthread_p");
8234 else
8235 CmdArgs.push_back("-lpthread");
8236 }
8237
8238 if (!Args.hasArg(options::OPT_shared)) {
8239 if (Args.hasArg(options::OPT_pg))
8240 CmdArgs.push_back("-lc_p");
8241 else
8242 CmdArgs.push_back("-lc");
8243 }
8244
8245 CmdArgs.push_back("-lgcc");
8246 }
8247
8248 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8249 if (!Args.hasArg(options::OPT_shared))
8250 CmdArgs.push_back(
8251 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8252 else
8253 CmdArgs.push_back(
8254 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8255 }
8256
8257 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8258 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8259 }
8260
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8261 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8262 const InputInfo &Output,
8263 const InputInfoList &Inputs,
8264 const ArgList &Args,
8265 const char *LinkingOutput) const {
8266 claimNoWarnArgs(Args);
8267 ArgStringList CmdArgs;
8268
8269 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8270
8271 CmdArgs.push_back("-o");
8272 CmdArgs.push_back(Output.getFilename());
8273
8274 for (const auto &II : Inputs)
8275 CmdArgs.push_back(II.getFilename());
8276
8277 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8278 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8279 }
8280
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8281 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8282 const InputInfo &Output,
8283 const InputInfoList &Inputs,
8284 const ArgList &Args,
8285 const char *LinkingOutput) const {
8286 const Driver &D = getToolChain().getDriver();
8287 ArgStringList CmdArgs;
8288
8289 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
8290 CmdArgs.push_back("-e");
8291 CmdArgs.push_back("__start");
8292 }
8293
8294 if (Args.hasArg(options::OPT_static)) {
8295 CmdArgs.push_back("-Bstatic");
8296 } else {
8297 if (Args.hasArg(options::OPT_rdynamic))
8298 CmdArgs.push_back("-export-dynamic");
8299 CmdArgs.push_back("--eh-frame-hdr");
8300 CmdArgs.push_back("-Bdynamic");
8301 if (Args.hasArg(options::OPT_shared)) {
8302 CmdArgs.push_back("-shared");
8303 } else {
8304 CmdArgs.push_back("-dynamic-linker");
8305 CmdArgs.push_back("/usr/libexec/ld.so");
8306 }
8307 }
8308
8309 if (Output.isFilename()) {
8310 CmdArgs.push_back("-o");
8311 CmdArgs.push_back(Output.getFilename());
8312 } else {
8313 assert(Output.isNothing() && "Invalid output.");
8314 }
8315
8316 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8317 if (!Args.hasArg(options::OPT_shared)) {
8318 if (Args.hasArg(options::OPT_pg))
8319 CmdArgs.push_back(
8320 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
8321 else
8322 CmdArgs.push_back(
8323 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8324 CmdArgs.push_back(
8325 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8326 } else {
8327 CmdArgs.push_back(
8328 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8329 }
8330 }
8331
8332 Args.AddAllArgs(CmdArgs,
8333 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
8334
8335 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8336
8337 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8338 if (D.CCCIsCXX()) {
8339 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8340 if (Args.hasArg(options::OPT_pg))
8341 CmdArgs.push_back("-lm_p");
8342 else
8343 CmdArgs.push_back("-lm");
8344 }
8345
8346 if (Args.hasArg(options::OPT_pthread)) {
8347 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
8348 CmdArgs.push_back("-lpthread_p");
8349 else
8350 CmdArgs.push_back("-lpthread");
8351 }
8352
8353 if (!Args.hasArg(options::OPT_shared)) {
8354 if (Args.hasArg(options::OPT_pg))
8355 CmdArgs.push_back("-lc_p");
8356 else
8357 CmdArgs.push_back("-lc");
8358 }
8359
8360 StringRef MyArch;
8361 switch (getToolChain().getArch()) {
8362 case llvm::Triple::arm:
8363 MyArch = "arm";
8364 break;
8365 case llvm::Triple::x86:
8366 MyArch = "i386";
8367 break;
8368 case llvm::Triple::x86_64:
8369 MyArch = "amd64";
8370 break;
8371 default:
8372 llvm_unreachable("Unsupported architecture");
8373 }
8374 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
8375 }
8376
8377 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8378 if (!Args.hasArg(options::OPT_shared))
8379 CmdArgs.push_back(
8380 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8381 else
8382 CmdArgs.push_back(
8383 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8384 }
8385
8386 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8387 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8388 }
8389
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8390 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8391 const InputInfo &Output,
8392 const InputInfoList &Inputs,
8393 const ArgList &Args,
8394 const char *LinkingOutput) const {
8395 claimNoWarnArgs(Args);
8396 ArgStringList CmdArgs;
8397
8398 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8399 // instruct as in the base system to assemble 32-bit code.
8400 switch (getToolChain().getArch()) {
8401 default:
8402 break;
8403 case llvm::Triple::x86:
8404 CmdArgs.push_back("--32");
8405 break;
8406 case llvm::Triple::ppc:
8407 CmdArgs.push_back("-a32");
8408 break;
8409 case llvm::Triple::mips:
8410 case llvm::Triple::mipsel:
8411 case llvm::Triple::mips64:
8412 case llvm::Triple::mips64el: {
8413 StringRef CPUName;
8414 StringRef ABIName;
8415 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8416
8417 CmdArgs.push_back("-march");
8418 CmdArgs.push_back(CPUName.data());
8419
8420 CmdArgs.push_back("-mabi");
8421 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8422
8423 if (getToolChain().getArch() == llvm::Triple::mips ||
8424 getToolChain().getArch() == llvm::Triple::mips64)
8425 CmdArgs.push_back("-EB");
8426 else
8427 CmdArgs.push_back("-EL");
8428
8429 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8430 StringRef v = A->getValue();
8431 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8432 A->claim();
8433 }
8434
8435 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8436 break;
8437 }
8438 case llvm::Triple::arm:
8439 case llvm::Triple::armeb:
8440 case llvm::Triple::thumb:
8441 case llvm::Triple::thumbeb: {
8442 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
8443
8444 if (ABI == arm::FloatABI::Hard)
8445 CmdArgs.push_back("-mfpu=vfp");
8446 else
8447 CmdArgs.push_back("-mfpu=softvfp");
8448
8449 switch (getToolChain().getTriple().getEnvironment()) {
8450 case llvm::Triple::GNUEABIHF:
8451 case llvm::Triple::GNUEABI:
8452 case llvm::Triple::EABI:
8453 CmdArgs.push_back("-meabi=5");
8454 break;
8455
8456 default:
8457 CmdArgs.push_back("-matpcs");
8458 }
8459 break;
8460 }
8461 case llvm::Triple::sparc:
8462 case llvm::Triple::sparcel:
8463 case llvm::Triple::sparcv9: {
8464 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8465 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8466 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8467 break;
8468 }
8469 }
8470
8471 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8472
8473 CmdArgs.push_back("-o");
8474 CmdArgs.push_back(Output.getFilename());
8475
8476 for (const auto &II : Inputs)
8477 CmdArgs.push_back(II.getFilename());
8478
8479 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8480 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8481 }
8482
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8483 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8484 const InputInfo &Output,
8485 const InputInfoList &Inputs,
8486 const ArgList &Args,
8487 const char *LinkingOutput) const {
8488 const toolchains::FreeBSD &ToolChain =
8489 static_cast<const toolchains::FreeBSD &>(getToolChain());
8490 const Driver &D = ToolChain.getDriver();
8491 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8492 const bool IsPIE =
8493 !Args.hasArg(options::OPT_shared) &&
8494 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8495 ArgStringList CmdArgs;
8496
8497 // Silence warning for "clang -g foo.o -o foo"
8498 Args.ClaimAllArgs(options::OPT_g_Group);
8499 // and "clang -emit-llvm foo.o -o foo"
8500 Args.ClaimAllArgs(options::OPT_emit_llvm);
8501 // and for "clang -w foo.o -o foo". Other warning options are already
8502 // handled somewhere else.
8503 Args.ClaimAllArgs(options::OPT_w);
8504
8505 if (!D.SysRoot.empty())
8506 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8507
8508 if (IsPIE)
8509 CmdArgs.push_back("-pie");
8510
8511 CmdArgs.push_back("--eh-frame-hdr");
8512 if (Args.hasArg(options::OPT_static)) {
8513 CmdArgs.push_back("-Bstatic");
8514 } else {
8515 if (Args.hasArg(options::OPT_rdynamic))
8516 CmdArgs.push_back("-export-dynamic");
8517 if (Args.hasArg(options::OPT_shared)) {
8518 CmdArgs.push_back("-Bshareable");
8519 } else {
8520 CmdArgs.push_back("-dynamic-linker");
8521 CmdArgs.push_back("/libexec/ld-elf.so.1");
8522 }
8523 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
8524 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
8525 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
8526 CmdArgs.push_back("--hash-style=both");
8527 }
8528 }
8529 CmdArgs.push_back("--enable-new-dtags");
8530 }
8531
8532 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
8533 // instruct ld in the base system to link 32-bit code.
8534 if (Arch == llvm::Triple::x86) {
8535 CmdArgs.push_back("-m");
8536 CmdArgs.push_back("elf_i386_fbsd");
8537 }
8538
8539 if (Arch == llvm::Triple::ppc) {
8540 CmdArgs.push_back("-m");
8541 CmdArgs.push_back("elf32ppc_fbsd");
8542 }
8543
8544 if (Arg *A = Args.getLastArg(options::OPT_G)) {
8545 if (ToolChain.getArch() == llvm::Triple::mips ||
8546 ToolChain.getArch() == llvm::Triple::mipsel ||
8547 ToolChain.getArch() == llvm::Triple::mips64 ||
8548 ToolChain.getArch() == llvm::Triple::mips64el) {
8549 StringRef v = A->getValue();
8550 CmdArgs.push_back(Args.MakeArgString("-G" + v));
8551 A->claim();
8552 }
8553 }
8554
8555 if (Output.isFilename()) {
8556 CmdArgs.push_back("-o");
8557 CmdArgs.push_back(Output.getFilename());
8558 } else {
8559 assert(Output.isNothing() && "Invalid output.");
8560 }
8561
8562 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8563 const char *crt1 = nullptr;
8564 if (!Args.hasArg(options::OPT_shared)) {
8565 if (Args.hasArg(options::OPT_pg))
8566 crt1 = "gcrt1.o";
8567 else if (IsPIE)
8568 crt1 = "Scrt1.o";
8569 else
8570 crt1 = "crt1.o";
8571 }
8572 if (crt1)
8573 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8574
8575 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8576
8577 const char *crtbegin = nullptr;
8578 if (Args.hasArg(options::OPT_static))
8579 crtbegin = "crtbeginT.o";
8580 else if (Args.hasArg(options::OPT_shared) || IsPIE)
8581 crtbegin = "crtbeginS.o";
8582 else
8583 crtbegin = "crtbegin.o";
8584
8585 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8586 }
8587
8588 Args.AddAllArgs(CmdArgs, options::OPT_L);
8589 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8590 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8591 Args.AddAllArgs(CmdArgs, options::OPT_e);
8592 Args.AddAllArgs(CmdArgs, options::OPT_s);
8593 Args.AddAllArgs(CmdArgs, options::OPT_t);
8594 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8595 Args.AddAllArgs(CmdArgs, options::OPT_r);
8596
8597 if (D.isUsingLTO())
8598 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8599
8600 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8601 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8602
8603 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8604 addOpenMPRuntime(CmdArgs, ToolChain, Args);
8605 if (D.CCCIsCXX()) {
8606 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8607 if (Args.hasArg(options::OPT_pg))
8608 CmdArgs.push_back("-lm_p");
8609 else
8610 CmdArgs.push_back("-lm");
8611 }
8612 if (NeedsSanitizerDeps)
8613 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8614 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8615 // the default system libraries. Just mimic this for now.
8616 if (Args.hasArg(options::OPT_pg))
8617 CmdArgs.push_back("-lgcc_p");
8618 else
8619 CmdArgs.push_back("-lgcc");
8620 if (Args.hasArg(options::OPT_static)) {
8621 CmdArgs.push_back("-lgcc_eh");
8622 } else if (Args.hasArg(options::OPT_pg)) {
8623 CmdArgs.push_back("-lgcc_eh_p");
8624 } else {
8625 CmdArgs.push_back("--as-needed");
8626 CmdArgs.push_back("-lgcc_s");
8627 CmdArgs.push_back("--no-as-needed");
8628 }
8629
8630 if (Args.hasArg(options::OPT_pthread)) {
8631 if (Args.hasArg(options::OPT_pg))
8632 CmdArgs.push_back("-lpthread_p");
8633 else
8634 CmdArgs.push_back("-lpthread");
8635 }
8636
8637 if (Args.hasArg(options::OPT_pg)) {
8638 if (Args.hasArg(options::OPT_shared))
8639 CmdArgs.push_back("-lc");
8640 else
8641 CmdArgs.push_back("-lc_p");
8642 CmdArgs.push_back("-lgcc_p");
8643 } else {
8644 CmdArgs.push_back("-lc");
8645 CmdArgs.push_back("-lgcc");
8646 }
8647
8648 if (Args.hasArg(options::OPT_static)) {
8649 CmdArgs.push_back("-lgcc_eh");
8650 } else if (Args.hasArg(options::OPT_pg)) {
8651 CmdArgs.push_back("-lgcc_eh_p");
8652 } else {
8653 CmdArgs.push_back("--as-needed");
8654 CmdArgs.push_back("-lgcc_s");
8655 CmdArgs.push_back("--no-as-needed");
8656 }
8657 }
8658
8659 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8660 if (Args.hasArg(options::OPT_shared) || IsPIE)
8661 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8662 else
8663 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8664 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8665 }
8666
8667 ToolChain.addProfileRTLibs(Args, CmdArgs);
8668
8669 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8670 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8671 }
8672
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8673 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8674 const InputInfo &Output,
8675 const InputInfoList &Inputs,
8676 const ArgList &Args,
8677 const char *LinkingOutput) const {
8678 claimNoWarnArgs(Args);
8679 ArgStringList CmdArgs;
8680
8681 // GNU as needs different flags for creating the correct output format
8682 // on architectures with different ABIs or optional feature sets.
8683 switch (getToolChain().getArch()) {
8684 case llvm::Triple::x86:
8685 CmdArgs.push_back("--32");
8686 break;
8687 case llvm::Triple::arm:
8688 case llvm::Triple::armeb:
8689 case llvm::Triple::thumb:
8690 case llvm::Triple::thumbeb: {
8691 StringRef MArch, MCPU;
8692 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8693 std::string Arch =
8694 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8695 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8696 break;
8697 }
8698
8699 case llvm::Triple::mips:
8700 case llvm::Triple::mipsel:
8701 case llvm::Triple::mips64:
8702 case llvm::Triple::mips64el: {
8703 StringRef CPUName;
8704 StringRef ABIName;
8705 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8706
8707 CmdArgs.push_back("-march");
8708 CmdArgs.push_back(CPUName.data());
8709
8710 CmdArgs.push_back("-mabi");
8711 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8712
8713 if (getToolChain().getArch() == llvm::Triple::mips ||
8714 getToolChain().getArch() == llvm::Triple::mips64)
8715 CmdArgs.push_back("-EB");
8716 else
8717 CmdArgs.push_back("-EL");
8718
8719 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8720 break;
8721 }
8722
8723 case llvm::Triple::sparc:
8724 case llvm::Triple::sparcel: {
8725 CmdArgs.push_back("-32");
8726 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8727 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8728 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8729 break;
8730 }
8731
8732 case llvm::Triple::sparcv9: {
8733 CmdArgs.push_back("-64");
8734 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8735 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8736 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8737 break;
8738 }
8739
8740 default:
8741 break;
8742 }
8743
8744 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8745
8746 CmdArgs.push_back("-o");
8747 CmdArgs.push_back(Output.getFilename());
8748
8749 for (const auto &II : Inputs)
8750 CmdArgs.push_back(II.getFilename());
8751
8752 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8753 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8754 }
8755
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8756 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8757 const InputInfo &Output,
8758 const InputInfoList &Inputs,
8759 const ArgList &Args,
8760 const char *LinkingOutput) const {
8761 const Driver &D = getToolChain().getDriver();
8762 ArgStringList CmdArgs;
8763
8764 if (!D.SysRoot.empty())
8765 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8766
8767 CmdArgs.push_back("--eh-frame-hdr");
8768 if (Args.hasArg(options::OPT_static)) {
8769 CmdArgs.push_back("-Bstatic");
8770 } else {
8771 if (Args.hasArg(options::OPT_rdynamic))
8772 CmdArgs.push_back("-export-dynamic");
8773 if (Args.hasArg(options::OPT_shared)) {
8774 CmdArgs.push_back("-Bshareable");
8775 } else {
8776 Args.AddAllArgs(CmdArgs, options::OPT_pie);
8777 CmdArgs.push_back("-dynamic-linker");
8778 CmdArgs.push_back("/libexec/ld.elf_so");
8779 }
8780 }
8781
8782 // Many NetBSD architectures support more than one ABI.
8783 // Determine the correct emulation for ld.
8784 switch (getToolChain().getArch()) {
8785 case llvm::Triple::x86:
8786 CmdArgs.push_back("-m");
8787 CmdArgs.push_back("elf_i386");
8788 break;
8789 case llvm::Triple::arm:
8790 case llvm::Triple::thumb:
8791 CmdArgs.push_back("-m");
8792 switch (getToolChain().getTriple().getEnvironment()) {
8793 case llvm::Triple::EABI:
8794 case llvm::Triple::GNUEABI:
8795 CmdArgs.push_back("armelf_nbsd_eabi");
8796 break;
8797 case llvm::Triple::EABIHF:
8798 case llvm::Triple::GNUEABIHF:
8799 CmdArgs.push_back("armelf_nbsd_eabihf");
8800 break;
8801 default:
8802 CmdArgs.push_back("armelf_nbsd");
8803 break;
8804 }
8805 break;
8806 case llvm::Triple::armeb:
8807 case llvm::Triple::thumbeb:
8808 arm::appendEBLinkFlags(
8809 Args, CmdArgs,
8810 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8811 CmdArgs.push_back("-m");
8812 switch (getToolChain().getTriple().getEnvironment()) {
8813 case llvm::Triple::EABI:
8814 case llvm::Triple::GNUEABI:
8815 CmdArgs.push_back("armelfb_nbsd_eabi");
8816 break;
8817 case llvm::Triple::EABIHF:
8818 case llvm::Triple::GNUEABIHF:
8819 CmdArgs.push_back("armelfb_nbsd_eabihf");
8820 break;
8821 default:
8822 CmdArgs.push_back("armelfb_nbsd");
8823 break;
8824 }
8825 break;
8826 case llvm::Triple::mips64:
8827 case llvm::Triple::mips64el:
8828 if (mips::hasMipsAbiArg(Args, "32")) {
8829 CmdArgs.push_back("-m");
8830 if (getToolChain().getArch() == llvm::Triple::mips64)
8831 CmdArgs.push_back("elf32btsmip");
8832 else
8833 CmdArgs.push_back("elf32ltsmip");
8834 } else if (mips::hasMipsAbiArg(Args, "64")) {
8835 CmdArgs.push_back("-m");
8836 if (getToolChain().getArch() == llvm::Triple::mips64)
8837 CmdArgs.push_back("elf64btsmip");
8838 else
8839 CmdArgs.push_back("elf64ltsmip");
8840 }
8841 break;
8842 case llvm::Triple::ppc:
8843 CmdArgs.push_back("-m");
8844 CmdArgs.push_back("elf32ppc_nbsd");
8845 break;
8846
8847 case llvm::Triple::ppc64:
8848 case llvm::Triple::ppc64le:
8849 CmdArgs.push_back("-m");
8850 CmdArgs.push_back("elf64ppc");
8851 break;
8852
8853 case llvm::Triple::sparc:
8854 CmdArgs.push_back("-m");
8855 CmdArgs.push_back("elf32_sparc");
8856 break;
8857
8858 case llvm::Triple::sparcv9:
8859 CmdArgs.push_back("-m");
8860 CmdArgs.push_back("elf64_sparc");
8861 break;
8862
8863 default:
8864 break;
8865 }
8866
8867 if (Output.isFilename()) {
8868 CmdArgs.push_back("-o");
8869 CmdArgs.push_back(Output.getFilename());
8870 } else {
8871 assert(Output.isNothing() && "Invalid output.");
8872 }
8873
8874 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8875 if (!Args.hasArg(options::OPT_shared)) {
8876 CmdArgs.push_back(
8877 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8878 }
8879 CmdArgs.push_back(
8880 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8881 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
8882 CmdArgs.push_back(
8883 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8884 } else {
8885 CmdArgs.push_back(
8886 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8887 }
8888 }
8889
8890 Args.AddAllArgs(CmdArgs, options::OPT_L);
8891 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8892 Args.AddAllArgs(CmdArgs, options::OPT_e);
8893 Args.AddAllArgs(CmdArgs, options::OPT_s);
8894 Args.AddAllArgs(CmdArgs, options::OPT_t);
8895 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8896 Args.AddAllArgs(CmdArgs, options::OPT_r);
8897
8898 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8899
8900 unsigned Major, Minor, Micro;
8901 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8902 bool useLibgcc = true;
8903 if (Major >= 7 || Major == 0) {
8904 switch (getToolChain().getArch()) {
8905 case llvm::Triple::aarch64:
8906 case llvm::Triple::arm:
8907 case llvm::Triple::armeb:
8908 case llvm::Triple::thumb:
8909 case llvm::Triple::thumbeb:
8910 case llvm::Triple::ppc:
8911 case llvm::Triple::ppc64:
8912 case llvm::Triple::ppc64le:
8913 case llvm::Triple::sparc:
8914 case llvm::Triple::sparcv9:
8915 case llvm::Triple::x86:
8916 case llvm::Triple::x86_64:
8917 useLibgcc = false;
8918 break;
8919 default:
8920 break;
8921 }
8922 }
8923
8924 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8925 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8926 if (D.CCCIsCXX()) {
8927 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8928 CmdArgs.push_back("-lm");
8929 }
8930 if (Args.hasArg(options::OPT_pthread))
8931 CmdArgs.push_back("-lpthread");
8932 CmdArgs.push_back("-lc");
8933
8934 if (useLibgcc) {
8935 if (Args.hasArg(options::OPT_static)) {
8936 // libgcc_eh depends on libc, so resolve as much as possible,
8937 // pull in any new requirements from libc and then get the rest
8938 // of libgcc.
8939 CmdArgs.push_back("-lgcc_eh");
8940 CmdArgs.push_back("-lc");
8941 CmdArgs.push_back("-lgcc");
8942 } else {
8943 CmdArgs.push_back("-lgcc");
8944 CmdArgs.push_back("--as-needed");
8945 CmdArgs.push_back("-lgcc_s");
8946 CmdArgs.push_back("--no-as-needed");
8947 }
8948 }
8949 }
8950
8951 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8952 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
8953 CmdArgs.push_back(
8954 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8955 else
8956 CmdArgs.push_back(
8957 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8958 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8959 }
8960
8961 getToolChain().addProfileRTLibs(Args, CmdArgs);
8962
8963 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8964 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8965 }
8966
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const8967 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8968 const InputInfo &Output,
8969 const InputInfoList &Inputs,
8970 const ArgList &Args,
8971 const char *LinkingOutput) const {
8972 claimNoWarnArgs(Args);
8973
8974 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8975 llvm::Triple Triple = llvm::Triple(TripleStr);
8976
8977 ArgStringList CmdArgs;
8978
8979 llvm::Reloc::Model RelocationModel;
8980 unsigned PICLevel;
8981 bool IsPIE;
8982 std::tie(RelocationModel, PICLevel, IsPIE) =
8983 ParsePICArgs(getToolChain(), Triple, Args);
8984
8985 switch (getToolChain().getArch()) {
8986 default:
8987 break;
8988 // Add --32/--64 to make sure we get the format we want.
8989 // This is incomplete
8990 case llvm::Triple::x86:
8991 CmdArgs.push_back("--32");
8992 break;
8993 case llvm::Triple::x86_64:
8994 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8995 CmdArgs.push_back("--x32");
8996 else
8997 CmdArgs.push_back("--64");
8998 break;
8999 case llvm::Triple::ppc:
9000 CmdArgs.push_back("-a32");
9001 CmdArgs.push_back("-mppc");
9002 CmdArgs.push_back("-many");
9003 break;
9004 case llvm::Triple::ppc64:
9005 CmdArgs.push_back("-a64");
9006 CmdArgs.push_back("-mppc64");
9007 CmdArgs.push_back("-many");
9008 break;
9009 case llvm::Triple::ppc64le:
9010 CmdArgs.push_back("-a64");
9011 CmdArgs.push_back("-mppc64");
9012 CmdArgs.push_back("-many");
9013 CmdArgs.push_back("-mlittle-endian");
9014 break;
9015 case llvm::Triple::sparc:
9016 case llvm::Triple::sparcel: {
9017 CmdArgs.push_back("-32");
9018 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9019 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9020 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9021 break;
9022 }
9023 case llvm::Triple::sparcv9: {
9024 CmdArgs.push_back("-64");
9025 std::string CPU = getCPUName(Args, getToolChain().getTriple());
9026 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
9027 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9028 break;
9029 }
9030 case llvm::Triple::arm:
9031 case llvm::Triple::armeb:
9032 case llvm::Triple::thumb:
9033 case llvm::Triple::thumbeb: {
9034 const llvm::Triple &Triple2 = getToolChain().getTriple();
9035 switch (Triple2.getSubArch()) {
9036 case llvm::Triple::ARMSubArch_v7:
9037 CmdArgs.push_back("-mfpu=neon");
9038 break;
9039 case llvm::Triple::ARMSubArch_v8:
9040 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
9041 break;
9042 default:
9043 break;
9044 }
9045
9046 switch (arm::getARMFloatABI(getToolChain(), Args)) {
9047 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
9048 case arm::FloatABI::Soft:
9049 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
9050 break;
9051 case arm::FloatABI::SoftFP:
9052 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
9053 break;
9054 case arm::FloatABI::Hard:
9055 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
9056 break;
9057 }
9058
9059 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
9060
9061 // FIXME: remove krait check when GNU tools support krait cpu
9062 // for now replace it with -mcpu=cortex-a15 to avoid a lower
9063 // march from being picked in the absence of a cpu flag.
9064 Arg *A;
9065 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
9066 StringRef(A->getValue()).lower() == "krait")
9067 CmdArgs.push_back("-mcpu=cortex-a15");
9068 else
9069 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
9070 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
9071 break;
9072 }
9073 case llvm::Triple::mips:
9074 case llvm::Triple::mipsel:
9075 case llvm::Triple::mips64:
9076 case llvm::Triple::mips64el: {
9077 StringRef CPUName;
9078 StringRef ABIName;
9079 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
9080 ABIName = getGnuCompatibleMipsABIName(ABIName);
9081
9082 CmdArgs.push_back("-march");
9083 CmdArgs.push_back(CPUName.data());
9084
9085 CmdArgs.push_back("-mabi");
9086 CmdArgs.push_back(ABIName.data());
9087
9088 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
9089 // or -mshared (not implemented) is in effect.
9090 if (RelocationModel == llvm::Reloc::Static)
9091 CmdArgs.push_back("-mno-shared");
9092
9093 // LLVM doesn't support -mplt yet and acts as if it is always given.
9094 // However, -mplt has no effect with the N64 ABI.
9095 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
9096
9097 if (getToolChain().getArch() == llvm::Triple::mips ||
9098 getToolChain().getArch() == llvm::Triple::mips64)
9099 CmdArgs.push_back("-EB");
9100 else
9101 CmdArgs.push_back("-EL");
9102
9103 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
9104 if (StringRef(A->getValue()) == "2008")
9105 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
9106 }
9107
9108 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
9109 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
9110 options::OPT_mfp64)) {
9111 A->claim();
9112 A->render(Args, CmdArgs);
9113 } else if (mips::shouldUseFPXX(
9114 Args, getToolChain().getTriple(), CPUName, ABIName,
9115 getMipsFloatABI(getToolChain().getDriver(), Args)))
9116 CmdArgs.push_back("-mfpxx");
9117
9118 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
9119 // -mno-mips16 is actually -no-mips16.
9120 if (Arg *A =
9121 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
9122 if (A->getOption().matches(options::OPT_mips16)) {
9123 A->claim();
9124 A->render(Args, CmdArgs);
9125 } else {
9126 A->claim();
9127 CmdArgs.push_back("-no-mips16");
9128 }
9129 }
9130
9131 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
9132 options::OPT_mno_micromips);
9133 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
9134 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
9135
9136 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
9137 // Do not use AddLastArg because not all versions of MIPS assembler
9138 // support -mmsa / -mno-msa options.
9139 if (A->getOption().matches(options::OPT_mmsa))
9140 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
9141 }
9142
9143 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
9144 options::OPT_msoft_float);
9145
9146 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
9147 options::OPT_msingle_float);
9148
9149 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
9150 options::OPT_mno_odd_spreg);
9151
9152 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
9153 break;
9154 }
9155 case llvm::Triple::systemz: {
9156 // Always pass an -march option, since our default of z10 is later
9157 // than the GNU assembler's default.
9158 StringRef CPUName = getSystemZTargetCPU(Args);
9159 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
9160 break;
9161 }
9162 }
9163
9164 Args.AddAllArgs(CmdArgs, options::OPT_I);
9165 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9166
9167 CmdArgs.push_back("-o");
9168 CmdArgs.push_back(Output.getFilename());
9169
9170 for (const auto &II : Inputs)
9171 CmdArgs.push_back(II.getFilename());
9172
9173 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9174 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9175
9176 // Handle the debug info splitting at object creation time if we're
9177 // creating an object.
9178 // TODO: Currently only works on linux with newer objcopy.
9179 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
9180 getToolChain().getTriple().isOSLinux())
9181 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9182 SplitDebugName(Args, Inputs[0]));
9183 }
9184
AddLibgcc(const llvm::Triple & Triple,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)9185 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
9186 ArgStringList &CmdArgs, const ArgList &Args) {
9187 bool isAndroid = Triple.isAndroid();
9188 bool isCygMing = Triple.isOSCygMing();
9189 bool IsIAMCU = Triple.isOSIAMCU();
9190 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
9191 Args.hasArg(options::OPT_static);
9192 if (!D.CCCIsCXX())
9193 CmdArgs.push_back("-lgcc");
9194
9195 if (StaticLibgcc || isAndroid) {
9196 if (D.CCCIsCXX())
9197 CmdArgs.push_back("-lgcc");
9198 } else {
9199 if (!D.CCCIsCXX() && !isCygMing)
9200 CmdArgs.push_back("--as-needed");
9201 CmdArgs.push_back("-lgcc_s");
9202 if (!D.CCCIsCXX() && !isCygMing)
9203 CmdArgs.push_back("--no-as-needed");
9204 }
9205
9206 if (StaticLibgcc && !isAndroid && !IsIAMCU)
9207 CmdArgs.push_back("-lgcc_eh");
9208 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
9209 CmdArgs.push_back("-lgcc");
9210
9211 // According to Android ABI, we have to link with libdl if we are
9212 // linking with non-static libgcc.
9213 //
9214 // NOTE: This fixes a link error on Android MIPS as well. The non-static
9215 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
9216 if (isAndroid && !StaticLibgcc)
9217 CmdArgs.push_back("-ldl");
9218 }
9219
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)9220 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
9221 ArgStringList &CmdArgs, const ArgList &Args) {
9222 // Make use of compiler-rt if --rtlib option is used
9223 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
9224
9225 switch (RLT) {
9226 case ToolChain::RLT_CompilerRT:
9227 switch (TC.getTriple().getOS()) {
9228 default:
9229 llvm_unreachable("unsupported OS");
9230 case llvm::Triple::Win32:
9231 case llvm::Triple::Linux:
9232 addClangRT(TC, Args, CmdArgs);
9233 break;
9234 }
9235 break;
9236 case ToolChain::RLT_Libgcc:
9237 // Make sure libgcc is not used under MSVC environment by default
9238 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
9239 // Issue error diagnostic if libgcc is explicitly specified
9240 // through command line as --rtlib option argument.
9241 if (Args.hasArg(options::OPT_rtlib_EQ)) {
9242 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
9243 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
9244 }
9245 } else
9246 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
9247 break;
9248 }
9249 }
9250
getLDMOption(const llvm::Triple & T,const ArgList & Args)9251 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
9252 switch (T.getArch()) {
9253 case llvm::Triple::x86:
9254 if (T.isOSIAMCU())
9255 return "elf_iamcu";
9256 return "elf_i386";
9257 case llvm::Triple::aarch64:
9258 return "aarch64linux";
9259 case llvm::Triple::aarch64_be:
9260 return "aarch64_be_linux";
9261 case llvm::Triple::arm:
9262 case llvm::Triple::thumb:
9263 return "armelf_linux_eabi";
9264 case llvm::Triple::armeb:
9265 case llvm::Triple::thumbeb:
9266 return "armelfb_linux_eabi";
9267 case llvm::Triple::ppc:
9268 return "elf32ppclinux";
9269 case llvm::Triple::ppc64:
9270 return "elf64ppc";
9271 case llvm::Triple::ppc64le:
9272 return "elf64lppc";
9273 case llvm::Triple::sparc:
9274 case llvm::Triple::sparcel:
9275 return "elf32_sparc";
9276 case llvm::Triple::sparcv9:
9277 return "elf64_sparc";
9278 case llvm::Triple::mips:
9279 return "elf32btsmip";
9280 case llvm::Triple::mipsel:
9281 return "elf32ltsmip";
9282 case llvm::Triple::mips64:
9283 if (mips::hasMipsAbiArg(Args, "n32"))
9284 return "elf32btsmipn32";
9285 return "elf64btsmip";
9286 case llvm::Triple::mips64el:
9287 if (mips::hasMipsAbiArg(Args, "n32"))
9288 return "elf32ltsmipn32";
9289 return "elf64ltsmip";
9290 case llvm::Triple::systemz:
9291 return "elf64_s390";
9292 case llvm::Triple::x86_64:
9293 if (T.getEnvironment() == llvm::Triple::GNUX32)
9294 return "elf32_x86_64";
9295 return "elf_x86_64";
9296 default:
9297 llvm_unreachable("Unexpected arch");
9298 }
9299 }
9300
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9301 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9302 const InputInfo &Output,
9303 const InputInfoList &Inputs,
9304 const ArgList &Args,
9305 const char *LinkingOutput) const {
9306 const toolchains::Linux &ToolChain =
9307 static_cast<const toolchains::Linux &>(getToolChain());
9308 const Driver &D = ToolChain.getDriver();
9309
9310 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
9311 llvm::Triple Triple = llvm::Triple(TripleStr);
9312
9313 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9314 const bool isAndroid = ToolChain.getTriple().isAndroid();
9315 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
9316 const bool IsPIE =
9317 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
9318 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
9319 const bool HasCRTBeginEndFiles =
9320 ToolChain.getTriple().hasEnvironment() ||
9321 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
9322
9323 ArgStringList CmdArgs;
9324
9325 // Silence warning for "clang -g foo.o -o foo"
9326 Args.ClaimAllArgs(options::OPT_g_Group);
9327 // and "clang -emit-llvm foo.o -o foo"
9328 Args.ClaimAllArgs(options::OPT_emit_llvm);
9329 // and for "clang -w foo.o -o foo". Other warning options are already
9330 // handled somewhere else.
9331 Args.ClaimAllArgs(options::OPT_w);
9332
9333 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9334 if (llvm::sys::path::filename(Exec) == "lld") {
9335 CmdArgs.push_back("-flavor");
9336 CmdArgs.push_back("old-gnu");
9337 CmdArgs.push_back("-target");
9338 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
9339 }
9340
9341 if (!D.SysRoot.empty())
9342 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9343
9344 if (IsPIE)
9345 CmdArgs.push_back("-pie");
9346
9347 if (Args.hasArg(options::OPT_rdynamic))
9348 CmdArgs.push_back("-export-dynamic");
9349
9350 if (Args.hasArg(options::OPT_s))
9351 CmdArgs.push_back("-s");
9352
9353 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
9354 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
9355
9356 for (const auto &Opt : ToolChain.ExtraOpts)
9357 CmdArgs.push_back(Opt.c_str());
9358
9359 if (!Args.hasArg(options::OPT_static)) {
9360 CmdArgs.push_back("--eh-frame-hdr");
9361 }
9362
9363 CmdArgs.push_back("-m");
9364 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
9365
9366 if (Args.hasArg(options::OPT_static)) {
9367 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
9368 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
9369 CmdArgs.push_back("-Bstatic");
9370 else
9371 CmdArgs.push_back("-static");
9372 } else if (Args.hasArg(options::OPT_shared)) {
9373 CmdArgs.push_back("-shared");
9374 }
9375
9376 if (!Args.hasArg(options::OPT_static)) {
9377 if (Args.hasArg(options::OPT_rdynamic))
9378 CmdArgs.push_back("-export-dynamic");
9379
9380 if (!Args.hasArg(options::OPT_shared)) {
9381 const std::string Loader =
9382 D.DyldPrefix + ToolChain.getDynamicLinker(Args);
9383 CmdArgs.push_back("-dynamic-linker");
9384 CmdArgs.push_back(Args.MakeArgString(Loader));
9385 }
9386 }
9387
9388 CmdArgs.push_back("-o");
9389 CmdArgs.push_back(Output.getFilename());
9390
9391 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9392 if (!isAndroid && !IsIAMCU) {
9393 const char *crt1 = nullptr;
9394 if (!Args.hasArg(options::OPT_shared)) {
9395 if (Args.hasArg(options::OPT_pg))
9396 crt1 = "gcrt1.o";
9397 else if (IsPIE)
9398 crt1 = "Scrt1.o";
9399 else
9400 crt1 = "crt1.o";
9401 }
9402 if (crt1)
9403 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
9404
9405 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9406 }
9407
9408 if (IsIAMCU)
9409 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
9410 else {
9411 const char *crtbegin;
9412 if (Args.hasArg(options::OPT_static))
9413 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
9414 else if (Args.hasArg(options::OPT_shared))
9415 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
9416 else if (IsPIE)
9417 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
9418 else
9419 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
9420
9421 if (HasCRTBeginEndFiles)
9422 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9423 }
9424
9425 // Add crtfastmath.o if available and fast math is enabled.
9426 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9427 }
9428
9429 Args.AddAllArgs(CmdArgs, options::OPT_L);
9430 Args.AddAllArgs(CmdArgs, options::OPT_u);
9431
9432 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9433
9434 if (D.isUsingLTO())
9435 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
9436
9437 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9438 CmdArgs.push_back("--no-demangle");
9439
9440 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
9441 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
9442 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9443 // The profile runtime also needs access to system libraries.
9444 getToolChain().addProfileRTLibs(Args, CmdArgs);
9445
9446 if (D.CCCIsCXX() &&
9447 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9448 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9449 !Args.hasArg(options::OPT_static);
9450 if (OnlyLibstdcxxStatic)
9451 CmdArgs.push_back("-Bstatic");
9452 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9453 if (OnlyLibstdcxxStatic)
9454 CmdArgs.push_back("-Bdynamic");
9455 CmdArgs.push_back("-lm");
9456 }
9457 // Silence warnings when linking C code with a C++ '-stdlib' argument.
9458 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
9459
9460 if (!Args.hasArg(options::OPT_nostdlib)) {
9461 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9462 if (Args.hasArg(options::OPT_static))
9463 CmdArgs.push_back("--start-group");
9464
9465 if (NeedsSanitizerDeps)
9466 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
9467
9468 if (NeedsXRayDeps)
9469 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
9470
9471 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
9472 Args.hasArg(options::OPT_pthreads);
9473
9474 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9475 options::OPT_fno_openmp, false)) {
9476 // OpenMP runtimes implies pthreads when using the GNU toolchain.
9477 // FIXME: Does this really make sense for all GNU toolchains?
9478 WantPthread = true;
9479
9480 // Also link the particular OpenMP runtimes.
9481 switch (getOpenMPRuntime(ToolChain, Args)) {
9482 case OMPRT_OMP:
9483 CmdArgs.push_back("-lomp");
9484 break;
9485 case OMPRT_GOMP:
9486 CmdArgs.push_back("-lgomp");
9487
9488 // FIXME: Exclude this for platforms with libgomp that don't require
9489 // librt. Most modern Linux platforms require it, but some may not.
9490 CmdArgs.push_back("-lrt");
9491 break;
9492 case OMPRT_IOMP5:
9493 CmdArgs.push_back("-liomp5");
9494 break;
9495 case OMPRT_Unknown:
9496 // Already diagnosed.
9497 break;
9498 }
9499 }
9500
9501 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9502
9503 if (WantPthread && !isAndroid)
9504 CmdArgs.push_back("-lpthread");
9505
9506 if (Args.hasArg(options::OPT_fsplit_stack))
9507 CmdArgs.push_back("--wrap=pthread_create");
9508
9509 CmdArgs.push_back("-lc");
9510
9511 // Add IAMCU specific libs, if needed.
9512 if (IsIAMCU)
9513 CmdArgs.push_back("-lgloss");
9514
9515 if (Args.hasArg(options::OPT_static))
9516 CmdArgs.push_back("--end-group");
9517 else
9518 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
9519
9520 // Add IAMCU specific libs (outside the group), if needed.
9521 if (IsIAMCU) {
9522 CmdArgs.push_back("--as-needed");
9523 CmdArgs.push_back("-lsoftfp");
9524 CmdArgs.push_back("--no-as-needed");
9525 }
9526 }
9527
9528 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
9529 const char *crtend;
9530 if (Args.hasArg(options::OPT_shared))
9531 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
9532 else if (IsPIE)
9533 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
9534 else
9535 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
9536
9537 if (HasCRTBeginEndFiles)
9538 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9539 if (!isAndroid)
9540 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9541 }
9542 }
9543
9544 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9545 }
9546
9547 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
9548 // for the various SFI requirements like register masking. The assembly tool
9549 // inserts the file containing the macros as an input into all the assembly
9550 // jobs.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9551 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
9552 const InputInfo &Output,
9553 const InputInfoList &Inputs,
9554 const ArgList &Args,
9555 const char *LinkingOutput) const {
9556 const toolchains::NaClToolChain &ToolChain =
9557 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9558 InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9559 "nacl-arm-macros.s");
9560 InputInfoList NewInputs;
9561 NewInputs.push_back(NaClMacros);
9562 NewInputs.append(Inputs.begin(), Inputs.end());
9563 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9564 LinkingOutput);
9565 }
9566
9567 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9568 // we use static by default, do not yet support sanitizers or LTO, and a few
9569 // others. Eventually we can support more of that and hopefully migrate back
9570 // to gnutools::Linker.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9571 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9572 const InputInfo &Output,
9573 const InputInfoList &Inputs,
9574 const ArgList &Args,
9575 const char *LinkingOutput) const {
9576
9577 const toolchains::NaClToolChain &ToolChain =
9578 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9579 const Driver &D = ToolChain.getDriver();
9580 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9581 const bool IsStatic =
9582 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9583
9584 ArgStringList CmdArgs;
9585
9586 // Silence warning for "clang -g foo.o -o foo"
9587 Args.ClaimAllArgs(options::OPT_g_Group);
9588 // and "clang -emit-llvm foo.o -o foo"
9589 Args.ClaimAllArgs(options::OPT_emit_llvm);
9590 // and for "clang -w foo.o -o foo". Other warning options are already
9591 // handled somewhere else.
9592 Args.ClaimAllArgs(options::OPT_w);
9593
9594 if (!D.SysRoot.empty())
9595 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9596
9597 if (Args.hasArg(options::OPT_rdynamic))
9598 CmdArgs.push_back("-export-dynamic");
9599
9600 if (Args.hasArg(options::OPT_s))
9601 CmdArgs.push_back("-s");
9602
9603 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9604 // from there is --build-id, which we do want.
9605 CmdArgs.push_back("--build-id");
9606
9607 if (!IsStatic)
9608 CmdArgs.push_back("--eh-frame-hdr");
9609
9610 CmdArgs.push_back("-m");
9611 if (Arch == llvm::Triple::x86)
9612 CmdArgs.push_back("elf_i386_nacl");
9613 else if (Arch == llvm::Triple::arm)
9614 CmdArgs.push_back("armelf_nacl");
9615 else if (Arch == llvm::Triple::x86_64)
9616 CmdArgs.push_back("elf_x86_64_nacl");
9617 else if (Arch == llvm::Triple::mipsel)
9618 CmdArgs.push_back("mipselelf_nacl");
9619 else
9620 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9621 << "Native Client";
9622
9623 if (IsStatic)
9624 CmdArgs.push_back("-static");
9625 else if (Args.hasArg(options::OPT_shared))
9626 CmdArgs.push_back("-shared");
9627
9628 CmdArgs.push_back("-o");
9629 CmdArgs.push_back(Output.getFilename());
9630 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9631 if (!Args.hasArg(options::OPT_shared))
9632 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9633 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9634
9635 const char *crtbegin;
9636 if (IsStatic)
9637 crtbegin = "crtbeginT.o";
9638 else if (Args.hasArg(options::OPT_shared))
9639 crtbegin = "crtbeginS.o";
9640 else
9641 crtbegin = "crtbegin.o";
9642 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9643 }
9644
9645 Args.AddAllArgs(CmdArgs, options::OPT_L);
9646 Args.AddAllArgs(CmdArgs, options::OPT_u);
9647
9648 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9649
9650 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9651 CmdArgs.push_back("--no-demangle");
9652
9653 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9654
9655 if (D.CCCIsCXX() &&
9656 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9657 bool OnlyLibstdcxxStatic =
9658 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9659 if (OnlyLibstdcxxStatic)
9660 CmdArgs.push_back("-Bstatic");
9661 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9662 if (OnlyLibstdcxxStatic)
9663 CmdArgs.push_back("-Bdynamic");
9664 CmdArgs.push_back("-lm");
9665 }
9666
9667 if (!Args.hasArg(options::OPT_nostdlib)) {
9668 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9669 // Always use groups, since it has no effect on dynamic libraries.
9670 CmdArgs.push_back("--start-group");
9671 CmdArgs.push_back("-lc");
9672 // NaCl's libc++ currently requires libpthread, so just always include it
9673 // in the group for C++.
9674 if (Args.hasArg(options::OPT_pthread) ||
9675 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9676 // Gold, used by Mips, handles nested groups differently than ld, and
9677 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9678 // which is not a desired behaviour here.
9679 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9680 if (getToolChain().getArch() == llvm::Triple::mipsel)
9681 CmdArgs.push_back("-lnacl");
9682
9683 CmdArgs.push_back("-lpthread");
9684 }
9685
9686 CmdArgs.push_back("-lgcc");
9687 CmdArgs.push_back("--as-needed");
9688 if (IsStatic)
9689 CmdArgs.push_back("-lgcc_eh");
9690 else
9691 CmdArgs.push_back("-lgcc_s");
9692 CmdArgs.push_back("--no-as-needed");
9693
9694 // Mips needs to create and use pnacl_legacy library that contains
9695 // definitions from bitcode/pnaclmm.c and definitions for
9696 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9697 if (getToolChain().getArch() == llvm::Triple::mipsel)
9698 CmdArgs.push_back("-lpnacl_legacy");
9699
9700 CmdArgs.push_back("--end-group");
9701 }
9702
9703 if (!Args.hasArg(options::OPT_nostartfiles)) {
9704 const char *crtend;
9705 if (Args.hasArg(options::OPT_shared))
9706 crtend = "crtendS.o";
9707 else
9708 crtend = "crtend.o";
9709
9710 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9711 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9712 }
9713 }
9714
9715 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9716 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9717 }
9718
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9719 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9720 const InputInfo &Output,
9721 const InputInfoList &Inputs,
9722 const ArgList &Args,
9723 const char *LinkingOutput) const {
9724 claimNoWarnArgs(Args);
9725 ArgStringList CmdArgs;
9726
9727 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9728
9729 CmdArgs.push_back("-o");
9730 CmdArgs.push_back(Output.getFilename());
9731
9732 for (const auto &II : Inputs)
9733 CmdArgs.push_back(II.getFilename());
9734
9735 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9736 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9737 }
9738
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9739 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9740 const InputInfo &Output,
9741 const InputInfoList &Inputs,
9742 const ArgList &Args,
9743 const char *LinkingOutput) const {
9744 const Driver &D = getToolChain().getDriver();
9745 ArgStringList CmdArgs;
9746
9747 if (Output.isFilename()) {
9748 CmdArgs.push_back("-o");
9749 CmdArgs.push_back(Output.getFilename());
9750 } else {
9751 assert(Output.isNothing() && "Invalid output.");
9752 }
9753
9754 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9755 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9756 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9757 CmdArgs.push_back(
9758 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9759 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9760 }
9761
9762 Args.AddAllArgs(CmdArgs,
9763 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9764
9765 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9766
9767 getToolChain().addProfileRTLibs(Args, CmdArgs);
9768
9769 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9770 if (D.CCCIsCXX()) {
9771 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9772 CmdArgs.push_back("-lm");
9773 }
9774 }
9775
9776 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9777 if (Args.hasArg(options::OPT_pthread))
9778 CmdArgs.push_back("-lpthread");
9779 CmdArgs.push_back("-lc");
9780 CmdArgs.push_back("-lCompilerRT-Generic");
9781 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9782 CmdArgs.push_back(
9783 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9784 }
9785
9786 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9787 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9788 }
9789
9790 /// DragonFly Tools
9791
9792 // For now, DragonFly Assemble does just about the same as for
9793 // FreeBSD, but this may change soon.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9794 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9795 const InputInfo &Output,
9796 const InputInfoList &Inputs,
9797 const ArgList &Args,
9798 const char *LinkingOutput) const {
9799 claimNoWarnArgs(Args);
9800 ArgStringList CmdArgs;
9801
9802 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9803 // instruct as in the base system to assemble 32-bit code.
9804 if (getToolChain().getArch() == llvm::Triple::x86)
9805 CmdArgs.push_back("--32");
9806
9807 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9808
9809 CmdArgs.push_back("-o");
9810 CmdArgs.push_back(Output.getFilename());
9811
9812 for (const auto &II : Inputs)
9813 CmdArgs.push_back(II.getFilename());
9814
9815 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9816 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9817 }
9818
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9819 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9820 const InputInfo &Output,
9821 const InputInfoList &Inputs,
9822 const ArgList &Args,
9823 const char *LinkingOutput) const {
9824 const Driver &D = getToolChain().getDriver();
9825 ArgStringList CmdArgs;
9826
9827 if (!D.SysRoot.empty())
9828 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9829
9830 CmdArgs.push_back("--eh-frame-hdr");
9831 if (Args.hasArg(options::OPT_static)) {
9832 CmdArgs.push_back("-Bstatic");
9833 } else {
9834 if (Args.hasArg(options::OPT_rdynamic))
9835 CmdArgs.push_back("-export-dynamic");
9836 if (Args.hasArg(options::OPT_shared))
9837 CmdArgs.push_back("-Bshareable");
9838 else {
9839 CmdArgs.push_back("-dynamic-linker");
9840 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9841 }
9842 CmdArgs.push_back("--hash-style=gnu");
9843 CmdArgs.push_back("--enable-new-dtags");
9844 }
9845
9846 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9847 // instruct ld in the base system to link 32-bit code.
9848 if (getToolChain().getArch() == llvm::Triple::x86) {
9849 CmdArgs.push_back("-m");
9850 CmdArgs.push_back("elf_i386");
9851 }
9852
9853 if (Output.isFilename()) {
9854 CmdArgs.push_back("-o");
9855 CmdArgs.push_back(Output.getFilename());
9856 } else {
9857 assert(Output.isNothing() && "Invalid output.");
9858 }
9859
9860 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9861 if (!Args.hasArg(options::OPT_shared)) {
9862 if (Args.hasArg(options::OPT_pg))
9863 CmdArgs.push_back(
9864 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9865 else {
9866 if (Args.hasArg(options::OPT_pie))
9867 CmdArgs.push_back(
9868 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9869 else
9870 CmdArgs.push_back(
9871 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9872 }
9873 }
9874 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9875 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9876 CmdArgs.push_back(
9877 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9878 else
9879 CmdArgs.push_back(
9880 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9881 }
9882
9883 Args.AddAllArgs(CmdArgs,
9884 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9885
9886 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9887
9888 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9889 CmdArgs.push_back("-L/usr/lib/gcc50");
9890
9891 if (!Args.hasArg(options::OPT_static)) {
9892 CmdArgs.push_back("-rpath");
9893 CmdArgs.push_back("/usr/lib/gcc50");
9894 }
9895
9896 if (D.CCCIsCXX()) {
9897 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9898 CmdArgs.push_back("-lm");
9899 }
9900
9901 if (Args.hasArg(options::OPT_pthread))
9902 CmdArgs.push_back("-lpthread");
9903
9904 if (!Args.hasArg(options::OPT_nolibc)) {
9905 CmdArgs.push_back("-lc");
9906 }
9907
9908 if (Args.hasArg(options::OPT_static) ||
9909 Args.hasArg(options::OPT_static_libgcc)) {
9910 CmdArgs.push_back("-lgcc");
9911 CmdArgs.push_back("-lgcc_eh");
9912 } else {
9913 if (Args.hasArg(options::OPT_shared_libgcc)) {
9914 CmdArgs.push_back("-lgcc_pic");
9915 if (!Args.hasArg(options::OPT_shared))
9916 CmdArgs.push_back("-lgcc");
9917 } else {
9918 CmdArgs.push_back("-lgcc");
9919 CmdArgs.push_back("--as-needed");
9920 CmdArgs.push_back("-lgcc_pic");
9921 CmdArgs.push_back("--no-as-needed");
9922 }
9923 }
9924 }
9925
9926 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9927 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9928 CmdArgs.push_back(
9929 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9930 else
9931 CmdArgs.push_back(
9932 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9933 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9934 }
9935
9936 getToolChain().addProfileRTLibs(Args, CmdArgs);
9937
9938 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9939 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9940 }
9941
9942 // Try to find Exe from a Visual Studio distribution. This first tries to find
9943 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9944 // making sure that whatever executable that's found is not a same-named exe
9945 // from clang itself to prevent clang from falling back to itself.
FindVisualStudioExecutable(const ToolChain & TC,const char * Exe,const char * ClangProgramPath)9946 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9947 const char *Exe,
9948 const char *ClangProgramPath) {
9949 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9950 std::string visualStudioBinDir;
9951 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9952 visualStudioBinDir)) {
9953 SmallString<128> FilePath(visualStudioBinDir);
9954 llvm::sys::path::append(FilePath, Exe);
9955 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9956 return FilePath.str();
9957 }
9958
9959 return Exe;
9960 }
9961
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const9962 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9963 const InputInfo &Output,
9964 const InputInfoList &Inputs,
9965 const ArgList &Args,
9966 const char *LinkingOutput) const {
9967 ArgStringList CmdArgs;
9968 const ToolChain &TC = getToolChain();
9969
9970 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9971 if (Output.isFilename())
9972 CmdArgs.push_back(
9973 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9974
9975 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9976 !C.getDriver().IsCLMode())
9977 CmdArgs.push_back("-defaultlib:libcmt");
9978
9979 if (!llvm::sys::Process::GetEnv("LIB")) {
9980 // If the VC environment hasn't been configured (perhaps because the user
9981 // did not run vcvarsall), try to build a consistent link environment. If
9982 // the environment variable is set however, assume the user knows what
9983 // they're doing.
9984 std::string VisualStudioDir;
9985 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9986 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9987 SmallString<128> LibDir(VisualStudioDir);
9988 llvm::sys::path::append(LibDir, "VC", "lib");
9989 switch (MSVC.getArch()) {
9990 case llvm::Triple::x86:
9991 // x86 just puts the libraries directly in lib
9992 break;
9993 case llvm::Triple::x86_64:
9994 llvm::sys::path::append(LibDir, "amd64");
9995 break;
9996 case llvm::Triple::arm:
9997 llvm::sys::path::append(LibDir, "arm");
9998 break;
9999 default:
10000 break;
10001 }
10002 CmdArgs.push_back(
10003 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
10004
10005 if (MSVC.useUniversalCRT(VisualStudioDir)) {
10006 std::string UniversalCRTLibPath;
10007 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
10008 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10009 UniversalCRTLibPath.c_str()));
10010 }
10011 }
10012
10013 std::string WindowsSdkLibPath;
10014 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
10015 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10016 WindowsSdkLibPath.c_str()));
10017 }
10018
10019 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
10020 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
10021 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
10022
10023 CmdArgs.push_back("-nologo");
10024
10025 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7,
10026 options::OPT__SLASH_Zd))
10027 CmdArgs.push_back("-debug");
10028
10029 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
10030 options::OPT_shared);
10031 if (DLL) {
10032 CmdArgs.push_back(Args.MakeArgString("-dll"));
10033
10034 SmallString<128> ImplibName(Output.getFilename());
10035 llvm::sys::path::replace_extension(ImplibName, "lib");
10036 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
10037 }
10038
10039 if (TC.getSanitizerArgs().needsAsanRt()) {
10040 CmdArgs.push_back(Args.MakeArgString("-debug"));
10041 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
10042 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
10043 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10044 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10045 // Make sure the dynamic runtime thunk is not optimized out at link time
10046 // to ensure proper SEH handling.
10047 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
10048 } else if (DLL) {
10049 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10050 } else {
10051 for (const auto &Lib : {"asan", "asan_cxx"})
10052 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10053 }
10054 }
10055
10056 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
10057
10058 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
10059 options::OPT_fno_openmp, false)) {
10060 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
10061 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
10062 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
10063 TC.getDriver().Dir + "/../lib"));
10064 switch (getOpenMPRuntime(getToolChain(), Args)) {
10065 case OMPRT_OMP:
10066 CmdArgs.push_back("-defaultlib:libomp.lib");
10067 break;
10068 case OMPRT_IOMP5:
10069 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
10070 break;
10071 case OMPRT_GOMP:
10072 break;
10073 case OMPRT_Unknown:
10074 // Already diagnosed.
10075 break;
10076 }
10077 }
10078
10079 // Add compiler-rt lib in case if it was explicitly
10080 // specified as an argument for --rtlib option.
10081 if (!Args.hasArg(options::OPT_nostdlib)) {
10082 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
10083 }
10084
10085 // Add filenames, libraries, and other linker inputs.
10086 for (const auto &Input : Inputs) {
10087 if (Input.isFilename()) {
10088 CmdArgs.push_back(Input.getFilename());
10089 continue;
10090 }
10091
10092 const Arg &A = Input.getInputArg();
10093
10094 // Render -l options differently for the MSVC linker.
10095 if (A.getOption().matches(options::OPT_l)) {
10096 StringRef Lib = A.getValue();
10097 const char *LinkLibArg;
10098 if (Lib.endswith(".lib"))
10099 LinkLibArg = Args.MakeArgString(Lib);
10100 else
10101 LinkLibArg = Args.MakeArgString(Lib + ".lib");
10102 CmdArgs.push_back(LinkLibArg);
10103 continue;
10104 }
10105
10106 // Otherwise, this is some other kind of linker input option like -Wl, -z,
10107 // or -L. Render it, even if MSVC doesn't understand it.
10108 A.renderAsInput(Args, CmdArgs);
10109 }
10110
10111 TC.addProfileRTLibs(Args, CmdArgs);
10112
10113 // We need to special case some linker paths. In the case of lld, we need to
10114 // translate 'lld' into 'lld-link', and in the case of the regular msvc
10115 // linker, we need to use a special search algorithm.
10116 llvm::SmallString<128> linkPath;
10117 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
10118 if (Linker.equals_lower("lld"))
10119 Linker = "lld-link";
10120
10121 if (Linker.equals_lower("link")) {
10122 // If we're using the MSVC linker, it's not sufficient to just use link
10123 // from the program PATH, because other environments like GnuWin32 install
10124 // their own link.exe which may come first.
10125 linkPath = FindVisualStudioExecutable(TC, "link.exe",
10126 C.getDriver().getClangProgramPath());
10127 } else {
10128 linkPath = Linker;
10129 llvm::sys::path::replace_extension(linkPath, "exe");
10130 linkPath = TC.GetProgramPath(linkPath.c_str());
10131 }
10132
10133 const char *Exec = Args.MakeArgString(linkPath);
10134 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10135 }
10136
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10137 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10138 const InputInfo &Output,
10139 const InputInfoList &Inputs,
10140 const ArgList &Args,
10141 const char *LinkingOutput) const {
10142 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
10143 }
10144
GetCommand(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10145 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
10146 Compilation &C, const JobAction &JA, const InputInfo &Output,
10147 const InputInfoList &Inputs, const ArgList &Args,
10148 const char *LinkingOutput) const {
10149 ArgStringList CmdArgs;
10150 CmdArgs.push_back("/nologo");
10151 CmdArgs.push_back("/c"); // Compile only.
10152 CmdArgs.push_back("/W0"); // No warnings.
10153
10154 // The goal is to be able to invoke this tool correctly based on
10155 // any flag accepted by clang-cl.
10156
10157 // These are spelled the same way in clang and cl.exe,.
10158 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
10159
10160 // Optimization level.
10161 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
10162 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
10163 : "/Oi-");
10164 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
10165 if (A->getOption().getID() == options::OPT_O0) {
10166 CmdArgs.push_back("/Od");
10167 } else {
10168 CmdArgs.push_back("/Og");
10169
10170 StringRef OptLevel = A->getValue();
10171 if (OptLevel == "s" || OptLevel == "z")
10172 CmdArgs.push_back("/Os");
10173 else
10174 CmdArgs.push_back("/Ot");
10175
10176 CmdArgs.push_back("/Ob2");
10177 }
10178 }
10179 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
10180 options::OPT_fno_omit_frame_pointer))
10181 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
10182 ? "/Oy"
10183 : "/Oy-");
10184 if (!Args.hasArg(options::OPT_fwritable_strings))
10185 CmdArgs.push_back("/GF");
10186
10187 // Flags for which clang-cl has an alias.
10188 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
10189
10190 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
10191 /*default=*/false))
10192 CmdArgs.push_back("/GR-");
10193
10194 if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
10195 /*default=*/false))
10196 CmdArgs.push_back("/GS-");
10197
10198 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
10199 options::OPT_fno_function_sections))
10200 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
10201 ? "/Gy"
10202 : "/Gy-");
10203 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
10204 options::OPT_fno_data_sections))
10205 CmdArgs.push_back(
10206 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
10207 if (Args.hasArg(options::OPT_fsyntax_only))
10208 CmdArgs.push_back("/Zs");
10209 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
10210 options::OPT__SLASH_Z7))
10211 CmdArgs.push_back("/Z7");
10212
10213 std::vector<std::string> Includes =
10214 Args.getAllArgValues(options::OPT_include);
10215 for (const auto &Include : Includes)
10216 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
10217
10218 // Flags that can simply be passed through.
10219 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
10220 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
10221 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
10222 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
10223 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
10224 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
10225
10226 // The order of these flags is relevant, so pick the last one.
10227 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
10228 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
10229 A->render(Args, CmdArgs);
10230
10231 // Pass through all unknown arguments so that the fallback command can see
10232 // them too.
10233 Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
10234
10235 // Input filename.
10236 assert(Inputs.size() == 1);
10237 const InputInfo &II = Inputs[0];
10238 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
10239 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
10240 if (II.isFilename())
10241 CmdArgs.push_back(II.getFilename());
10242 else
10243 II.getInputArg().renderAsInput(Args, CmdArgs);
10244
10245 // Output filename.
10246 assert(Output.getType() == types::TY_Object);
10247 const char *Fo =
10248 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
10249 CmdArgs.push_back(Fo);
10250
10251 const Driver &D = getToolChain().getDriver();
10252 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
10253 D.getClangProgramPath());
10254 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10255 CmdArgs, Inputs);
10256 }
10257
10258 /// MinGW Tools
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10259 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10260 const InputInfo &Output,
10261 const InputInfoList &Inputs,
10262 const ArgList &Args,
10263 const char *LinkingOutput) const {
10264 claimNoWarnArgs(Args);
10265 ArgStringList CmdArgs;
10266
10267 if (getToolChain().getArch() == llvm::Triple::x86) {
10268 CmdArgs.push_back("--32");
10269 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
10270 CmdArgs.push_back("--64");
10271 }
10272
10273 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10274
10275 CmdArgs.push_back("-o");
10276 CmdArgs.push_back(Output.getFilename());
10277
10278 for (const auto &II : Inputs)
10279 CmdArgs.push_back(II.getFilename());
10280
10281 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
10282 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10283
10284 if (Args.hasArg(options::OPT_gsplit_dwarf))
10285 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
10286 SplitDebugName(Args, Inputs[0]));
10287 }
10288
AddLibGCC(const ArgList & Args,ArgStringList & CmdArgs) const10289 void MinGW::Linker::AddLibGCC(const ArgList &Args,
10290 ArgStringList &CmdArgs) const {
10291 if (Args.hasArg(options::OPT_mthreads))
10292 CmdArgs.push_back("-lmingwthrd");
10293 CmdArgs.push_back("-lmingw32");
10294
10295 // Make use of compiler-rt if --rtlib option is used
10296 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
10297 if (RLT == ToolChain::RLT_Libgcc) {
10298 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
10299 Args.hasArg(options::OPT_static);
10300 bool Shared = Args.hasArg(options::OPT_shared);
10301 bool CXX = getToolChain().getDriver().CCCIsCXX();
10302
10303 if (Static || (!CXX && !Shared)) {
10304 CmdArgs.push_back("-lgcc");
10305 CmdArgs.push_back("-lgcc_eh");
10306 } else {
10307 CmdArgs.push_back("-lgcc_s");
10308 CmdArgs.push_back("-lgcc");
10309 }
10310 } else {
10311 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
10312 }
10313
10314 CmdArgs.push_back("-lmoldname");
10315 CmdArgs.push_back("-lmingwex");
10316 CmdArgs.push_back("-lmsvcrt");
10317 }
10318
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10319 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10320 const InputInfo &Output,
10321 const InputInfoList &Inputs,
10322 const ArgList &Args,
10323 const char *LinkingOutput) const {
10324 const ToolChain &TC = getToolChain();
10325 const Driver &D = TC.getDriver();
10326 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
10327
10328 ArgStringList CmdArgs;
10329
10330 // Silence warning for "clang -g foo.o -o foo"
10331 Args.ClaimAllArgs(options::OPT_g_Group);
10332 // and "clang -emit-llvm foo.o -o foo"
10333 Args.ClaimAllArgs(options::OPT_emit_llvm);
10334 // and for "clang -w foo.o -o foo". Other warning options are already
10335 // handled somewhere else.
10336 Args.ClaimAllArgs(options::OPT_w);
10337
10338 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
10339 if (LinkerName.equals_lower("lld")) {
10340 CmdArgs.push_back("-flavor");
10341 CmdArgs.push_back("gnu");
10342 } else if (!LinkerName.equals_lower("ld")) {
10343 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
10344 }
10345
10346 if (!D.SysRoot.empty())
10347 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10348
10349 if (Args.hasArg(options::OPT_s))
10350 CmdArgs.push_back("-s");
10351
10352 CmdArgs.push_back("-m");
10353 if (TC.getArch() == llvm::Triple::x86)
10354 CmdArgs.push_back("i386pe");
10355 if (TC.getArch() == llvm::Triple::x86_64)
10356 CmdArgs.push_back("i386pep");
10357 if (TC.getArch() == llvm::Triple::arm)
10358 CmdArgs.push_back("thumb2pe");
10359
10360 if (Args.hasArg(options::OPT_mwindows)) {
10361 CmdArgs.push_back("--subsystem");
10362 CmdArgs.push_back("windows");
10363 } else if (Args.hasArg(options::OPT_mconsole)) {
10364 CmdArgs.push_back("--subsystem");
10365 CmdArgs.push_back("console");
10366 }
10367
10368 if (Args.hasArg(options::OPT_static))
10369 CmdArgs.push_back("-Bstatic");
10370 else {
10371 if (Args.hasArg(options::OPT_mdll))
10372 CmdArgs.push_back("--dll");
10373 else if (Args.hasArg(options::OPT_shared))
10374 CmdArgs.push_back("--shared");
10375 CmdArgs.push_back("-Bdynamic");
10376 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
10377 CmdArgs.push_back("-e");
10378 if (TC.getArch() == llvm::Triple::x86)
10379 CmdArgs.push_back("_DllMainCRTStartup@12");
10380 else
10381 CmdArgs.push_back("DllMainCRTStartup");
10382 CmdArgs.push_back("--enable-auto-image-base");
10383 }
10384 }
10385
10386 CmdArgs.push_back("-o");
10387 CmdArgs.push_back(Output.getFilename());
10388
10389 Args.AddAllArgs(CmdArgs, options::OPT_e);
10390 // FIXME: add -N, -n flags
10391 Args.AddLastArg(CmdArgs, options::OPT_r);
10392 Args.AddLastArg(CmdArgs, options::OPT_s);
10393 Args.AddLastArg(CmdArgs, options::OPT_t);
10394 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
10395 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
10396
10397 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10398 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
10399 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
10400 } else {
10401 if (Args.hasArg(options::OPT_municode))
10402 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
10403 else
10404 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
10405 }
10406 if (Args.hasArg(options::OPT_pg))
10407 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
10408 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10409 }
10410
10411 Args.AddAllArgs(CmdArgs, options::OPT_L);
10412 TC.AddFilePathLibArgs(Args, CmdArgs);
10413 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10414
10415 // TODO: Add ASan stuff here
10416
10417 // TODO: Add profile stuff here
10418
10419 if (D.CCCIsCXX() &&
10420 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10421 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
10422 !Args.hasArg(options::OPT_static);
10423 if (OnlyLibstdcxxStatic)
10424 CmdArgs.push_back("-Bstatic");
10425 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10426 if (OnlyLibstdcxxStatic)
10427 CmdArgs.push_back("-Bdynamic");
10428 }
10429
10430 if (!Args.hasArg(options::OPT_nostdlib)) {
10431 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10432 if (Args.hasArg(options::OPT_static))
10433 CmdArgs.push_back("--start-group");
10434
10435 if (Args.hasArg(options::OPT_fstack_protector) ||
10436 Args.hasArg(options::OPT_fstack_protector_strong) ||
10437 Args.hasArg(options::OPT_fstack_protector_all)) {
10438 CmdArgs.push_back("-lssp_nonshared");
10439 CmdArgs.push_back("-lssp");
10440 }
10441 if (Args.hasArg(options::OPT_fopenmp))
10442 CmdArgs.push_back("-lgomp");
10443
10444 AddLibGCC(Args, CmdArgs);
10445
10446 if (Args.hasArg(options::OPT_pg))
10447 CmdArgs.push_back("-lgmon");
10448
10449 if (Args.hasArg(options::OPT_pthread))
10450 CmdArgs.push_back("-lpthread");
10451
10452 // add system libraries
10453 if (Args.hasArg(options::OPT_mwindows)) {
10454 CmdArgs.push_back("-lgdi32");
10455 CmdArgs.push_back("-lcomdlg32");
10456 }
10457 CmdArgs.push_back("-ladvapi32");
10458 CmdArgs.push_back("-lshell32");
10459 CmdArgs.push_back("-luser32");
10460 CmdArgs.push_back("-lkernel32");
10461
10462 if (Args.hasArg(options::OPT_static))
10463 CmdArgs.push_back("--end-group");
10464 else if (!LinkerName.equals_lower("lld"))
10465 AddLibGCC(Args, CmdArgs);
10466 }
10467
10468 if (!Args.hasArg(options::OPT_nostartfiles)) {
10469 // Add crtfastmath.o if available and fast math is enabled.
10470 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
10471
10472 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10473 }
10474 }
10475 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
10476 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10477 }
10478
10479 /// XCore Tools
10480 // We pass assemble and link construction to the xcc tool.
10481
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10482 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10483 const InputInfo &Output,
10484 const InputInfoList &Inputs,
10485 const ArgList &Args,
10486 const char *LinkingOutput) const {
10487 claimNoWarnArgs(Args);
10488 ArgStringList CmdArgs;
10489
10490 CmdArgs.push_back("-o");
10491 CmdArgs.push_back(Output.getFilename());
10492
10493 CmdArgs.push_back("-c");
10494
10495 if (Args.hasArg(options::OPT_v))
10496 CmdArgs.push_back("-v");
10497
10498 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
10499 if (!A->getOption().matches(options::OPT_g0))
10500 CmdArgs.push_back("-g");
10501
10502 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
10503 false))
10504 CmdArgs.push_back("-fverbose-asm");
10505
10506 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10507
10508 for (const auto &II : Inputs)
10509 CmdArgs.push_back(II.getFilename());
10510
10511 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10512 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10513 }
10514
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10515 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10516 const InputInfo &Output,
10517 const InputInfoList &Inputs,
10518 const ArgList &Args,
10519 const char *LinkingOutput) const {
10520 ArgStringList CmdArgs;
10521
10522 if (Output.isFilename()) {
10523 CmdArgs.push_back("-o");
10524 CmdArgs.push_back(Output.getFilename());
10525 } else {
10526 assert(Output.isNothing() && "Invalid output.");
10527 }
10528
10529 if (Args.hasArg(options::OPT_v))
10530 CmdArgs.push_back("-v");
10531
10532 // Pass -fexceptions through to the linker if it was present.
10533 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
10534 false))
10535 CmdArgs.push_back("-fexceptions");
10536
10537 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10538
10539 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
10540 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10541 }
10542
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10543 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10544 const InputInfo &Output,
10545 const InputInfoList &Inputs,
10546 const ArgList &Args,
10547 const char *LinkingOutput) const {
10548 claimNoWarnArgs(Args);
10549 const auto &TC =
10550 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10551 ArgStringList CmdArgs;
10552 const char *Exec;
10553
10554 switch (TC.getArch()) {
10555 default:
10556 llvm_unreachable("unsupported architecture");
10557 case llvm::Triple::arm:
10558 case llvm::Triple::thumb:
10559 break;
10560 case llvm::Triple::x86:
10561 CmdArgs.push_back("--32");
10562 break;
10563 case llvm::Triple::x86_64:
10564 CmdArgs.push_back("--64");
10565 break;
10566 }
10567
10568 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10569
10570 CmdArgs.push_back("-o");
10571 CmdArgs.push_back(Output.getFilename());
10572
10573 for (const auto &Input : Inputs)
10574 CmdArgs.push_back(Input.getFilename());
10575
10576 const std::string Assembler = TC.GetProgramPath("as");
10577 Exec = Args.MakeArgString(Assembler);
10578
10579 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10580 }
10581
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10582 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10583 const InputInfo &Output,
10584 const InputInfoList &Inputs,
10585 const ArgList &Args,
10586 const char *LinkingOutput) const {
10587 const auto &TC =
10588 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10589 const llvm::Triple &T = TC.getTriple();
10590 const Driver &D = TC.getDriver();
10591 SmallString<128> EntryPoint;
10592 ArgStringList CmdArgs;
10593 const char *Exec;
10594
10595 // Silence warning for "clang -g foo.o -o foo"
10596 Args.ClaimAllArgs(options::OPT_g_Group);
10597 // and "clang -emit-llvm foo.o -o foo"
10598 Args.ClaimAllArgs(options::OPT_emit_llvm);
10599 // and for "clang -w foo.o -o foo"
10600 Args.ClaimAllArgs(options::OPT_w);
10601 // Other warning options are already handled somewhere else.
10602
10603 if (!D.SysRoot.empty())
10604 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10605
10606 if (Args.hasArg(options::OPT_pie))
10607 CmdArgs.push_back("-pie");
10608 if (Args.hasArg(options::OPT_rdynamic))
10609 CmdArgs.push_back("-export-dynamic");
10610 if (Args.hasArg(options::OPT_s))
10611 CmdArgs.push_back("--strip-all");
10612
10613 CmdArgs.push_back("-m");
10614 switch (TC.getArch()) {
10615 default:
10616 llvm_unreachable("unsupported architecture");
10617 case llvm::Triple::arm:
10618 case llvm::Triple::thumb:
10619 // FIXME: this is incorrect for WinCE
10620 CmdArgs.push_back("thumb2pe");
10621 break;
10622 case llvm::Triple::x86:
10623 CmdArgs.push_back("i386pe");
10624 EntryPoint.append("_");
10625 break;
10626 case llvm::Triple::x86_64:
10627 CmdArgs.push_back("i386pep");
10628 break;
10629 }
10630
10631 if (Args.hasArg(options::OPT_shared)) {
10632 switch (T.getArch()) {
10633 default:
10634 llvm_unreachable("unsupported architecture");
10635 case llvm::Triple::arm:
10636 case llvm::Triple::thumb:
10637 case llvm::Triple::x86_64:
10638 EntryPoint.append("_DllMainCRTStartup");
10639 break;
10640 case llvm::Triple::x86:
10641 EntryPoint.append("_DllMainCRTStartup@12");
10642 break;
10643 }
10644
10645 CmdArgs.push_back("-shared");
10646 CmdArgs.push_back("-Bdynamic");
10647
10648 CmdArgs.push_back("--enable-auto-image-base");
10649
10650 CmdArgs.push_back("--entry");
10651 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10652 } else {
10653 EntryPoint.append("mainCRTStartup");
10654
10655 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10656 : "-Bdynamic");
10657
10658 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10659 CmdArgs.push_back("--entry");
10660 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10661 }
10662
10663 // FIXME: handle subsystem
10664 }
10665
10666 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10667 CmdArgs.push_back("--allow-multiple-definition");
10668
10669 CmdArgs.push_back("-o");
10670 CmdArgs.push_back(Output.getFilename());
10671
10672 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10673 SmallString<261> ImpLib(Output.getFilename());
10674 llvm::sys::path::replace_extension(ImpLib, ".lib");
10675
10676 CmdArgs.push_back("--out-implib");
10677 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10678 }
10679
10680 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10681 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10682 const char *CRTBegin;
10683
10684 CRTBegin =
10685 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10686 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10687 }
10688
10689 Args.AddAllArgs(CmdArgs, options::OPT_L);
10690 TC.AddFilePathLibArgs(Args, CmdArgs);
10691 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10692
10693 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10694 !Args.hasArg(options::OPT_nodefaultlibs)) {
10695 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10696 !Args.hasArg(options::OPT_static);
10697 if (StaticCXX)
10698 CmdArgs.push_back("-Bstatic");
10699 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10700 if (StaticCXX)
10701 CmdArgs.push_back("-Bdynamic");
10702 }
10703
10704 if (!Args.hasArg(options::OPT_nostdlib)) {
10705 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10706 // TODO handle /MT[d] /MD[d]
10707 CmdArgs.push_back("-lmsvcrt");
10708 AddRunTimeLibs(TC, D, CmdArgs, Args);
10709 }
10710 }
10711
10712 if (TC.getSanitizerArgs().needsAsanRt()) {
10713 // TODO handle /MT[d] /MD[d]
10714 if (Args.hasArg(options::OPT_shared)) {
10715 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10716 } else {
10717 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10718 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10719 // Make sure the dynamic runtime thunk is not optimized out at link time
10720 // to ensure proper SEH handling.
10721 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10722 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10723 ? "___asan_seh_interceptor"
10724 : "__asan_seh_interceptor"));
10725 }
10726 }
10727
10728 Exec = Args.MakeArgString(TC.GetLinkerPath());
10729
10730 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10731 }
10732
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10733 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10734 const InputInfo &Output,
10735 const InputInfoList &Inputs,
10736 const ArgList &Args,
10737 const char *LinkingOutput) const {
10738 ArgStringList CmdArgs;
10739 assert(Inputs.size() == 1);
10740 const InputInfo &II = Inputs[0];
10741 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10742 II.getType() == types::TY_PP_CXX);
10743
10744 if (JA.getKind() == Action::PreprocessJobClass) {
10745 Args.ClaimAllArgs();
10746 CmdArgs.push_back("-E");
10747 } else {
10748 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10749 CmdArgs.push_back("-S");
10750 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10751 }
10752 CmdArgs.push_back("-DMYRIAD2");
10753
10754 // Append all -I, -iquote, -isystem paths, defines/undefines,
10755 // 'f' flags, optimize flags, and warning options.
10756 // These are spelled the same way in clang and moviCompile.
10757 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10758 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10759 options::OPT_f_Group, options::OPT_f_clang_Group,
10760 options::OPT_g_Group, options::OPT_M_Group,
10761 options::OPT_O_Group, options::OPT_W_Group,
10762 options::OPT_mcpu_EQ});
10763
10764 // If we're producing a dependency file, and assembly is the final action,
10765 // then the name of the target in the dependency file should be the '.o'
10766 // file, not the '.s' file produced by this step. For example, instead of
10767 // /tmp/mumble.s: mumble.c .../someheader.h
10768 // the filename on the lefthand side should be "mumble.o"
10769 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10770 C.getActions().size() == 1 &&
10771 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10772 Arg *A = Args.getLastArg(options::OPT_o);
10773 if (A) {
10774 CmdArgs.push_back("-MT");
10775 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10776 }
10777 }
10778
10779 CmdArgs.push_back(II.getFilename());
10780 CmdArgs.push_back("-o");
10781 CmdArgs.push_back(Output.getFilename());
10782
10783 std::string Exec =
10784 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10785 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10786 CmdArgs, Inputs));
10787 }
10788
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10789 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10790 const InputInfo &Output,
10791 const InputInfoList &Inputs,
10792 const ArgList &Args,
10793 const char *LinkingOutput) const {
10794 ArgStringList CmdArgs;
10795
10796 assert(Inputs.size() == 1);
10797 const InputInfo &II = Inputs[0];
10798 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10799 assert(Output.getType() == types::TY_Object);
10800
10801 CmdArgs.push_back("-no6thSlotCompression");
10802 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
10803 if (CPUArg)
10804 CmdArgs.push_back(
10805 Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
10806 CmdArgs.push_back("-noSPrefixing");
10807 CmdArgs.push_back("-a"); // Mystery option.
10808 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10809 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10810 A->claim();
10811 CmdArgs.push_back(
10812 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10813 }
10814 CmdArgs.push_back("-elf"); // Output format.
10815 CmdArgs.push_back(II.getFilename());
10816 CmdArgs.push_back(
10817 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10818
10819 std::string Exec =
10820 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10821 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10822 CmdArgs, Inputs));
10823 }
10824
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10825 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10826 const InputInfo &Output,
10827 const InputInfoList &Inputs,
10828 const ArgList &Args,
10829 const char *LinkingOutput) const {
10830 const auto &TC =
10831 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10832 const llvm::Triple &T = TC.getTriple();
10833 ArgStringList CmdArgs;
10834 bool UseStartfiles =
10835 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10836 bool UseDefaultLibs =
10837 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10838
10839 if (T.getArch() == llvm::Triple::sparc)
10840 CmdArgs.push_back("-EB");
10841 else // SHAVE assumes little-endian, and sparcel is expressly so.
10842 CmdArgs.push_back("-EL");
10843
10844 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10845 // but we never pass through a --sysroot option and various other bits.
10846 // For example, there are no sanitizers (yet) nor gold linker.
10847
10848 // Eat some arguments that may be present but have no effect.
10849 Args.ClaimAllArgs(options::OPT_g_Group);
10850 Args.ClaimAllArgs(options::OPT_w);
10851 Args.ClaimAllArgs(options::OPT_static_libgcc);
10852
10853 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10854 CmdArgs.push_back("-s");
10855
10856 CmdArgs.push_back("-o");
10857 CmdArgs.push_back(Output.getFilename());
10858
10859 if (UseStartfiles) {
10860 // If you want startfiles, it means you want the builtin crti and crtbegin,
10861 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10862 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10863 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10864 }
10865
10866 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10867 options::OPT_e, options::OPT_s, options::OPT_t,
10868 options::OPT_Z_Flag, options::OPT_r});
10869
10870 TC.AddFilePathLibArgs(Args, CmdArgs);
10871
10872 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10873
10874 if (UseDefaultLibs) {
10875 if (C.getDriver().CCCIsCXX())
10876 CmdArgs.push_back("-lstdc++");
10877 if (T.getOS() == llvm::Triple::RTEMS) {
10878 CmdArgs.push_back("--start-group");
10879 CmdArgs.push_back("-lc");
10880 // You must provide your own "-L" option to enable finding these.
10881 CmdArgs.push_back("-lrtemscpu");
10882 CmdArgs.push_back("-lrtemsbsp");
10883 CmdArgs.push_back("--end-group");
10884 } else {
10885 CmdArgs.push_back("-lc");
10886 }
10887 CmdArgs.push_back("-lgcc");
10888 }
10889 if (UseStartfiles) {
10890 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10891 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10892 }
10893
10894 std::string Exec =
10895 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10896 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10897 CmdArgs, Inputs));
10898 }
10899
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const10900 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10901 const InputInfo &Output,
10902 const InputInfoList &Inputs,
10903 const ArgList &Args,
10904 const char *LinkingOutput) const {
10905 claimNoWarnArgs(Args);
10906 ArgStringList CmdArgs;
10907
10908 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10909
10910 CmdArgs.push_back("-o");
10911 CmdArgs.push_back(Output.getFilename());
10912
10913 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10914 const InputInfo &Input = Inputs[0];
10915 assert(Input.isFilename() && "Invalid input.");
10916 CmdArgs.push_back(Input.getFilename());
10917
10918 const char *Exec =
10919 Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
10920 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10921 }
10922
AddPS4SanitizerArgs(const ToolChain & TC,ArgStringList & CmdArgs)10923 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10924 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10925 if (SanArgs.needsUbsanRt()) {
10926 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10927 }
10928 if (SanArgs.needsAsanRt()) {
10929 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10930 }
10931 }
10932
ConstructPS4LinkJob(const Tool & T,Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput)10933 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10934 const JobAction &JA, const InputInfo &Output,
10935 const InputInfoList &Inputs,
10936 const ArgList &Args,
10937 const char *LinkingOutput) {
10938 const toolchains::FreeBSD &ToolChain =
10939 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10940 const Driver &D = ToolChain.getDriver();
10941 ArgStringList CmdArgs;
10942
10943 // Silence warning for "clang -g foo.o -o foo"
10944 Args.ClaimAllArgs(options::OPT_g_Group);
10945 // and "clang -emit-llvm foo.o -o foo"
10946 Args.ClaimAllArgs(options::OPT_emit_llvm);
10947 // and for "clang -w foo.o -o foo". Other warning options are already
10948 // handled somewhere else.
10949 Args.ClaimAllArgs(options::OPT_w);
10950
10951 if (!D.SysRoot.empty())
10952 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10953
10954 if (Args.hasArg(options::OPT_pie))
10955 CmdArgs.push_back("-pie");
10956
10957 if (Args.hasArg(options::OPT_rdynamic))
10958 CmdArgs.push_back("-export-dynamic");
10959 if (Args.hasArg(options::OPT_shared))
10960 CmdArgs.push_back("--oformat=so");
10961
10962 if (Output.isFilename()) {
10963 CmdArgs.push_back("-o");
10964 CmdArgs.push_back(Output.getFilename());
10965 } else {
10966 assert(Output.isNothing() && "Invalid output.");
10967 }
10968
10969 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10970
10971 Args.AddAllArgs(CmdArgs, options::OPT_L);
10972 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10973 Args.AddAllArgs(CmdArgs, options::OPT_e);
10974 Args.AddAllArgs(CmdArgs, options::OPT_s);
10975 Args.AddAllArgs(CmdArgs, options::OPT_t);
10976 Args.AddAllArgs(CmdArgs, options::OPT_r);
10977
10978 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10979 CmdArgs.push_back("--no-demangle");
10980
10981 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10982
10983 if (Args.hasArg(options::OPT_pthread)) {
10984 CmdArgs.push_back("-lpthread");
10985 }
10986
10987 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
10988
10989 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10990 }
10991
ConstructGoldLinkJob(const Tool & T,Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput)10992 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10993 const JobAction &JA, const InputInfo &Output,
10994 const InputInfoList &Inputs,
10995 const ArgList &Args,
10996 const char *LinkingOutput) {
10997 const toolchains::FreeBSD &ToolChain =
10998 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10999 const Driver &D = ToolChain.getDriver();
11000 ArgStringList CmdArgs;
11001
11002 // Silence warning for "clang -g foo.o -o foo"
11003 Args.ClaimAllArgs(options::OPT_g_Group);
11004 // and "clang -emit-llvm foo.o -o foo"
11005 Args.ClaimAllArgs(options::OPT_emit_llvm);
11006 // and for "clang -w foo.o -o foo". Other warning options are already
11007 // handled somewhere else.
11008 Args.ClaimAllArgs(options::OPT_w);
11009
11010 if (!D.SysRoot.empty())
11011 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
11012
11013 if (Args.hasArg(options::OPT_pie))
11014 CmdArgs.push_back("-pie");
11015
11016 if (Args.hasArg(options::OPT_static)) {
11017 CmdArgs.push_back("-Bstatic");
11018 } else {
11019 if (Args.hasArg(options::OPT_rdynamic))
11020 CmdArgs.push_back("-export-dynamic");
11021 CmdArgs.push_back("--eh-frame-hdr");
11022 if (Args.hasArg(options::OPT_shared)) {
11023 CmdArgs.push_back("-Bshareable");
11024 } else {
11025 CmdArgs.push_back("-dynamic-linker");
11026 CmdArgs.push_back("/libexec/ld-elf.so.1");
11027 }
11028 CmdArgs.push_back("--enable-new-dtags");
11029 }
11030
11031 if (Output.isFilename()) {
11032 CmdArgs.push_back("-o");
11033 CmdArgs.push_back(Output.getFilename());
11034 } else {
11035 assert(Output.isNothing() && "Invalid output.");
11036 }
11037
11038 AddPS4SanitizerArgs(ToolChain, CmdArgs);
11039
11040 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11041 const char *crt1 = nullptr;
11042 if (!Args.hasArg(options::OPT_shared)) {
11043 if (Args.hasArg(options::OPT_pg))
11044 crt1 = "gcrt1.o";
11045 else if (Args.hasArg(options::OPT_pie))
11046 crt1 = "Scrt1.o";
11047 else
11048 crt1 = "crt1.o";
11049 }
11050 if (crt1)
11051 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
11052
11053 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
11054
11055 const char *crtbegin = nullptr;
11056 if (Args.hasArg(options::OPT_static))
11057 crtbegin = "crtbeginT.o";
11058 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11059 crtbegin = "crtbeginS.o";
11060 else
11061 crtbegin = "crtbegin.o";
11062
11063 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
11064 }
11065
11066 Args.AddAllArgs(CmdArgs, options::OPT_L);
11067 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
11068 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
11069 Args.AddAllArgs(CmdArgs, options::OPT_e);
11070 Args.AddAllArgs(CmdArgs, options::OPT_s);
11071 Args.AddAllArgs(CmdArgs, options::OPT_t);
11072 Args.AddAllArgs(CmdArgs, options::OPT_r);
11073
11074 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
11075 CmdArgs.push_back("--no-demangle");
11076
11077 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
11078
11079 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
11080 // For PS4, we always want to pass libm, libstdc++ and libkernel
11081 // libraries for both C and C++ compilations.
11082 CmdArgs.push_back("-lkernel");
11083 if (D.CCCIsCXX()) {
11084 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
11085 if (Args.hasArg(options::OPT_pg))
11086 CmdArgs.push_back("-lm_p");
11087 else
11088 CmdArgs.push_back("-lm");
11089 }
11090 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
11091 // the default system libraries. Just mimic this for now.
11092 if (Args.hasArg(options::OPT_pg))
11093 CmdArgs.push_back("-lgcc_p");
11094 else
11095 CmdArgs.push_back("-lcompiler_rt");
11096 if (Args.hasArg(options::OPT_static)) {
11097 CmdArgs.push_back("-lstdc++");
11098 } else if (Args.hasArg(options::OPT_pg)) {
11099 CmdArgs.push_back("-lgcc_eh_p");
11100 } else {
11101 CmdArgs.push_back("--as-needed");
11102 CmdArgs.push_back("-lstdc++");
11103 CmdArgs.push_back("--no-as-needed");
11104 }
11105
11106 if (Args.hasArg(options::OPT_pthread)) {
11107 if (Args.hasArg(options::OPT_pg))
11108 CmdArgs.push_back("-lpthread_p");
11109 else
11110 CmdArgs.push_back("-lpthread");
11111 }
11112
11113 if (Args.hasArg(options::OPT_pg)) {
11114 if (Args.hasArg(options::OPT_shared))
11115 CmdArgs.push_back("-lc");
11116 else {
11117 if (Args.hasArg(options::OPT_static)) {
11118 CmdArgs.push_back("--start-group");
11119 CmdArgs.push_back("-lc_p");
11120 CmdArgs.push_back("-lpthread_p");
11121 CmdArgs.push_back("--end-group");
11122 } else {
11123 CmdArgs.push_back("-lc_p");
11124 }
11125 }
11126 CmdArgs.push_back("-lgcc_p");
11127 } else {
11128 if (Args.hasArg(options::OPT_static)) {
11129 CmdArgs.push_back("--start-group");
11130 CmdArgs.push_back("-lc");
11131 CmdArgs.push_back("-lpthread");
11132 CmdArgs.push_back("--end-group");
11133 } else {
11134 CmdArgs.push_back("-lc");
11135 }
11136 CmdArgs.push_back("-lcompiler_rt");
11137 }
11138
11139 if (Args.hasArg(options::OPT_static)) {
11140 CmdArgs.push_back("-lstdc++");
11141 } else if (Args.hasArg(options::OPT_pg)) {
11142 CmdArgs.push_back("-lgcc_eh_p");
11143 } else {
11144 CmdArgs.push_back("--as-needed");
11145 CmdArgs.push_back("-lstdc++");
11146 CmdArgs.push_back("--no-as-needed");
11147 }
11148 }
11149
11150 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
11151 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
11152 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
11153 else
11154 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
11155 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
11156 }
11157
11158 const char *Exec =
11159 #ifdef LLVM_ON_WIN32
11160 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
11161 #else
11162 Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
11163 #endif
11164
11165 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
11166 }
11167
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const11168 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
11169 const InputInfo &Output,
11170 const InputInfoList &Inputs,
11171 const ArgList &Args,
11172 const char *LinkingOutput) const {
11173 const toolchains::FreeBSD &ToolChain =
11174 static_cast<const toolchains::FreeBSD &>(getToolChain());
11175 const Driver &D = ToolChain.getDriver();
11176 bool PS4Linker;
11177 StringRef LinkerOptName;
11178 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
11179 LinkerOptName = A->getValue();
11180 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
11181 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
11182 }
11183
11184 if (LinkerOptName == "gold")
11185 PS4Linker = false;
11186 else if (LinkerOptName == "ps4")
11187 PS4Linker = true;
11188 else
11189 PS4Linker = !Args.hasArg(options::OPT_shared);
11190
11191 if (PS4Linker)
11192 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11193 else
11194 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
11195 }
11196
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const11197 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
11198 const InputInfo &Output,
11199 const InputInfoList &Inputs,
11200 const ArgList &Args,
11201 const char *LinkingOutput) const {
11202 const auto &TC =
11203 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11204 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11205
11206 std::vector<std::string> gpu_archs =
11207 Args.getAllArgValues(options::OPT_march_EQ);
11208 assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
11209 const std::string& gpu_arch = gpu_archs[0];
11210
11211 // Check that our installation's ptxas supports gpu_arch.
11212 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
11213 TC.cudaInstallation().CheckCudaVersionSupportsArch(
11214 StringToCudaArch(gpu_arch));
11215 }
11216
11217 ArgStringList CmdArgs;
11218 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
11219 if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
11220 options::OPT_no_cuda_noopt_device_debug, false)) {
11221 // ptxas does not accept -g option if optimization is enabled, so
11222 // we ignore the compiler's -O* options if we want debug info.
11223 CmdArgs.push_back("-g");
11224 CmdArgs.push_back("--dont-merge-basicblocks");
11225 CmdArgs.push_back("--return-at-end");
11226 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
11227 // Map the -O we received to -O{0,1,2,3}.
11228 //
11229 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
11230 // default, so it may correspond more closely to the spirit of clang -O2.
11231
11232 // -O3 seems like the least-bad option when -Osomething is specified to
11233 // clang but it isn't handled below.
11234 StringRef OOpt = "3";
11235 if (A->getOption().matches(options::OPT_O4) ||
11236 A->getOption().matches(options::OPT_Ofast))
11237 OOpt = "3";
11238 else if (A->getOption().matches(options::OPT_O0))
11239 OOpt = "0";
11240 else if (A->getOption().matches(options::OPT_O)) {
11241 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
11242 OOpt = llvm::StringSwitch<const char *>(A->getValue())
11243 .Case("1", "1")
11244 .Case("2", "2")
11245 .Case("3", "3")
11246 .Case("s", "2")
11247 .Case("z", "2")
11248 .Default("2");
11249 }
11250 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
11251 } else {
11252 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
11253 // to no optimizations, but ptxas's default is -O3.
11254 CmdArgs.push_back("-O0");
11255 }
11256
11257 CmdArgs.push_back("--gpu-name");
11258 CmdArgs.push_back(Args.MakeArgString(gpu_arch));
11259 CmdArgs.push_back("--output-file");
11260 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11261 for (const auto& II : Inputs)
11262 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
11263
11264 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
11265 CmdArgs.push_back(Args.MakeArgString(A));
11266
11267 const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
11268 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11269 }
11270
11271 // All inputs to this linker must be from CudaDeviceActions, as we need to look
11272 // at the Inputs' Actions in order to figure out which GPU architecture they
11273 // correspond to.
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const11274 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
11275 const InputInfo &Output,
11276 const InputInfoList &Inputs,
11277 const ArgList &Args,
11278 const char *LinkingOutput) const {
11279 const auto &TC =
11280 static_cast<const toolchains::CudaToolChain &>(getToolChain());
11281 assert(TC.getTriple().isNVPTX() && "Wrong platform");
11282
11283 ArgStringList CmdArgs;
11284 CmdArgs.push_back("--cuda");
11285 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
11286 CmdArgs.push_back(Args.MakeArgString("--create"));
11287 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
11288
11289 for (const auto& II : Inputs) {
11290 auto* A = cast<const CudaDeviceAction>(II.getAction());
11291 // We need to pass an Arch of the form "sm_XX" for cubin files and
11292 // "compute_XX" for ptx.
11293 const char *Arch =
11294 (II.getType() == types::TY_PP_Asm)
11295 ? CudaVirtualArchToString(VirtualArchForCudaArch(A->getGpuArch()))
11296 : CudaArchToString(A->getGpuArch());
11297 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
11298 Arch + ",file=" + II.getFilename()));
11299 }
11300
11301 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
11302 CmdArgs.push_back(Args.MakeArgString(A));
11303
11304 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
11305 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
11306 }
11307