1//===--- ToolChain.h - Collections of tools for one platform ----*- 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#ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
11#define LLVM_CLANG_DRIVER_TOOLCHAIN_H
12
13#include "clang/Basic/Sanitizers.h"
14#include "clang/Basic/VersionTuple.h"
15#include "clang/Driver/Action.h"
16#include "clang/Driver/Multilib.h"
17#include "clang/Driver/Types.h"
18#include "clang/Driver/Util.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Triple.h"
21#include "llvm/Target/TargetOptions.h"
22#include <memory>
23#include <string>
24
25namespace llvm {
26namespace opt {
27  class ArgList;
28  class DerivedArgList;
29  class InputArgList;
30}
31}
32
33namespace clang {
34class ObjCRuntime;
35namespace vfs {
36class FileSystem;
37}
38
39namespace driver {
40  class Compilation;
41  class CudaInstallationDetector;
42  class Driver;
43  class JobAction;
44  class RegisterEffectiveTriple;
45  class SanitizerArgs;
46  class Tool;
47  class XRayArgs;
48
49/// Helper structure used to pass information extracted from clang executable
50/// name such as `i686-linux-android-g++`.
51///
52struct ParsedClangName {
53  /// Target part of the executable name, as `i686-linux-android`.
54  std::string TargetPrefix;
55  /// Driver mode part of the executable name, as `g++`.
56  std::string ModeSuffix;
57  /// Corresponding driver mode argument, as '--driver-mode=g++'
58  const char *DriverMode;
59  /// True if TargetPrefix is recognized as a registered target name.
60  bool TargetIsValid;
61
62  ParsedClangName() : DriverMode(nullptr), TargetIsValid(false) {}
63  ParsedClangName(std::string Suffix, const char *Mode)
64      : ModeSuffix(Suffix), DriverMode(Mode), TargetIsValid(false) {}
65  ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
66                  bool IsRegistered)
67      : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
68        TargetIsValid(IsRegistered) {}
69};
70
71/// ToolChain - Access to tools for a single platform.
72class ToolChain {
73public:
74  typedef SmallVector<std::string, 16> path_list;
75
76  enum CXXStdlibType {
77    CST_Libcxx,
78    CST_Libstdcxx
79  };
80
81  enum RuntimeLibType {
82    RLT_CompilerRT,
83    RLT_Libgcc
84  };
85
86  enum RTTIMode {
87    RM_EnabledExplicitly,
88    RM_EnabledImplicitly,
89    RM_DisabledExplicitly,
90    RM_DisabledImplicitly
91  };
92
93private:
94  const Driver &D;
95  const llvm::Triple Triple;
96  const llvm::opt::ArgList &Args;
97  // We need to initialize CachedRTTIArg before CachedRTTIMode
98  const llvm::opt::Arg *const CachedRTTIArg;
99  const RTTIMode CachedRTTIMode;
100
101  /// The list of toolchain specific path prefixes to search for
102  /// files.
103  path_list FilePaths;
104
105  /// The list of toolchain specific path prefixes to search for
106  /// programs.
107  path_list ProgramPaths;
108
109  mutable std::unique_ptr<Tool> Clang;
110  mutable std::unique_ptr<Tool> Assemble;
111  mutable std::unique_ptr<Tool> Link;
112  mutable std::unique_ptr<Tool> OffloadBundler;
113  Tool *getClang() const;
114  Tool *getAssemble() const;
115  Tool *getLink() const;
116  Tool *getClangAs() const;
117  Tool *getOffloadBundler() const;
118
119  mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
120  mutable std::unique_ptr<XRayArgs> XRayArguments;
121
122  /// The effective clang triple for the current Job.
123  mutable llvm::Triple EffectiveTriple;
124
125  /// Set the toolchain's effective clang triple.
126  void setEffectiveTriple(llvm::Triple ET) const {
127    EffectiveTriple = std::move(ET);
128  }
129
130  friend class RegisterEffectiveTriple;
131
132protected:
133  MultilibSet Multilibs;
134
135  ToolChain(const Driver &D, const llvm::Triple &T,
136            const llvm::opt::ArgList &Args);
137
138  virtual Tool *buildAssembler() const;
139  virtual Tool *buildLinker() const;
140  virtual Tool *getTool(Action::ActionClass AC) const;
141
142  /// \name Utilities for implementing subclasses.
143  ///@{
144  static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
145                               llvm::opt::ArgStringList &CC1Args,
146                               const Twine &Path);
147  static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
148                                      llvm::opt::ArgStringList &CC1Args,
149                                      const Twine &Path);
150  static void
151      addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
152                                      llvm::opt::ArgStringList &CC1Args,
153                                      const Twine &Path);
154  static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
155                                llvm::opt::ArgStringList &CC1Args,
156                                ArrayRef<StringRef> Paths);
157  ///@}
158
159public:
160  virtual ~ToolChain();
161
162  // Accessors
163
164  const Driver &getDriver() const { return D; }
165  vfs::FileSystem &getVFS() const;
166  const llvm::Triple &getTriple() const { return Triple; }
167
168  /// Get the toolchain's aux triple, if it has one.
169  ///
170  /// Exactly what the aux triple represents depends on the toolchain, but for
171  /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
172  /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
173  virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
174
175  llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
176  StringRef getArchName() const { return Triple.getArchName(); }
177  StringRef getPlatform() const { return Triple.getVendorName(); }
178  StringRef getOS() const { return Triple.getOSName(); }
179
180  /// \brief Provide the default architecture name (as expected by -arch) for
181  /// this toolchain.
182  StringRef getDefaultUniversalArchName() const;
183
184  std::string getTripleString() const {
185    return Triple.getTriple();
186  }
187
188  /// Get the toolchain's effective clang triple.
189  const llvm::Triple &getEffectiveTriple() const {
190    assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
191    return EffectiveTriple;
192  }
193
194  path_list &getFilePaths() { return FilePaths; }
195  const path_list &getFilePaths() const { return FilePaths; }
196
197  path_list &getProgramPaths() { return ProgramPaths; }
198  const path_list &getProgramPaths() const { return ProgramPaths; }
199
200  const MultilibSet &getMultilibs() const { return Multilibs; }
201
202  const SanitizerArgs& getSanitizerArgs() const;
203
204  const XRayArgs& getXRayArgs() const;
205
206  // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
207  const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
208
209  // Returns the RTTIMode for the toolchain with the current arguments.
210  RTTIMode getRTTIMode() const { return CachedRTTIMode; }
211
212  /// \brief Return any implicit target and/or mode flag for an invocation of
213  /// the compiler driver as `ProgName`.
214  ///
215  /// For example, when called with i686-linux-android-g++, the first element
216  /// of the return value will be set to `"i686-linux-android"` and the second
217  /// will be set to "--driver-mode=g++"`.
218  /// It is OK if the target name is not registered. In this case the return
219  /// value contains false in the field TargetIsValid.
220  ///
221  /// \pre `llvm::InitializeAllTargets()` has been called.
222  /// \param ProgName The name the Clang driver was invoked with (from,
223  /// e.g., argv[0]).
224  /// \return A structure of type ParsedClangName that contains the executable
225  /// name parts.
226  ///
227  static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
228
229  // Tool access.
230
231  /// TranslateArgs - Create a new derived argument list for any argument
232  /// translations this ToolChain may wish to perform, or 0 if no tool chain
233  /// specific translations are needed. If \p DeviceOffloadKind is specified
234  /// the translation specific for that offload kind is performed.
235  ///
236  /// \param BoundArch - The bound architecture name, or 0.
237  /// \param DeviceOffloadKind - The device offload kind used for the
238  /// translation.
239  virtual llvm::opt::DerivedArgList *
240  TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
241                Action::OffloadKind DeviceOffloadKind) const {
242    return nullptr;
243  }
244
245  /// TranslateOpenMPTargetArgs - Create a new derived argument list for
246  /// that contains the OpenMP target specific flags passed via
247  /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
248  virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
249      const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
250      SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
251
252  /// Choose a tool to use to handle the action \p JA.
253  ///
254  /// This can be overridden when a particular ToolChain needs to use
255  /// a compiler other than Clang.
256  virtual Tool *SelectTool(const JobAction &JA) const;
257
258  // Helper methods
259
260  std::string GetFilePath(const char *Name) const;
261  std::string GetProgramPath(const char *Name) const;
262
263  /// Returns the linker path, respecting the -fuse-ld= argument to determine
264  /// the linker suffix or name.
265  std::string GetLinkerPath() const;
266
267  /// \brief Dispatch to the specific toolchain for verbose printing.
268  ///
269  /// This is used when handling the verbose option to print detailed,
270  /// toolchain-specific information useful for understanding the behavior of
271  /// the driver on a specific platform.
272  virtual void printVerboseInfo(raw_ostream &OS) const {}
273
274  // Platform defaults information
275
276  /// \brief Returns true if the toolchain is targeting a non-native
277  /// architecture.
278  virtual bool isCrossCompiling() const;
279
280  /// HasNativeLTOLinker - Check whether the linker and related tools have
281  /// native LLVM support.
282  virtual bool HasNativeLLVMSupport() const;
283
284  /// LookupTypeForExtension - Return the default language type to use for the
285  /// given extension.
286  virtual types::ID LookupTypeForExtension(StringRef Ext) const;
287
288  /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
289  virtual bool IsBlocksDefault() const { return false; }
290
291  /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
292  /// by default.
293  virtual bool IsIntegratedAssemblerDefault() const { return false; }
294
295  /// \brief Check if the toolchain should use the integrated assembler.
296  virtual bool useIntegratedAs() const;
297
298  /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
299  virtual bool IsMathErrnoDefault() const { return true; }
300
301  /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
302  /// -fencode-extended-block-signature by default.
303  virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
304
305  /// IsObjCNonFragileABIDefault - Does this tool chain set
306  /// -fobjc-nonfragile-abi by default.
307  virtual bool IsObjCNonFragileABIDefault() const { return false; }
308
309  /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
310  /// mixed dispatch method be used?
311  virtual bool UseObjCMixedDispatch() const { return false; }
312
313  /// GetDefaultStackProtectorLevel - Get the default stack protector level for
314  /// this tool chain (0=off, 1=on, 2=strong, 3=all).
315  virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
316    return 0;
317  }
318
319  /// GetDefaultLinker - Get the default linker to use.
320  virtual const char *getDefaultLinker() const {
321    return "ld";
322  }
323
324  /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
325  virtual RuntimeLibType GetDefaultRuntimeLibType() const {
326    return ToolChain::RLT_Libgcc;
327  }
328
329  virtual CXXStdlibType GetDefaultCXXStdlibType() const {
330    return ToolChain::CST_Libstdcxx;
331  }
332
333  virtual std::string getCompilerRTPath() const;
334
335  virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
336                                    StringRef Component,
337                                    bool Shared = false) const;
338
339  const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
340                                     StringRef Component,
341                                     bool Shared = false) const;
342
343  // Returns <ResourceDir>/lib/<OSName>/<arch>.  This is used by runtimes (such
344  // as OpenMP) to find arch-specific libraries.
345  std::string getArchSpecificLibPath() const;
346
347  /// needsProfileRT - returns true if instrumentation profile is on.
348  static bool needsProfileRT(const llvm::opt::ArgList &Args);
349
350  /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
351  /// by default.
352  virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
353
354  /// \brief Test whether this toolchain defaults to PIC.
355  virtual bool isPICDefault() const = 0;
356
357  /// \brief Test whether this toolchain defaults to PIE.
358  virtual bool isPIEDefault() const = 0;
359
360  /// \brief Tests whether this toolchain forces its default for PIC, PIE or
361  /// non-PIC.  If this returns true, any PIC related flags should be ignored
362  /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
363  /// used exclusively.
364  virtual bool isPICDefaultForced() const = 0;
365
366  /// SupportsProfiling - Does this tool chain support -pg.
367  virtual bool SupportsProfiling() const { return true; }
368
369  /// Does this tool chain support Objective-C garbage collection.
370  virtual bool SupportsObjCGC() const { return true; }
371
372  /// Complain if this tool chain doesn't support Objective-C ARC.
373  virtual void CheckObjCARC() const {}
374
375  /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
376  /// compile unit information.
377  virtual bool UseDwarfDebugFlags() const { return false; }
378
379  // Return the DWARF version to emit, in the absence of arguments
380  // to the contrary.
381  virtual unsigned GetDefaultDwarfVersion() const { return 4; }
382
383  // True if the driver should assume "-fstandalone-debug"
384  // in the absence of an option specifying otherwise,
385  // provided that debugging was requested in the first place.
386  // i.e. a value of 'true' does not imply that debugging is wanted.
387  virtual bool GetDefaultStandaloneDebug() const { return false; }
388
389  // Return the default debugger "tuning."
390  virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
391    return llvm::DebuggerKind::GDB;
392  }
393
394  /// UseSjLjExceptions - Does this tool chain use SjLj exceptions.
395  virtual bool UseSjLjExceptions(const llvm::opt::ArgList &Args) const {
396    return false;
397  }
398
399  /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
400  virtual bool SupportsEmbeddedBitcode() const {
401    return false;
402  }
403
404  /// getThreadModel() - Which thread model does this target use?
405  virtual std::string getThreadModel() const { return "posix"; }
406
407  /// isThreadModelSupported() - Does this target support a thread model?
408  virtual bool isThreadModelSupported(const StringRef Model) const;
409
410  /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
411  /// command line arguments into account.
412  virtual std::string
413  ComputeLLVMTriple(const llvm::opt::ArgList &Args,
414                    types::ID InputType = types::TY_INVALID) const;
415
416  /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
417  /// target, which may take into account the command line arguments. For
418  /// example, on Darwin the -mmacosx-version-min= command line argument (which
419  /// sets the deployment target) determines the version in the triple passed to
420  /// Clang.
421  virtual std::string ComputeEffectiveClangTriple(
422      const llvm::opt::ArgList &Args,
423      types::ID InputType = types::TY_INVALID) const;
424
425  /// getDefaultObjCRuntime - Return the default Objective-C runtime
426  /// for this platform.
427  ///
428  /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
429  virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
430
431  /// hasBlocksRuntime - Given that the user is compiling with
432  /// -fblocks, does this tool chain guarantee the existence of a
433  /// blocks runtime?
434  ///
435  /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
436  virtual bool hasBlocksRuntime() const { return true; }
437
438  /// \brief Add the clang cc1 arguments for system include paths.
439  ///
440  /// This routine is responsible for adding the necessary cc1 arguments to
441  /// include headers from standard system header directories.
442  virtual void
443  AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
444                            llvm::opt::ArgStringList &CC1Args) const;
445
446  /// \brief Add options that need to be passed to cc1 for this target.
447  virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
448                                     llvm::opt::ArgStringList &CC1Args,
449                                     Action::OffloadKind DeviceOffloadKind) const;
450
451  /// \brief Add warning options that need to be passed to cc1 for this target.
452  virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
453
454  // GetRuntimeLibType - Determine the runtime library type to use with the
455  // given compilation arguments.
456  virtual RuntimeLibType
457  GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
458
459  // GetCXXStdlibType - Determine the C++ standard library type to use with the
460  // given compilation arguments.
461  virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
462
463  /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
464  /// the include paths to use for the given C++ standard library type.
465  virtual void
466  AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
467                               llvm::opt::ArgStringList &CC1Args) const;
468
469  /// Returns if the C++ standard library should be linked in.
470  /// Note that e.g. -lm should still be linked even if this returns false.
471  bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
472
473  /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
474  /// for the given C++ standard library type.
475  virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
476                                   llvm::opt::ArgStringList &CmdArgs) const;
477
478  /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
479  void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
480                          llvm::opt::ArgStringList &CmdArgs) const;
481
482  /// AddCCKextLibArgs - Add the system specific linker arguments to use
483  /// for kernel extensions (Darwin-specific).
484  virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
485                                llvm::opt::ArgStringList &CmdArgs) const;
486
487  /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
488  /// global flags for unsafe floating point math, add it and return true.
489  ///
490  /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
491  virtual bool AddFastMathRuntimeIfAvailable(
492      const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
493  /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
494  /// a suitable profile runtime library to the linker.
495  virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
496                                llvm::opt::ArgStringList &CmdArgs) const;
497
498  /// \brief Add arguments to use system-specific CUDA includes.
499  virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
500                                  llvm::opt::ArgStringList &CC1Args) const;
501
502  /// \brief Add arguments to use MCU GCC toolchain includes.
503  virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
504                                   llvm::opt::ArgStringList &CC1Args) const;
505
506  /// \brief On Windows, returns the MSVC compatibility version.
507  virtual VersionTuple computeMSVCVersion(const Driver *D,
508                                          const llvm::opt::ArgList &Args) const;
509
510  /// \brief Return sanitizers which are available in this toolchain.
511  virtual SanitizerMask getSupportedSanitizers() const;
512
513  /// \brief Return sanitizers which are enabled by default.
514  virtual SanitizerMask getDefaultSanitizers() const { return 0; }
515};
516
517/// Set a ToolChain's effective triple. Reset it when the registration object
518/// is destroyed.
519class RegisterEffectiveTriple {
520  const ToolChain &TC;
521
522public:
523  RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
524    TC.setEffectiveTriple(std::move(T));
525  }
526
527  ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
528};
529
530} // end namespace driver
531} // end namespace clang
532
533#endif
534