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/SanitizerArgs.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Option/Arg.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 using namespace clang::driver;
26 using namespace clang;
27 using namespace llvm::opt;
28 
29 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
30                      const ArgList &A)
31   : D(D), Triple(T), Args(A) {
32 }
33 
34 ToolChain::~ToolChain() {
35 }
36 
37 const Driver &ToolChain::getDriver() const {
38  return D;
39 }
40 
41 bool ToolChain::useIntegratedAs() const {
42   return Args.hasFlag(options::OPT_fintegrated_as,
43                       options::OPT_fno_integrated_as,
44                       IsIntegratedAssemblerDefault());
45 }
46 
47 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
48   if (!SanitizerArguments.get())
49     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
50   return *SanitizerArguments.get();
51 }
52 
53 StringRef ToolChain::getDefaultUniversalArchName() const {
54   // In universal driver terms, the arch name accepted by -arch isn't exactly
55   // the same as the ones that appear in the triple. Roughly speaking, this is
56   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
57   // only interesting special case is powerpc.
58   switch (Triple.getArch()) {
59   case llvm::Triple::ppc:
60     return "ppc";
61   case llvm::Triple::ppc64:
62     return "ppc64";
63   case llvm::Triple::ppc64le:
64     return "ppc64le";
65   default:
66     return Triple.getArchName();
67   }
68 }
69 
70 bool ToolChain::IsUnwindTablesDefault() const {
71   return false;
72 }
73 
74 Tool *ToolChain::getClang() const {
75   if (!Clang)
76     Clang.reset(new tools::Clang(*this));
77   return Clang.get();
78 }
79 
80 Tool *ToolChain::buildAssembler() const {
81   return new tools::ClangAs(*this);
82 }
83 
84 Tool *ToolChain::buildLinker() const {
85   llvm_unreachable("Linking is not supported by this toolchain");
86 }
87 
88 Tool *ToolChain::getAssemble() const {
89   if (!Assemble)
90     Assemble.reset(buildAssembler());
91   return Assemble.get();
92 }
93 
94 Tool *ToolChain::getClangAs() const {
95   if (!Assemble)
96     Assemble.reset(new tools::ClangAs(*this));
97   return Assemble.get();
98 }
99 
100 Tool *ToolChain::getLink() const {
101   if (!Link)
102     Link.reset(buildLinker());
103   return Link.get();
104 }
105 
106 Tool *ToolChain::getTool(Action::ActionClass AC) const {
107   switch (AC) {
108   case Action::AssembleJobClass:
109     return getAssemble();
110 
111   case Action::LinkJobClass:
112     return getLink();
113 
114   case Action::InputClass:
115   case Action::BindArchClass:
116   case Action::LipoJobClass:
117   case Action::DsymutilJobClass:
118   case Action::VerifyDebugInfoJobClass:
119     llvm_unreachable("Invalid tool kind.");
120 
121   case Action::CompileJobClass:
122   case Action::PrecompileJobClass:
123   case Action::PreprocessJobClass:
124   case Action::AnalyzeJobClass:
125   case Action::MigrateJobClass:
126   case Action::VerifyPCHJobClass:
127     return getClang();
128   }
129 
130   llvm_unreachable("Invalid tool kind.");
131 }
132 
133 Tool *ToolChain::SelectTool(const JobAction &JA) const {
134   if (getDriver().ShouldUseClangCompiler(JA))
135     return getClang();
136   Action::ActionClass AC = JA.getKind();
137   if (AC == Action::AssembleJobClass && useIntegratedAs())
138     return getClangAs();
139   return getTool(AC);
140 }
141 
142 std::string ToolChain::GetFilePath(const char *Name) const {
143   return D.GetFilePath(Name, *this);
144 
145 }
146 
147 std::string ToolChain::GetProgramPath(const char *Name) const {
148   return D.GetProgramPath(Name, *this);
149 }
150 
151 std::string ToolChain::GetLinkerPath() const {
152   if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
153     StringRef Suffix = A->getValue();
154 
155     // If we're passed -fuse-ld= with no argument, or with the argument ld,
156     // then use whatever the default system linker is.
157     if (Suffix.empty() || Suffix == "ld")
158       return GetProgramPath("ld");
159 
160     llvm::SmallString<8> LinkerName("ld.");
161     LinkerName.append(Suffix);
162 
163     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
164     if (llvm::sys::fs::exists(LinkerPath))
165       return LinkerPath;
166 
167     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
168     return "";
169   }
170 
171   return GetProgramPath("ld");
172 }
173 
174 
175 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
176   return types::lookupTypeForExtension(Ext);
177 }
178 
179 bool ToolChain::HasNativeLLVMSupport() const {
180   return false;
181 }
182 
183 bool ToolChain::isCrossCompiling() const {
184   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
185   switch (HostTriple.getArch()) {
186   // The A32/T32/T16 instruction sets are not separate architectures in this
187   // context.
188   case llvm::Triple::arm:
189   case llvm::Triple::armeb:
190   case llvm::Triple::thumb:
191   case llvm::Triple::thumbeb:
192     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
193            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
194   default:
195     return HostTriple.getArch() != getArch();
196   }
197 }
198 
199 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
200   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
201                      VersionTuple());
202 }
203 
204 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
205                                          types::ID InputType) const {
206   switch (getTriple().getArch()) {
207   default:
208     return getTripleString();
209 
210   case llvm::Triple::x86_64: {
211     llvm::Triple Triple = getTriple();
212     if (!Triple.isOSBinFormatMachO())
213       return getTripleString();
214 
215     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
216       // x86_64h goes in the triple. Other -march options just use the
217       // vanilla triple we already have.
218       StringRef MArch = A->getValue();
219       if (MArch == "x86_64h")
220         Triple.setArchName(MArch);
221     }
222     return Triple.getTriple();
223   }
224   case llvm::Triple::aarch64: {
225     llvm::Triple Triple = getTriple();
226     if (!Triple.isOSBinFormatMachO())
227       return getTripleString();
228 
229     // FIXME: older versions of ld64 expect the "arm64" component in the actual
230     // triple string and query it to determine whether an LTO file can be
231     // handled. Remove this when we don't care any more.
232     Triple.setArchName("arm64");
233     return Triple.getTriple();
234   }
235   case llvm::Triple::arm:
236   case llvm::Triple::armeb:
237   case llvm::Triple::thumb:
238   case llvm::Triple::thumbeb: {
239     // FIXME: Factor into subclasses.
240     llvm::Triple Triple = getTriple();
241     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
242                        getTriple().getArch() == llvm::Triple::thumbeb;
243 
244     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
245     // '-mbig-endian'/'-EB'.
246     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
247                                  options::OPT_mbig_endian)) {
248       if (A->getOption().matches(options::OPT_mlittle_endian))
249         IsBigEndian = false;
250       else
251         IsBigEndian = true;
252     }
253 
254     // Thumb2 is the default for V7 on Darwin.
255     //
256     // FIXME: Thumb should just be another -target-feaure, not in the triple.
257     StringRef Suffix = Triple.isOSBinFormatMachO()
258       ? tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMCPUForMArch(Args, Triple))
259       : tools::arm::getLLVMArchSuffixForARM(tools::arm::getARMTargetCPU(Args, Triple));
260     bool ThumbDefault = Suffix.startswith("v6m") || Suffix.startswith("v7m") ||
261       Suffix.startswith("v7em") ||
262       (Suffix.startswith("v7") && getTriple().isOSBinFormatMachO());
263     // FIXME: this is invalid for WindowsCE
264     if (getTriple().isOSWindows())
265       ThumbDefault = true;
266     std::string ArchName;
267     if (IsBigEndian)
268       ArchName = "armeb";
269     else
270       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     {
276       if (IsBigEndian)
277         ArchName = "thumbeb";
278       else
279         ArchName = "thumb";
280     }
281     Triple.setArchName(ArchName + Suffix.str());
282 
283     return Triple.getTriple();
284   }
285   }
286 }
287 
288 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
289                                                    types::ID InputType) const {
290   return ComputeLLVMTriple(Args, InputType);
291 }
292 
293 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
294                                           ArgStringList &CC1Args) const {
295   // Each toolchain should provide the appropriate include flags.
296 }
297 
298 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
299                                       ArgStringList &CC1Args) const {
300 }
301 
302 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
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   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
412   // (to keep the linker options consistent with gcc and clang itself).
413   if (!isOptimizationLevelFast(Args)) {
414     // Check if -ffast-math or -funsafe-math.
415     Arg *A =
416         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
417                         options::OPT_funsafe_math_optimizations,
418                         options::OPT_fno_unsafe_math_optimizations);
419 
420     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
421         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
422       return false;
423   }
424   // If crtfastmath.o exists add it to the arguments.
425   std::string Path = GetFilePath("crtfastmath.o");
426   if (Path == "crtfastmath.o") // Not found.
427     return false;
428 
429   CmdArgs.push_back(Args.MakeArgString(Path));
430   return true;
431 }
432