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