ToolChain.cpp revision 4c49f7b473b0158bb6e3534f70143132cc638ce8
1//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
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 "clang/Driver/ToolChain.h"
12#include "clang/Basic/ObjCRuntime.h"
13#include "clang/Driver/Action.h"
14#include "clang/Driver/Arg.h"
15#include "clang/Driver/ArgList.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/DriverDiagnostic.h"
18#include "clang/Driver/Option.h"
19#include "clang/Driver/Options.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/ErrorHandling.h"
22using namespace clang::driver;
23using namespace clang;
24
25ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
26                     const ArgList &A)
27  : D(D), Triple(T), Args(A) {
28}
29
30ToolChain::~ToolChain() {
31}
32
33const Driver &ToolChain::getDriver() const {
34 return D;
35}
36
37bool ToolChain::useIntegratedAs() const {
38  return Args.hasFlag(options::OPT_integrated_as,
39                      options::OPT_no_integrated_as,
40                      IsIntegratedAssemblerDefault());
41}
42
43std::string ToolChain::getDefaultUniversalArchName() const {
44  // In universal driver terms, the arch name accepted by -arch isn't exactly
45  // the same as the ones that appear in the triple. Roughly speaking, this is
46  // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
47  // only interesting special case is powerpc.
48  switch (Triple.getArch()) {
49  case llvm::Triple::ppc:
50    return "ppc";
51  case llvm::Triple::ppc64:
52    return "ppc64";
53  default:
54    return Triple.getArchName();
55  }
56}
57
58bool ToolChain::IsUnwindTablesDefault() const {
59  return false;
60}
61
62Tool *ToolChain::getClang() const {
63  if (!Clang)
64    Clang.reset(new tools::Clang(*this));
65  return Clang.get();
66}
67
68Tool *ToolChain::buildAssembler() const {
69  return new tools::ClangAs(*this);
70}
71
72Tool *ToolChain::buildLinker() const {
73  llvm_unreachable("Linking is not supported by this toolchain");
74}
75
76Tool *ToolChain::getAssemble() const {
77  if (!Assemble)
78    Assemble.reset(buildAssembler());
79  return Assemble.get();
80}
81
82Tool *ToolChain::getClangAs() const {
83  if (!Assemble)
84    Assemble.reset(new tools::ClangAs(*this));
85  return Assemble.get();
86}
87
88Tool *ToolChain::getLink() const {
89  if (!Link)
90    Link.reset(buildLinker());
91  return Link.get();
92}
93
94Tool *ToolChain::getTool(Action::ActionClass AC) const {
95  switch (AC) {
96  case Action::AssembleJobClass:
97    return getAssemble();
98
99  case Action::LinkJobClass:
100    return getLink();
101
102  case Action::InputClass:
103  case Action::BindArchClass:
104  case Action::LipoJobClass:
105  case Action::DsymutilJobClass:
106  case Action::VerifyJobClass:
107    llvm_unreachable("Invalid tool kind.");
108
109  case Action::CompileJobClass:
110  case Action::PrecompileJobClass:
111  case Action::PreprocessJobClass:
112  case Action::AnalyzeJobClass:
113  case Action::MigrateJobClass:
114    return getClang();
115  }
116
117  llvm_unreachable("Invalid tool kind.");
118}
119
120Tool &ToolChain::SelectTool(const JobAction &JA) const {
121  if (getDriver().ShouldUseClangCompiler(JA))
122    return *getClang();
123  Action::ActionClass AC = JA.getKind();
124  if (AC == Action::AssembleJobClass && useIntegratedAs())
125    return *getClangAs();
126  return *getTool(AC);
127}
128
129std::string ToolChain::GetFilePath(const char *Name) const {
130  return D.GetFilePath(Name, *this);
131
132}
133
134std::string ToolChain::GetProgramPath(const char *Name) const {
135  return D.GetProgramPath(Name, *this);
136}
137
138types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
139  return types::lookupTypeForExtension(Ext);
140}
141
142bool ToolChain::HasNativeLLVMSupport() const {
143  return false;
144}
145
146ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
147  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
148                     VersionTuple());
149}
150
151/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
152//
153// FIXME: tblgen this.
154static const char *getARMTargetCPU(const ArgList &Args,
155                                   const llvm::Triple &Triple) {
156  // For Darwin targets, the -arch option (which is translated to a
157  // corresponding -march option) should determine the architecture
158  // (and the Mach-O slice) regardless of any -mcpu options.
159  if (!Triple.isOSDarwin()) {
160    // FIXME: Warn on inconsistent use of -mcpu and -march.
161    // If we have -mcpu=, use that.
162    if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
163      return A->getValue();
164  }
165
166  StringRef MArch;
167  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
168    // Otherwise, if we have -march= choose the base CPU for that arch.
169    MArch = A->getValue();
170  } else {
171    // Otherwise, use the Arch from the triple.
172    MArch = Triple.getArchName();
173  }
174
175  return llvm::StringSwitch<const char *>(MArch)
176    .Cases("armv2", "armv2a","arm2")
177    .Case("armv3", "arm6")
178    .Case("armv3m", "arm7m")
179    .Cases("armv4", "armv4t", "arm7tdmi")
180    .Cases("armv5", "armv5t", "arm10tdmi")
181    .Cases("armv5e", "armv5te", "arm1026ejs")
182    .Case("armv5tej", "arm926ej-s")
183    .Cases("armv6", "armv6k", "arm1136jf-s")
184    .Case("armv6j", "arm1136j-s")
185    .Cases("armv6z", "armv6zk", "arm1176jzf-s")
186    .Case("armv6t2", "arm1156t2-s")
187    .Cases("armv6m", "armv6-m", "cortex-m0")
188    .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
189    .Cases("armv7l", "armv7-l", "cortex-a8")
190    .Cases("armv7f", "armv7-f", "cortex-a9-mp")
191    .Cases("armv7s", "armv7-s", "swift")
192    .Cases("armv7r", "armv7-r", "cortex-r4")
193    .Cases("armv7m", "armv7-m", "cortex-m3")
194    .Cases("armv7em", "armv7e-m", "cortex-m4")
195    .Case("ep9312", "ep9312")
196    .Case("iwmmxt", "iwmmxt")
197    .Case("xscale", "xscale")
198    // If all else failed, return the most base CPU LLVM supports.
199    .Default("arm7tdmi");
200}
201
202/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
203/// CPU.
204//
205// FIXME: This is redundant with -mcpu, why does LLVM use this.
206// FIXME: tblgen this, or kill it!
207static const char *getLLVMArchSuffixForARM(StringRef CPU) {
208  return llvm::StringSwitch<const char *>(CPU)
209    .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
210    .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
211    .Cases("arm920", "arm920t", "arm922t", "v4t")
212    .Cases("arm940t", "ep9312","v4t")
213    .Cases("arm10tdmi",  "arm1020t", "v5")
214    .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
215    .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
216    .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
217    .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
218    .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
219    .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
220    .Cases("cortex-a5", "cortex-a7", "cortex-a8", "v7")
221    .Cases("cortex-a9", "cortex-a15", "v7")
222    .Case("cortex-r5", "v7r")
223    .Case("cortex-m0", "v6m")
224    .Case("cortex-m3", "v7m")
225    .Case("cortex-m4", "v7em")
226    .Case("cortex-a9-mp", "v7f")
227    .Case("swift", "v7s")
228    .Default("");
229}
230
231std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
232                                         types::ID InputType) const {
233  switch (getTriple().getArch()) {
234  default:
235    return getTripleString();
236
237  case llvm::Triple::arm:
238  case llvm::Triple::thumb: {
239    // FIXME: Factor into subclasses.
240    llvm::Triple Triple = getTriple();
241
242    // Thumb2 is the default for V7 on Darwin.
243    //
244    // FIXME: Thumb should just be another -target-feaure, not in the triple.
245    StringRef Suffix =
246      getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
247    bool ThumbDefault = Suffix.startswith("v6m") ||
248      (Suffix.startswith("v7") && getTriple().isOSDarwin());
249    std::string ArchName = "arm";
250
251    // Assembly files should start in ARM mode.
252    if (InputType != types::TY_PP_Asm &&
253        Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
254      ArchName = "thumb";
255    Triple.setArchName(ArchName + Suffix.str());
256
257    return Triple.getTriple();
258  }
259  }
260}
261
262std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
263                                                   types::ID InputType) const {
264  // Diagnose use of Darwin OS deployment target arguments on non-Darwin.
265  if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
266                               options::OPT_miphoneos_version_min_EQ,
267                               options::OPT_mios_simulator_version_min_EQ))
268    getDriver().Diag(diag::err_drv_clang_unsupported)
269      << A->getAsString(Args);
270
271  return ComputeLLVMTriple(Args, InputType);
272}
273
274void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
275                                          ArgStringList &CC1Args) const {
276  // Each toolchain should provide the appropriate include flags.
277}
278
279void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
280                                      ArgStringList &CC1Args) const {
281}
282
283ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
284  const ArgList &Args) const
285{
286  if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
287    StringRef Value = A->getValue();
288    if (Value == "compiler-rt")
289      return ToolChain::RLT_CompilerRT;
290    if (Value == "libgcc")
291      return ToolChain::RLT_Libgcc;
292    getDriver().Diag(diag::err_drv_invalid_rtlib_name)
293      << A->getAsString(Args);
294  }
295
296  return GetDefaultRuntimeLibType();
297}
298
299ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
300  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
301    StringRef Value = A->getValue();
302    if (Value == "libc++")
303      return ToolChain::CST_Libcxx;
304    if (Value == "libstdc++")
305      return ToolChain::CST_Libstdcxx;
306    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
307      << A->getAsString(Args);
308  }
309
310  return ToolChain::CST_Libstdcxx;
311}
312
313/// \brief Utility function to add a system include directory to CC1 arguments.
314/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
315                                            ArgStringList &CC1Args,
316                                            const Twine &Path) {
317  CC1Args.push_back("-internal-isystem");
318  CC1Args.push_back(DriverArgs.MakeArgString(Path));
319}
320
321/// \brief Utility function to add a system include directory with extern "C"
322/// semantics to CC1 arguments.
323///
324/// Note that this should be used rarely, and only for directories that
325/// historically and for legacy reasons are treated as having implicit extern
326/// "C" semantics. These semantics are *ignored* by and large today, but its
327/// important to preserve the preprocessor changes resulting from the
328/// classification.
329/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
330                                                   ArgStringList &CC1Args,
331                                                   const Twine &Path) {
332  CC1Args.push_back("-internal-externc-isystem");
333  CC1Args.push_back(DriverArgs.MakeArgString(Path));
334}
335
336/// \brief Utility function to add a list of system include directories to CC1.
337/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
338                                             ArgStringList &CC1Args,
339                                             ArrayRef<StringRef> Paths) {
340  for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
341       I != E; ++I) {
342    CC1Args.push_back("-internal-isystem");
343    CC1Args.push_back(DriverArgs.MakeArgString(*I));
344  }
345}
346
347void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
348                                             ArgStringList &CC1Args) const {
349  // Header search paths should be handled by each of the subclasses.
350  // Historically, they have not been, and instead have been handled inside of
351  // the CC1-layer frontend. As the logic is hoisted out, this generic function
352  // will slowly stop being called.
353  //
354  // While it is being called, replicate a bit of a hack to propagate the
355  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
356  // header search paths with it. Once all systems are overriding this
357  // function, the CC1 flag and this line can be removed.
358  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
359}
360
361void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
362                                    ArgStringList &CmdArgs) const {
363  CXXStdlibType Type = GetCXXStdlibType(Args);
364
365  switch (Type) {
366  case ToolChain::CST_Libcxx:
367    CmdArgs.push_back("-lc++");
368    break;
369
370  case ToolChain::CST_Libstdcxx:
371    CmdArgs.push_back("-lstdc++");
372    break;
373  }
374}
375
376void ToolChain::AddCCKextLibArgs(const ArgList &Args,
377                                 ArgStringList &CmdArgs) const {
378  CmdArgs.push_back("-lcc_kext");
379}
380
381bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
382                                              ArgStringList &CmdArgs) const {
383  // Check if -ffast-math or -funsafe-math is enabled.
384  Arg *A = Args.getLastArg(options::OPT_ffast_math,
385                           options::OPT_fno_fast_math,
386                           options::OPT_funsafe_math_optimizations,
387                           options::OPT_fno_unsafe_math_optimizations);
388
389  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
390      A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
391    return false;
392
393  // If crtfastmath.o exists add it to the arguments.
394  std::string Path = GetFilePath("crtfastmath.o");
395  if (Path == "crtfastmath.o") // Not found.
396    return false;
397
398  CmdArgs.push_back(Args.MakeArgString(Path));
399  return true;
400}
401