1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
3 // This file contains routines to handle linking together LLVM bytecode files,
4 // and to handle annoying things like static libraries.
6 //===----------------------------------------------------------------------===//
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 "Config/stdlib.h"
28 // Function: FileExists ()
31 // Determine if the specified filename exists and is readable.
34 // FN - The name of the file.
40 // TRUE - The file exists and is readable.
41 // FALSE - The file does not exist or is unreadable.
43 static inline bool FileExists(const std::string &FN) {
44 return access(FN.c_str(), R_OK | F_OK) != -1;
48 // Function: IsArchive ()
51 // Determine if the specified file is an ar archive. It determines this by
52 // checking the magic string at the beginning of the file.
55 // filename - A C++ string containing the name of the file.
61 // TRUE - The file is an archive.
62 // FALSE - The file is not an archive.
64 static inline bool IsArchive(const std::string &filename)
66 std::string ArchiveMagic("!<arch>\012");
67 char buf[1 + ArchiveMagic.size()];
68 std::ifstream f(filename.c_str());
69 f.read(buf, ArchiveMagic.size());
70 buf[ArchiveMagic.size()] = '\0';
71 return ArchiveMagic == buf;
75 // Function: FindLib ()
78 // This function locates a particular library. It will prepend and append
79 // various directories, prefixes, and suffixes until it can find the library.
82 // Filename - Name of the file to find.
83 // Paths - List of directories to search.
89 // The name of the file is returned.
90 // If the file is not found, an empty string is returned.
93 FindLib(const std::string &Filename, const std::vector<std::string> &Paths)
95 // Determine if the pathname can be found as it stands.
96 if (FileExists(Filename))
99 // If that doesn't work, convert the name into a library name.
100 std::string LibName = "lib" + Filename;
102 // Iterate over the directories in Paths to see if we can find the library
104 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
105 std::string Directory = Paths[Index] + "/";
107 if (FileExists(Directory + LibName + ".bc"))
108 return Directory + LibName + ".bc";
110 if (FileExists(Directory + LibName + ".so"))
111 return Directory + LibName + ".so";
113 if (FileExists(Directory + LibName + ".a"))
114 return Directory + LibName + ".a";
117 // One last hope: Check LLVM_LIB_SEARCH_PATH.
118 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
119 if (SearchPath == NULL)
120 return std::string();
122 LibName = std::string(SearchPath) + "/" + LibName;
123 if (FileExists(LibName))
126 return std::string();
130 // Function: GetAllDefinedSymbols ()
133 // Find all of the defined symbols in the specified module.
136 // M - The module in which to find defined symbols.
139 // DefinedSymbols - A set of C++ strings that will contain the name of all
146 GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols)
148 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
149 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
150 DefinedSymbols.insert(I->getName());
151 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
152 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
153 DefinedSymbols.insert(I->getName());
157 // Function: GetAllUndefinedSymbols ()
160 // This calculates the set of undefined symbols that still exist in an LLVM
161 // module. This is a bit tricky because there may be two symbols with the
162 // same name but different LLVM types that will be resolved to each other but
163 // aren't currently (thus we need to treat it as resolved).
166 // M - The module in which to find undefined symbols.
169 // UndefinedSymbols - A set of C++ strings containing the name of all
170 // undefined symbols.
176 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols)
178 std::set<std::string> DefinedSymbols;
179 UndefinedSymbols.clear(); // Start out empty
181 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
184 UndefinedSymbols.insert(I->getName());
185 else if (!I->hasInternalLinkage())
186 DefinedSymbols.insert(I->getName());
188 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
191 UndefinedSymbols.insert(I->getName());
192 else if (!I->hasInternalLinkage())
193 DefinedSymbols.insert(I->getName());
196 // Prune out any defined symbols from the undefined symbols set...
197 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
198 I != UndefinedSymbols.end(); )
199 if (DefinedSymbols.count(*I))
200 UndefinedSymbols.erase(I++); // This symbol really is defined!
202 ++I; // Keep this symbol in the undefined symbols list
207 // Function: LoadObject ()
210 // Read the specified bytecode object file.
213 // FN - The name of the file to load.
216 // OutErrorMessage - The error message to give back to the caller.
219 // A pointer to a module represening the bytecode file is returned.
220 // If an error occurs, the pointer is 0.
222 std::auto_ptr<Module>
223 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
224 std::string ErrorMessage;
225 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
226 if (Result) return std::auto_ptr<Module>(Result);
227 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
228 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
229 return std::auto_ptr<Module>();
233 // Function: LinkInArchive ()
236 // This function will open an archive library and link in all objects which
237 // provide symbols that are currently undefined.
240 // M - The module in which to link the archives.
241 // Filename - The pathname of the archive.
242 // Verbose - Flags whether verbose messages should be printed.
245 // ErrorMessage - A C++ string detailing what error occurred, if any.
248 // TRUE - An error occurred.
249 // FALSE - No errors.
251 static bool LinkInArchive(Module *M,
252 const std::string &Filename,
253 std::string &ErrorMessage,
257 // Find all of the symbols currently undefined in the bytecode program.
258 // If all the symbols are defined, the program is complete, and there is
259 // no reason to link in any archive files.
261 std::set<std::string> UndefinedSymbols;
262 GetAllUndefinedSymbols(M, UndefinedSymbols);
263 if (UndefinedSymbols.empty()) {
264 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
265 return false; // No need to link anything in!
269 // Load in the archive objects.
271 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
272 std::vector<Module*> Objects;
273 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
277 // Figure out which symbols are defined by all of the modules in the archive.
279 std::vector<std::set<std::string> > DefinedSymbols;
280 DefinedSymbols.resize(Objects.size());
281 for (unsigned i = 0; i != Objects.size(); ++i) {
282 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
285 // While we are linking in object files, loop.
290 for (unsigned i = 0; i != Objects.size(); ++i) {
291 // Consider whether we need to link in this module... we only need to
292 // link it in if it defines some symbol which is so far undefined.
294 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
296 bool ObjectRequired = false;
297 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
298 E = UndefinedSymbols.end(); I != E; ++I)
299 if (DefSymbols.count(*I)) {
301 std::cerr << " Found object providing symbol '" << *I << "'...\n";
302 ObjectRequired = true;
306 // We DO need to link this object into the program...
307 if (ObjectRequired) {
308 if (LinkModules(M, Objects[i], &ErrorMessage))
309 return true; // Couldn't link in the right object file...
311 // Since we have linked in this object, delete it from the list of
312 // objects to consider in this archive file.
313 std::swap(Objects[i], Objects.back());
314 std::swap(DefinedSymbols[i], DefinedSymbols.back());
316 DefinedSymbols.pop_back();
317 --i; // Do not skip an entry
319 // The undefined symbols set should have shrunk.
320 GetAllUndefinedSymbols(M, UndefinedSymbols);
321 Linked = true; // We have linked something in!
330 // Function: LinkInFile ()
333 // This function will open an archive library and link in all objects which
334 // provide symbols that are currently undefined.
337 // HeadModule - The module in which to link the archives.
338 // Filename - The pathname of the archive.
339 // Verbose - Flags whether verbose messages should be printed.
342 // ErrorMessage - A C++ string detailing what error occurred, if any.
345 // TRUE - An error occurred.
346 // FALSE - No errors.
348 static bool LinkInFile(Module *HeadModule,
349 const std::string &Filename,
350 std::string &ErrorMessage,
353 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
354 if (M.get() == 0) return true;
355 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
356 return LinkModules(HeadModule, M.get(), &ErrorMessage);
360 // Function: LinkFiles ()
363 // This function takes a module and a list of files and links them all
364 // together. It locates the file either in the current directory, as it's
365 // absolute or relative pathname, or as a file somewhere in
366 // LLVM_LIB_SEARCH_PATH.
369 // progname - The name of the program (infamous argv[0]).
370 // HeadModule - The module under which all files will be linked.
371 // Files - A vector of C++ strings indicating the LLVM bytecode filenames
372 // to be linked. The names can refer to a mixture of pure LLVM
373 // bytecode files and archive (ar) formatted files.
374 // Verbose - Flags whether verbose output should be printed while linking.
377 // HeadModule - The module will have the specified LLVM bytecode files linked
381 // FALSE - No errors.
382 // TRUE - Some error occurred.
384 bool LinkFiles(const char *progname,
386 const std::vector<std::string> &Files,
389 // String in which to receive error messages.
390 std::string ErrorMessage;
392 // Full pathname of the file
393 std::string Pathname;
395 // Get the library search path from the environment
396 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
398 for (unsigned i = 1; i < Files.size(); ++i) {
399 // Determine where this file lives.
400 if (FileExists(Files[i])) {
403 if (SearchPath == NULL) {
404 std::cerr << "Cannot find linker input file '" << Files[i] << "'";
408 Pathname = std::string(SearchPath)+"/"+Files[i];
409 if (!FileExists(Pathname)) {
410 std::cerr << "Cannot find linker input file '" << Files[i] << "'";
415 // A user may specify an ar archive without -l, perhaps because it
416 // is not installed as a library. Detect that and link the library.
417 if (IsArchive(Pathname)) {
419 std::cerr << "Linking archive '" << Files[i] << "'\n";
421 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
422 PrintAndReturn(progname, ErrorMessage,
423 ": Error linking in '" + Files[i] + "'");
428 std::cerr << "Linking file '" << Files[i] << "'\n";
430 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
431 PrintAndReturn(progname, ErrorMessage,
432 ": error linking in '" + Files[i] + "'");
442 // Function: LinkLibraries ()
445 // This function takes the specified library files and links them into the
446 // main bytecode object file.
449 // progname - The name of the program (infamous argv[0]).
450 // HeadModule - The module into which all necessary libraries will be linked.
451 // Libraries - The list of libraries to link into the module.
452 // LibPaths - The list of library paths in which to find libraries.
453 // Verbose - Flags whether verbose messages should be printed.
454 // Native - Flags whether native code is being generated.
457 // HeadModule - The module will have all necessary libraries linked in.
463 bool LinkLibraries(const char *progname,
465 const std::vector<std::string> &Libraries,
466 const std::vector<std::string> &LibPaths,
470 // String in which to receive error messages.
471 std::string ErrorMessage;
473 for (unsigned i = 1; i < Libraries.size(); ++i) {
474 // Determine where this library lives.
475 std::string Pathname = FindLib(Libraries[i], LibPaths);
476 if (Pathname.empty()) {
477 // If the pathname does not exist, then continue to the next one if
478 // we're doing a native link and give an error if we're doing a bytecode
481 PrintAndReturn(progname, "Cannot find " + Libraries[i]);
486 // A user may specify an ar archive without -l, perhaps because it
487 // is not installed as a library. Detect that and link the library.
488 if (IsArchive(Pathname)) {
490 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
492 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
493 PrintAndReturn(progname, ErrorMessage,
494 ": Error linking in '" + Libraries[i] + "'");
499 std::cerr << "Linking file '" << Libraries[i] << "'\n";
501 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
502 PrintAndReturn(progname, ErrorMessage,
503 ": error linking in '" + Libraries[i] + "'");