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