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