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