Shorten and correct some function-header comments.
[oota-llvm.git] / lib / Linker / LinkArchives.cpp
1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines to handle linking together LLVM bytecode files,
11 // and to handle annoying things like static libraries.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "gccld.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/WriteBytecodePass.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/Linker.h"
24 #include "Support/CommandLine.h"
25 #include "Support/FileUtilities.h"
26 #include "Support/Signals.h"
27 #include "Support/SystemUtils.h"
28 #include <algorithm>
29 #include <fstream>
30 #include <memory>
31 #include <set>
32
33 /// FileExists - Returns true IFF a file named FN exists and is readable.
34 ///
35 static inline bool FileExists(const std::string &FN) {
36   return access(FN.c_str(), R_OK | F_OK) != -1;
37 }
38
39 /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
40 /// archive. The file named FN must exist.
41 ///
42 static inline bool IsArchive(const std::string &FN) {
43   // Inspect the beginning of the file to see if it contains the "ar" magic
44   // string.
45   std::string ArchiveMagic("!<arch>\012");
46   char buf[1 + ArchiveMagic.size()];
47   std::ifstream f(FN.c_str());
48   f.read(buf, ArchiveMagic.size());
49   buf[ArchiveMagic.size()] = '\0';
50   return ArchiveMagic == buf;
51 }
52
53 /// FindLib - locates a particular library.  It will prepend and append
54 /// various directories, prefixes, and suffixes until it can find the library.
55 ///
56 /// Inputs:
57 ///  Filename  - Name of the file to find.
58 ///  Paths     - List of directories to search.
59 ///
60 /// Outputs:
61 ///  None.
62 ///
63 /// Return value:
64 ///  The name of the file is returned.
65 ///  If the file is not found, an empty string is returned.
66 ///
67 static std::string
68 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
69   // Determine if the pathname can be found as it stands.
70   if (FileExists(Filename))
71     return Filename;
72
73   // If that doesn't work, convert the name into a library name.
74   std::string LibName = "lib" + Filename;
75
76   // Iterate over the directories in Paths to see if we can find the library
77   // there.
78   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
79     std::string Directory = Paths[Index] + "/";
80
81     if (FileExists(Directory + LibName + ".bc"))
82       return Directory + LibName + ".bc";
83
84     if (FileExists(Directory + LibName + ".so"))
85       return Directory + LibName + ".so";
86
87     if (FileExists(Directory + LibName + ".a"))
88       return Directory + LibName + ".a";
89   }
90
91   // One last hope: Check LLVM_LIB_SEARCH_PATH.
92   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
93   if (SearchPath == NULL)
94     return std::string();
95
96   LibName = std::string(SearchPath) + "/" + LibName;
97   if (FileExists(LibName))
98     return LibName;
99
100   return std::string();
101 }
102
103 /// GetAllDefinedSymbols - Modifies its parameter DefinedSymbols to contain the
104 /// name of each externally-visible symbol defined in M.
105 ///
106 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
107   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
108     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
109       DefinedSymbols.insert(I->getName());
110   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
111     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
112       DefinedSymbols.insert(I->getName());
113 }
114
115 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
116 /// exist in an LLVM module. This is a bit tricky because there may be two
117 /// symbols with the same name but different LLVM types that will be resolved to
118 /// each other but aren't currently (thus we need to treat it as resolved).
119 ///
120 /// Inputs:
121 ///  M - The module in which to find undefined symbols.
122 ///
123 /// Outputs:
124 ///  UndefinedSymbols - A set of C++ strings containing the name of all
125 ///                     undefined symbols.
126 ///
127 /// Return value:
128 ///  None.
129 ///
130 void
131 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
132   std::set<std::string> DefinedSymbols;
133   UndefinedSymbols.clear();   // Start out empty
134   
135   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
136     if (I->hasName()) {
137       if (I->isExternal())
138         UndefinedSymbols.insert(I->getName());
139       else if (!I->hasInternalLinkage())
140         DefinedSymbols.insert(I->getName());
141     }
142   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
143     if (I->hasName()) {
144       if (I->isExternal())
145         UndefinedSymbols.insert(I->getName());
146       else if (!I->hasInternalLinkage())
147         DefinedSymbols.insert(I->getName());
148     }
149   
150   // Prune out any defined symbols from the undefined symbols set...
151   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
152        I != UndefinedSymbols.end(); )
153     if (DefinedSymbols.count(*I))
154       UndefinedSymbols.erase(I++);  // This symbol really is defined!
155     else
156       ++I; // Keep this symbol in the undefined symbols list
157 }
158
159
160 /// LoadObject - reads the specified bytecode object file.
161 ///
162 /// Inputs:
163 ///  FN - The name of the file to load.
164 ///
165 /// Outputs:
166 ///  OutErrorMessage - The error message to give back to the caller.
167 ///
168 /// Return Value:
169 ///  A pointer to a module represening the bytecode file is returned.
170 ///  If an error occurs, the pointer is 0.
171 ///
172 std::auto_ptr<Module>
173 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
174   std::string ErrorMessage;
175   Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
176   if (Result) return std::auto_ptr<Module>(Result);
177   OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
178   if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
179   return std::auto_ptr<Module>();
180 }
181
182 /// LinkInArchive - opens an archive library and link in all objects which
183 /// provide symbols that are currently undefined.
184 ///
185 /// Inputs:
186 ///  M        - The module in which to link the archives.
187 ///  Filename - The pathname of the archive.
188 ///  Verbose  - Flags whether verbose messages should be printed.
189 ///
190 /// Outputs:
191 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
192 ///
193 /// Return Value:
194 ///  TRUE  - An error occurred.
195 ///  FALSE - No errors.
196 ///
197 static bool LinkInArchive(Module *M,
198                           const std::string &Filename,
199                           std::string &ErrorMessage,
200                           bool Verbose)
201 {
202   // Find all of the symbols currently undefined in the bytecode program.
203   // If all the symbols are defined, the program is complete, and there is
204   // no reason to link in any archive files.
205   std::set<std::string> UndefinedSymbols;
206   GetAllUndefinedSymbols(M, UndefinedSymbols);
207   if (UndefinedSymbols.empty()) {
208     if (Verbose) std::cerr << "  No symbols undefined, don't link library!\n";
209     return false;  // No need to link anything in!
210   }
211
212   // Load in the archive objects.
213   if (Verbose) std::cerr << "  Loading archive file '" << Filename << "'\n";
214   std::vector<Module*> Objects;
215   if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
216     return true;
217
218   // Figure out which symbols are defined by all of the modules in the archive.
219   std::vector<std::set<std::string> > DefinedSymbols;
220   DefinedSymbols.resize(Objects.size());
221   for (unsigned i = 0; i != Objects.size(); ++i) {
222     GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
223   }
224
225   // While we are linking in object files, loop.
226   bool Linked = true;
227   while (Linked) {     
228     Linked = false;
229
230     for (unsigned i = 0; i != Objects.size(); ++i) {
231       // Consider whether we need to link in this module...  we only need to
232       // link it in if it defines some symbol which is so far undefined.
233       //
234       const std::set<std::string> &DefSymbols = DefinedSymbols[i];
235
236       bool ObjectRequired = false;
237       for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
238              E = UndefinedSymbols.end(); I != E; ++I)
239         if (DefSymbols.count(*I)) {
240           if (Verbose)
241             std::cerr << "  Found object providing symbol '" << *I << "'...\n";
242           ObjectRequired = true;
243           break;
244         }
245       
246       // We DO need to link this object into the program...
247       if (ObjectRequired) {
248         if (LinkModules(M, Objects[i], &ErrorMessage))
249           return true;   // Couldn't link in the right object file...        
250         
251         // Since we have linked in this object, delete it from the list of
252         // objects to consider in this archive file.
253         std::swap(Objects[i], Objects.back());
254         std::swap(DefinedSymbols[i], DefinedSymbols.back());
255         Objects.pop_back();
256         DefinedSymbols.pop_back();
257         --i;   // Do not skip an entry
258         
259         // The undefined symbols set should have shrunk.
260         GetAllUndefinedSymbols(M, UndefinedSymbols);
261         Linked = true;  // We have linked something in!
262       }
263     }
264   }
265   
266   return false;
267 }
268
269 /// LinkInFile - opens a bytecode file and links in all objects which
270 /// provide symbols that are currently undefined.
271 ///
272 /// Inputs:
273 ///  HeadModule - The module in which to link the bytecode file.
274 ///  Filename   - The pathname of the bytecode file.
275 ///  Verbose    - Flags whether verbose messages should be printed.
276 ///
277 /// Outputs:
278 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
279 ///
280 /// Return Value:
281 ///  TRUE  - An error occurred.
282 ///  FALSE - No errors.
283 ///
284 static bool LinkInFile(Module *HeadModule,
285                        const std::string &Filename,
286                        std::string &ErrorMessage,
287                        bool Verbose)
288 {
289   std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
290   if (M.get() == 0) return true;
291   bool Result = LinkModules(HeadModule, M.get(), &ErrorMessage);
292   if (Verbose) std::cerr << "Linked in bytecode file '" << Filename << "'\n";
293   return Result;
294 }
295
296 /// LinkFiles - takes a module and a list of files and links them all together.
297 /// It locates the file either in the current directory, as its absolute
298 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
299 ///
300 /// Inputs:
301 ///  progname   - The name of the program (infamous argv[0]).
302 ///  HeadModule - The module under which all files will be linked.
303 ///  Files      - A vector of C++ strings indicating the LLVM bytecode filenames
304 ///               to be linked.  The names can refer to a mixture of pure LLVM
305 ///               bytecode files and archive (ar) formatted files.
306 ///  Verbose    - Flags whether verbose output should be printed while linking.
307 ///
308 /// Outputs:
309 ///  HeadModule - The module will have the specified LLVM bytecode files linked
310 ///               in.
311 ///
312 /// Return value:
313 ///  FALSE - No errors.
314 ///  TRUE  - Some error occurred.
315 ///
316 bool LinkFiles(const char *progname,
317                Module *HeadModule,
318                const std::vector<std::string> &Files,
319                bool Verbose)
320 {
321   // String in which to receive error messages.
322   std::string ErrorMessage;
323
324   // Full pathname of the file
325   std::string Pathname;
326
327   // Get the library search path from the environment
328   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
329
330   for (unsigned i = 0; i < Files.size(); ++i) {
331     // Determine where this file lives.
332     if (FileExists(Files[i])) {
333       Pathname = Files[i];
334     } else {
335       if (SearchPath == NULL) {
336         std::cerr << progname << ": Cannot find linker input file '"
337                   << Files[i] << "'\n";
338         std::cerr << progname
339                   << ": Warning: Your LLVM_LIB_SEARCH_PATH is unset.\n";
340         return true;
341       }
342
343       Pathname = std::string(SearchPath)+"/"+Files[i];
344       if (!FileExists(Pathname)) {
345         std::cerr << progname << ": Cannot find linker input file '"
346                   << Files[i] << "'\n";
347         return true;
348       }
349     }
350
351     // A user may specify an ar archive without -l, perhaps because it
352     // is not installed as a library. Detect that and link the library.
353     if (IsArchive(Pathname)) {
354       if (Verbose)
355         std::cerr << "Trying to link archive '" << Pathname << "'\n";
356
357       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
358         PrintAndReturn(progname, ErrorMessage,
359                        ": Error linking in archive '" + Pathname + "'");
360         return true;
361       }
362     } else {
363       if (Verbose)
364         std::cerr << "Trying to link bytecode file '" << Pathname << "'\n";
365
366       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
367         PrintAndReturn(progname, ErrorMessage,
368                        ": Error linking in bytecode file '" + Pathname + "'");
369         return true;
370       }
371     }
372   }
373
374   return false;
375 }
376
377 /// LinkLibraries - takes the specified library files and links them into the
378 /// main bytecode object file.
379 ///
380 /// Inputs:
381 ///  progname   - The name of the program (infamous argv[0]).
382 ///  HeadModule - The module into which all necessary libraries will be linked.
383 ///  Libraries  - The list of libraries to link into the module.
384 ///  LibPaths   - The list of library paths in which to find libraries.
385 ///  Verbose    - Flags whether verbose messages should be printed.
386 ///  Native     - Flags whether native code is being generated.
387 ///
388 /// Outputs:
389 ///  HeadModule - The module will have all necessary libraries linked in.
390 ///
391 /// Return value:
392 ///  FALSE - No error.
393 ///  TRUE  - Error.
394 ///
395 bool LinkLibraries(const char *progname,
396                    Module *HeadModule,
397                    const std::vector<std::string> &Libraries,
398                    const std::vector<std::string> &LibPaths,
399                    bool Verbose,
400                    bool Native)
401 {
402   // String in which to receive error messages.
403   std::string ErrorMessage;
404
405   for (unsigned i = 0; i < Libraries.size(); ++i) {
406     // Determine where this library lives.
407     std::string Pathname = FindLib(Libraries[i], LibPaths);
408     if (Pathname.empty()) {
409       // If the pathname does not exist, then continue to the next one if
410       // we're doing a native link and give an error if we're doing a bytecode
411       // link.
412       if (!Native) {
413         PrintAndReturn(progname, "Cannot find library -l" + Libraries[i] + "\n");
414         return true;
415       }
416     }
417
418     // A user may specify an ar archive without -l, perhaps because it
419     // is not installed as a library. Detect that and link the library.
420     if (IsArchive(Pathname)) {
421       if (Verbose)
422         std::cerr << "Trying to link archive '" << Pathname << "' (-l" << Libraries[i] << ")\n";
423
424       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
425         PrintAndReturn(progname, ErrorMessage,
426                        ": Error linking in archive '" + Pathname + "' (-l" + Libraries[i] + ")");
427         return true;
428       }
429     } else {
430       if (Verbose)
431         std::cerr << "Trying to link bytecode file '" << Pathname << "' (-l" << Libraries[i] << ")\n";
432
433       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
434         PrintAndReturn(progname, ErrorMessage,
435                        ": error linking in bytecode file '" + Pathname + "' (-l" + Libraries[i] + ")");
436         return true;
437       }
438     }
439   }
440
441   return false;
442 }