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