1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines to handle linking together LLVM bytecode files,
11 // and to handle annoying things like static libraries.
13 //===----------------------------------------------------------------------===//
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"
33 /// FileExists - determines if the specified filename exists and is readable.
36 /// FN - The name of the file.
42 /// TRUE - The file exists and is readable.
43 /// FALSE - The file does not exist or is unreadable.
45 static inline bool FileExists(const std::string &FN) {
46 return access(FN.c_str(), R_OK | F_OK) != -1;
49 /// IsArchive - determines if the specified file is an ar archive
50 /// by checking the magic string at the beginning of the file.
53 /// filename - A C++ string containing the name of the file.
59 /// TRUE - The file is an archive.
60 /// FALSE - The file is not an archive.
62 static inline bool IsArchive(const std::string &filename) {
63 std::string ArchiveMagic("!<arch>\012");
64 char buf[1 + ArchiveMagic.size()];
65 std::ifstream f(filename.c_str());
66 f.read(buf, ArchiveMagic.size());
67 buf[ArchiveMagic.size()] = '\0';
68 return ArchiveMagic == buf;
71 /// FindLib - locates a particular library. It will prepend and append
72 /// various directories, prefixes, and suffixes until it can find the library.
75 /// Filename - Name of the file to find.
76 /// Paths - List of directories to search.
82 /// The name of the file is returned.
83 /// If the file is not found, an empty string is returned.
86 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
87 // Determine if the pathname can be found as it stands.
88 if (FileExists(Filename))
91 // If that doesn't work, convert the name into a library name.
92 std::string LibName = "lib" + Filename;
94 // Iterate over the directories in Paths to see if we can find the library
96 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
97 std::string Directory = Paths[Index] + "/";
99 if (FileExists(Directory + LibName + ".bc"))
100 return Directory + LibName + ".bc";
102 if (FileExists(Directory + LibName + ".so"))
103 return Directory + LibName + ".so";
105 if (FileExists(Directory + LibName + ".a"))
106 return Directory + LibName + ".a";
109 // One last hope: Check LLVM_LIB_SEARCH_PATH.
110 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
111 if (SearchPath == NULL)
112 return std::string();
114 LibName = std::string(SearchPath) + "/" + LibName;
115 if (FileExists(LibName))
118 return std::string();
121 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified
125 /// M - The module in which to find defined symbols.
128 /// DefinedSymbols - A set of C++ strings that will contain the name of all
134 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
135 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
136 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
137 DefinedSymbols.insert(I->getName());
138 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
139 if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
140 DefinedSymbols.insert(I->getName());
143 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
144 /// exist in an LLVM module. This is a bit tricky because there may be two
145 /// symbols with the same name but different LLVM types that will be resolved to
146 /// each other but aren't currently (thus we need to treat it as resolved).
149 /// M - The module in which to find undefined symbols.
152 /// UndefinedSymbols - A set of C++ strings containing the name of all
153 /// undefined symbols.
159 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
160 std::set<std::string> DefinedSymbols;
161 UndefinedSymbols.clear(); // Start out empty
163 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
166 UndefinedSymbols.insert(I->getName());
167 else if (!I->hasInternalLinkage())
168 DefinedSymbols.insert(I->getName());
170 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
173 UndefinedSymbols.insert(I->getName());
174 else if (!I->hasInternalLinkage())
175 DefinedSymbols.insert(I->getName());
178 // Prune out any defined symbols from the undefined symbols set...
179 for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
180 I != UndefinedSymbols.end(); )
181 if (DefinedSymbols.count(*I))
182 UndefinedSymbols.erase(I++); // This symbol really is defined!
184 ++I; // Keep this symbol in the undefined symbols list
188 /// LoadObject - reads the specified bytecode object file.
191 /// FN - The name of the file to load.
194 /// OutErrorMessage - The error message to give back to the caller.
197 /// A pointer to a module represening the bytecode file is returned.
198 /// If an error occurs, the pointer is 0.
200 std::auto_ptr<Module>
201 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
202 std::string ErrorMessage;
203 Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
204 if (Result) return std::auto_ptr<Module>(Result);
205 OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
206 if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
207 return std::auto_ptr<Module>();
210 /// LinkInArchive - opens an archive library and link in all objects which
211 /// provide symbols that are currently undefined.
214 /// M - The module in which to link the archives.
215 /// Filename - The pathname of the archive.
216 /// Verbose - Flags whether verbose messages should be printed.
219 /// ErrorMessage - A C++ string detailing what error occurred, if any.
222 /// TRUE - An error occurred.
223 /// FALSE - No errors.
225 static bool LinkInArchive(Module *M,
226 const std::string &Filename,
227 std::string &ErrorMessage,
230 // Find all of the symbols currently undefined in the bytecode program.
231 // If all the symbols are defined, the program is complete, and there is
232 // no reason to link in any archive files.
233 std::set<std::string> UndefinedSymbols;
234 GetAllUndefinedSymbols(M, UndefinedSymbols);
235 if (UndefinedSymbols.empty()) {
236 if (Verbose) std::cerr << " No symbols undefined, don't link library!\n";
237 return false; // No need to link anything in!
240 // Load in the archive objects.
241 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
242 std::vector<Module*> Objects;
243 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
246 // Figure out which symbols are defined by all of the modules in the archive.
247 std::vector<std::set<std::string> > DefinedSymbols;
248 DefinedSymbols.resize(Objects.size());
249 for (unsigned i = 0; i != Objects.size(); ++i) {
250 GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
253 // While we are linking in object files, loop.
258 for (unsigned i = 0; i != Objects.size(); ++i) {
259 // Consider whether we need to link in this module... we only need to
260 // link it in if it defines some symbol which is so far undefined.
262 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
264 bool ObjectRequired = false;
265 for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
266 E = UndefinedSymbols.end(); I != E; ++I)
267 if (DefSymbols.count(*I)) {
269 std::cerr << " Found object providing symbol '" << *I << "'...\n";
270 ObjectRequired = true;
274 // We DO need to link this object into the program...
275 if (ObjectRequired) {
276 if (LinkModules(M, Objects[i], &ErrorMessage))
277 return true; // Couldn't link in the right object file...
279 // Since we have linked in this object, delete it from the list of
280 // objects to consider in this archive file.
281 std::swap(Objects[i], Objects.back());
282 std::swap(DefinedSymbols[i], DefinedSymbols.back());
284 DefinedSymbols.pop_back();
285 --i; // Do not skip an entry
287 // The undefined symbols set should have shrunk.
288 GetAllUndefinedSymbols(M, UndefinedSymbols);
289 Linked = true; // We have linked something in!
297 /// LinkInFile - opens an archive library and link in all objects which
298 /// provide symbols that are currently undefined.
301 /// HeadModule - The module in which to link the archives.
302 /// Filename - The pathname of the archive.
303 /// Verbose - Flags whether verbose messages should be printed.
306 /// ErrorMessage - A C++ string detailing what error occurred, if any.
309 /// TRUE - An error occurred.
310 /// FALSE - No errors.
312 static bool LinkInFile(Module *HeadModule,
313 const std::string &Filename,
314 std::string &ErrorMessage,
317 std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
318 if (M.get() == 0) return true;
319 if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
320 return LinkModules(HeadModule, M.get(), &ErrorMessage);
323 /// LinkFiles - takes a module and a list of files and links them all together.
324 /// It locates the file either in the current directory, as its absolute
325 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
328 /// progname - The name of the program (infamous argv[0]).
329 /// HeadModule - The module under which all files will be linked.
330 /// Files - A vector of C++ strings indicating the LLVM bytecode filenames
331 /// to be linked. The names can refer to a mixture of pure LLVM
332 /// bytecode files and archive (ar) formatted files.
333 /// Verbose - Flags whether verbose output should be printed while linking.
336 /// HeadModule - The module will have the specified LLVM bytecode files linked
340 /// FALSE - No errors.
341 /// TRUE - Some error occurred.
343 bool LinkFiles(const char *progname,
345 const std::vector<std::string> &Files,
348 // String in which to receive error messages.
349 std::string ErrorMessage;
351 // Full pathname of the file
352 std::string Pathname;
354 // Get the library search path from the environment
355 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
357 for (unsigned i = 1; i < Files.size(); ++i) {
358 // Determine where this file lives.
359 if (FileExists(Files[i])) {
362 if (SearchPath == NULL) {
363 std::cerr << progname << ": Cannot find linker input file '"
364 << Files[i] << "'\n";
368 Pathname = std::string(SearchPath)+"/"+Files[i];
369 if (!FileExists(Pathname)) {
370 std::cerr << progname << ": Cannot find linker input file '"
371 << Files[i] << "'\n";
376 // A user may specify an ar archive without -l, perhaps because it
377 // is not installed as a library. Detect that and link the library.
378 if (IsArchive(Pathname)) {
380 std::cerr << "Linking archive '" << Files[i] << "'\n";
382 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
383 PrintAndReturn(progname, ErrorMessage,
384 ": Error linking in '" + Files[i] + "'");
389 std::cerr << "Linking file '" << Files[i] << "'\n";
391 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
392 PrintAndReturn(progname, ErrorMessage,
393 ": Error linking in '" + Files[i] + "'");
402 /// LinkLibraries - takes the specified library files and links them into the
403 /// main bytecode object file.
406 /// progname - The name of the program (infamous argv[0]).
407 /// HeadModule - The module into which all necessary libraries will be linked.
408 /// Libraries - The list of libraries to link into the module.
409 /// LibPaths - The list of library paths in which to find libraries.
410 /// Verbose - Flags whether verbose messages should be printed.
411 /// Native - Flags whether native code is being generated.
414 /// HeadModule - The module will have all necessary libraries linked in.
417 /// FALSE - No error.
420 bool LinkLibraries(const char *progname,
422 const std::vector<std::string> &Libraries,
423 const std::vector<std::string> &LibPaths,
427 // String in which to receive error messages.
428 std::string ErrorMessage;
430 for (unsigned i = 0; i < Libraries.size(); ++i) {
431 // Determine where this library lives.
432 std::string Pathname = FindLib(Libraries[i], LibPaths);
433 if (Pathname.empty()) {
434 // If the pathname does not exist, then continue to the next one if
435 // we're doing a native link and give an error if we're doing a bytecode
438 PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
443 // A user may specify an ar archive without -l, perhaps because it
444 // is not installed as a library. Detect that and link the library.
445 if (IsArchive(Pathname)) {
447 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
449 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
450 PrintAndReturn(progname, ErrorMessage,
451 ": Error linking in '" + Libraries[i] + "'");
456 std::cerr << "Linking file '" << Libraries[i] << "'\n";
458 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
459 PrintAndReturn(progname, ErrorMessage,
460 ": error linking in '" + Libraries[i] + "'");