1//===- llvm/Linker.h - Module Linker Interface ------------------*- 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// This file defines the interface to the module/file/archive linker.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LINKER_H
15#define LLVM_LINKER_H
16
17#include <memory>
18#include <string>
19#include <vector>
20
21namespace llvm {
22  namespace sys { class Path; }
23
24class Module;
25class LLVMContext;
26class StringRef;
27
28/// This class provides the core functionality of linking in LLVM. It retains a
29/// Module object which is the composite of the modules and libraries linked
30/// into it. The composite Module can be retrieved via the getModule() method.
31/// In this case the Linker still retains ownership of the Module. If the
32/// releaseModule() method is used, the ownership of the Module is transferred
33/// to the caller and the Linker object is only suitable for destruction.
34/// The Linker can link Modules from memory, bitcode files, or bitcode
35/// archives.  It retains a set of search paths in which to find any libraries
36/// presented to it. By default, the linker will generate error and warning
37/// messages to stderr but this capability can be turned off with the
38/// QuietWarnings and QuietErrors flags. It can also be instructed to verbosely
39/// print out the linking actions it is taking with the Verbose flag.
40/// @brief The LLVM Linker.
41class Linker {
42
43  /// @name Types
44  /// @{
45  public:
46    /// This type is used to pass the linkage items (libraries and files) to
47    /// the LinkItems function. It is composed of string/bool pairs. The string
48    /// provides the name of the file or library (as with the -l option). The
49    /// bool should be true for libraries and false for files, signifying
50    /// "isLibrary".
51    /// @brief A list of linkage items
52    typedef std::vector<std::pair<std::string,bool> > ItemList;
53
54    /// This enumeration is used to control various optional features of the
55    /// linker.
56    enum ControlFlags {
57      Verbose       = 1, ///< Print to stderr what steps the linker is taking
58      QuietWarnings = 2, ///< Don't print warnings to stderr.
59      QuietErrors   = 4  ///< Don't print errors to stderr.
60    };
61
62    enum LinkerMode {
63      DestroySource = 0, // Allow source module to be destroyed.
64      PreserveSource = 1 // Preserve the source module.
65    };
66
67  /// @}
68  /// @name Constructors
69  /// @{
70  public:
71    /// Construct the Linker with an empty module which will be given the
72    /// name \p progname. \p progname will also be used for error messages.
73    /// @brief Construct with empty module
74    Linker(StringRef progname, ///< name of tool running linker
75           StringRef modulename, ///< name of linker's end-result module
76           LLVMContext &C, ///< Context for global info
77           unsigned Flags = 0  ///< ControlFlags (one or more |'d together)
78    );
79
80    /// Construct the Linker with a previously defined module, \p aModule. Use
81    /// \p progname for the name of the program in error messages.
82    /// @brief Construct with existing module
83    Linker(StringRef progname, Module* aModule, unsigned Flags = 0);
84
85    /// Destruct the Linker.
86    /// @brief Destructor
87    ~Linker();
88
89  /// @}
90  /// @name Accessors
91  /// @{
92  public:
93    /// This method gets the composite module into which linking is being
94    /// done. The Composite module starts out empty and accumulates modules
95    /// linked into it via the various LinkIn* methods. This method does not
96    /// release the Module to the caller. The Linker retains ownership and will
97    /// destruct the Module when the Linker is destructed.
98    /// @see releaseModule
99    /// @brief Get the linked/composite module.
100    Module* getModule() const { return Composite; }
101
102    /// This method releases the composite Module into which linking is being
103    /// done. Ownership of the composite Module is transferred to the caller who
104    /// must arrange for its destruct. After this method is called, the Linker
105    /// terminates the linking session for the returned Module. It will no
106    /// longer utilize the returned Module but instead resets itself for
107    /// subsequent linking as if the constructor had been called. The Linker's
108    /// LibPaths and flags to be reset, and memory will be released.
109    /// @brief Release the linked/composite module.
110    Module* releaseModule();
111
112    /// This method gets the list of libraries that form the path that the
113    /// Linker will search when it is presented with a library name.
114    /// @brief Get the Linkers library path
115    const std::vector<sys::Path>& getLibPaths() const { return LibPaths; }
116
117    /// This method returns an error string suitable for printing to the user.
118    /// The return value will be empty unless an error occurred in one of the
119    /// LinkIn* methods. In those cases, the LinkIn* methods will have returned
120    /// true, indicating an error occurred. At most one error is retained so
121    /// this function always returns the last error that occurred. Note that if
122    /// the Quiet control flag is not set, the error string will have already
123    /// been printed to stderr.
124    /// @brief Get the text of the last error that occurred.
125    const std::string &getLastError() const { return Error; }
126
127  /// @}
128  /// @name Mutators
129  /// @{
130  public:
131    /// Add a path to the list of paths that the Linker will search. The Linker
132    /// accumulates the set of libraries added
133    /// library paths for the target platform. The standard libraries will
134    /// always be searched last. The added libraries will be searched in the
135    /// order added.
136    /// @brief Add a path.
137    void addPath(const sys::Path& path);
138
139    /// Add a set of paths to the list of paths that the linker will search. The
140    /// Linker accumulates the set of libraries added. The \p paths will be
141    /// added to the end of the Linker's list. Order will be retained.
142    /// @brief Add a set of paths.
143    void addPaths(const std::vector<std::string>& paths);
144
145    /// This method augments the Linker's list of library paths with the system
146    /// paths of the host operating system, include LLVM_LIB_SEARCH_PATH.
147    /// @brief Add the system paths.
148    void addSystemPaths();
149
150    /// Control optional linker behavior by setting a group of flags. The flags
151    /// are defined in the ControlFlags enumeration.
152    /// @see ControlFlags
153    /// @brief Set control flags.
154    void setFlags(unsigned flags) { Flags = flags; }
155
156    /// This method is the main interface to the linker. It can be used to
157    /// link a set of linkage items into a module. A linkage item is either a
158    /// file name with fully qualified path, or a library for which the Linker's
159    /// LibraryPath will be utilized to locate the library. The bool value in
160    /// the LinkItemKind should be set to true for libraries.  This function
161    /// allows linking to preserve the order of specification associated with
162    /// the command line, or for other purposes. Each item will be linked in
163    /// turn as it occurs in \p Items.
164    /// @returns true if an error occurred, false otherwise
165    /// @see LinkItemKind
166    /// @see getLastError
167    bool LinkInItems (
168      const ItemList& Items, ///< Set of libraries/files to link in
169      ItemList& NativeItems  ///< Output list of native files/libs
170    );
171
172    /// This function links the bitcode \p Files into the composite module.
173    /// Note that this does not do any linking of unresolved symbols. The \p
174    /// Files are all completely linked into \p HeadModule regardless of
175    /// unresolved symbols. This function just loads each bitcode file and
176    /// calls LinkInModule on them.
177    /// @returns true if an error occurs, false otherwise
178    /// @see getLastError
179    /// @brief Link in multiple files.
180    bool LinkInFiles (
181      const std::vector<sys::Path> & Files ///< Files to link in
182    );
183
184    /// This function links a single bitcode file, \p File, into the composite
185    /// module. Note that this does not attempt to resolve symbols. This method
186    /// just loads the bitcode file and calls LinkInModule on it. If an error
187    /// occurs, the Linker's error string is set.
188    /// @returns true if an error occurs, false otherwise
189    /// @see getLastError
190    /// @brief Link in a single file.
191    bool LinkInFile(
192      const sys::Path& File, ///< File to link in.
193      bool &is_native        ///< Indicates if the file is native object file
194    );
195
196    /// This function provides a way to selectively link in a set of modules,
197    /// found in libraries, based on the unresolved symbols in the composite
198    /// module. Each item in \p Libraries should be the base name of a library,
199    /// as if given with the -l option of a linker tool.  The Linker's LibPaths
200    /// are searched for the \p Libraries and any found will be linked in with
201    /// LinkInArchive.  If an error occurs, the Linker's error string is set.
202    /// @see LinkInArchive
203    /// @see getLastError
204    /// @returns true if an error occurs, false otherwise
205    /// @brief Link libraries into the module
206    bool LinkInLibraries (
207      const std::vector<std::string> & Libraries ///< Libraries to link in
208    );
209
210    /// This function provides a way to selectively link in a set of modules,
211    /// found in one library, based on the unresolved symbols in the composite
212    /// module.The \p Library should be the base name of a library, as if given
213    /// with the -l option of a linker tool. The Linker's LibPaths are searched
214    /// for the \p Library and if found, it will be linked in with via the
215    /// LinkInArchive method. If an error occurs, the Linker's error string is
216    /// set.
217    /// @see LinkInArchive
218    /// @see getLastError
219    /// @returns true if an error occurs, false otherwise
220    /// @brief Link one library into the module
221    bool LinkInLibrary (
222      StringRef Library, ///< The library to link in
223      bool& is_native    ///< Indicates if lib a native library
224    );
225
226    /// This function links one bitcode archive, \p Filename, into the module.
227    /// The archive is searched to resolve outstanding symbols. Any modules in
228    /// the archive that resolve outstanding symbols will be linked in. The
229    /// library is searched repeatedly until no more modules that resolve
230    /// symbols can be found. If an error occurs, the error string is  set.
231    /// To speed up this function, ensure the archive has been processed
232    /// llvm-ranlib or the S option was given to llvm-ar when the archive was
233    /// created. These tools add a symbol table to the archive which makes the
234    /// search for undefined symbols much faster.
235    /// @see getLastError
236    /// @returns true if an error occurs, otherwise false.
237    /// @brief Link in one archive.
238    bool LinkInArchive(
239      const sys::Path& Filename, ///< Filename of the archive to link
240      bool& is_native            ///<  Indicates if archive is a native archive
241    );
242
243    /// This method links the \p Src module into the Linker's Composite module
244    /// by calling LinkModules.  All the other LinkIn* methods eventually
245    /// result in calling this method to link a Module into the Linker's
246    /// composite.
247    /// @see LinkModules
248    /// @returns True if an error occurs, false otherwise.
249    /// @brief Link in a module.
250    bool LinkInModule(
251      Module* Src,              ///< Module linked into \p Dest
252      std::string* ErrorMsg = 0 /// Error/diagnostic string
253    ) {
254      return LinkModules(Composite, Src, Linker::DestroySource, ErrorMsg );
255    }
256
257    /// This is the heart of the linker. This method will take unconditional
258    /// control of the \p Src module and link it into the \p Dest module. The
259    /// \p Src module will be destructed or subsumed by this method. In either
260    /// case it is not usable by the caller after this method is invoked. Only
261    /// the \p Dest module will remain. The \p Src module is linked into the
262    /// Linker's composite module such that types, global variables, functions,
263    /// and etc. are matched and resolved.  If an error occurs, this function
264    /// returns true and ErrorMsg is set to a descriptive message about the
265    /// error.
266    /// @returns True if an error occurs, false otherwise.
267    /// @brief Generically link two modules together.
268    static bool LinkModules(Module* Dest, Module* Src, unsigned Mode,
269                            std::string* ErrorMsg);
270
271    /// This function looks through the Linker's LibPaths to find a library with
272    /// the name \p Filename. If the library cannot be found, the returned path
273    /// will be empty (i.e. sys::Path::isEmpty() will return true).
274    /// @returns A sys::Path to the found library
275    /// @brief Find a library from its short name.
276    sys::Path FindLib(StringRef Filename);
277
278  /// @}
279  /// @name Implementation
280  /// @{
281  private:
282    /// Read in and parse the bitcode file named by FN and return the
283    /// Module it contains (wrapped in an auto_ptr), or 0 if an error occurs.
284    std::auto_ptr<Module> LoadObject(const sys::Path& FN);
285
286    bool warning(StringRef message);
287    bool error(StringRef message);
288    void verbose(StringRef message);
289
290  /// @}
291  /// @name Data
292  /// @{
293  private:
294    LLVMContext& Context; ///< The context for global information
295    Module* Composite; ///< The composite module linked together
296    std::vector<sys::Path> LibPaths; ///< The library search paths
297    unsigned Flags;    ///< Flags to control optional behavior.
298    std::string Error; ///< Text of error that occurred.
299    std::string ProgramName; ///< Name of the program being linked
300  /// @}
301
302};
303
304} // End llvm namespace
305
306#endif
307