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