1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
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.
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.
14 //===----------------------------------------------------------------------===//
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"
36 // Function: FileExists ()
39 // Determine if the specified filename exists and is readable.
42 // FN - The name of the file.
48 // TRUE - The file exists and is readable.
49 // FALSE - The file does not exist or is unreadable.
51 static inline bool FileExists(const std::string &FN) {
52 return access(FN.c_str(), R_OK | F_OK) != -1;
56 // Function: IsArchive ()
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.
63 // filename - A C++ string containing the name of the file.
69 // TRUE - The file is an archive.
70 // FALSE - The file is not an archive.
72 static inline bool IsArchive(const std::string &filename)
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;
83 // Function: FindLib ()
86 // This function locates a particular library. It will prepend and append
87 // various directories, prefixes, and suffixes until it can find the library.
90 // Filename - Name of the file to find.
91 // Paths - List of directories to search.
97 // The name of the file is returned.
98 // If the file is not found, an empty string is returned.
101 FindLib(const std::string &Filename, const std::vector<std::string> &Paths)
103 // Determine if the pathname can be found as it stands.
104 if (FileExists(Filename))
107 // If that doesn't work, convert the name into a library name.
108 std::string LibName = "lib" + Filename;
110 // Iterate over the directories in Paths to see if we can find the library
112 for (unsigned Index = 0; Index != Paths.size(); ++Index) {
113 std::string Directory = Paths[Index] + "/";
115 if (FileExists(Directory + LibName + ".bc"))
116 return Directory + LibName + ".bc";
118 if (FileExists(Directory + LibName + ".so"))
119 return Directory + LibName + ".so";
121 if (FileExists(Directory + LibName + ".a"))
122 return Directory + LibName + ".a";
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();
130 LibName = std::string(SearchPath) + "/" + LibName;
131 if (FileExists(LibName))
134 return std::string();
138 // Function: GetAllDefinedSymbols ()
141 // Find all of the defined symbols in the specified module.
144 // M - The module in which to find defined symbols.
147 // DefinedSymbols - A set of C++ strings that will contain the name of all
154 GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols)
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());
165 // Function: GetAllUndefinedSymbols ()
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).
174 // M - The module in which to find undefined symbols.
177 // UndefinedSymbols - A set of C++ strings containing the name of all
178 // undefined symbols.
184 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols)
186 std::set<std::string> DefinedSymbols;
187 UndefinedSymbols.clear(); // Start out empty
189 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
192 UndefinedSymbols.insert(I->getName());
193 else if (!I->hasInternalLinkage())
194 DefinedSymbols.insert(I->getName());
196 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
199 UndefinedSymbols.insert(I->getName());
200 else if (!I->hasInternalLinkage())
201 DefinedSymbols.insert(I->getName());
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!
210 ++I; // Keep this symbol in the undefined symbols list
215 // Function: LoadObject ()
218 // Read the specified bytecode object file.
221 // FN - The name of the file to load.
224 // OutErrorMessage - The error message to give back to the caller.
227 // A pointer to a module represening the bytecode file is returned.
228 // If an error occurs, the pointer is 0.
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>();
241 // Function: LinkInArchive ()
244 // This function will open an archive library and link in all objects which
245 // provide symbols that are currently undefined.
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.
253 // ErrorMessage - A C++ string detailing what error occurred, if any.
256 // TRUE - An error occurred.
257 // FALSE - No errors.
259 static bool LinkInArchive(Module *M,
260 const std::string &Filename,
261 std::string &ErrorMessage,
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.
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!
277 // Load in the archive objects.
279 if (Verbose) std::cerr << " Loading '" << Filename << "'\n";
280 std::vector<Module*> Objects;
281 if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
285 // Figure out which symbols are defined by all of the modules in the archive.
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]);
293 // While we are linking in object files, loop.
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.
302 const std::set<std::string> &DefSymbols = DefinedSymbols[i];
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)) {
309 std::cerr << " Found object providing symbol '" << *I << "'...\n";
310 ObjectRequired = true;
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...
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());
324 DefinedSymbols.pop_back();
325 --i; // Do not skip an entry
327 // The undefined symbols set should have shrunk.
328 GetAllUndefinedSymbols(M, UndefinedSymbols);
329 Linked = true; // We have linked something in!
338 // Function: LinkInFile ()
341 // This function will open an archive library and link in all objects which
342 // provide symbols that are currently undefined.
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.
350 // ErrorMessage - A C++ string detailing what error occurred, if any.
353 // TRUE - An error occurred.
354 // FALSE - No errors.
356 static bool LinkInFile(Module *HeadModule,
357 const std::string &Filename,
358 std::string &ErrorMessage,
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);
368 // Function: LinkFiles ()
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.
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.
385 // HeadModule - The module will have the specified LLVM bytecode files linked
389 // FALSE - No errors.
390 // TRUE - Some error occurred.
392 bool LinkFiles(const char *progname,
394 const std::vector<std::string> &Files,
397 // String in which to receive error messages.
398 std::string ErrorMessage;
400 // Full pathname of the file
401 std::string Pathname;
403 // Get the library search path from the environment
404 char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
406 for (unsigned i = 1; i < Files.size(); ++i) {
407 // Determine where this file lives.
408 if (FileExists(Files[i])) {
411 if (SearchPath == NULL) {
412 std::cerr << "Cannot find " << Files[i];
416 Pathname = std::string(SearchPath)+"/"+Files[i];
417 if (!FileExists(Pathname)) {
418 std::cerr << "Cannot find " << Files[i];
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)) {
427 std::cerr << "Linking archive '" << Files[i] << "'\n";
429 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
430 PrintAndReturn(progname, ErrorMessage,
431 ": Error linking in '" + Files[i] + "'");
436 std::cerr << "Linking file '" << Files[i] << "'\n";
438 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
439 PrintAndReturn(progname, ErrorMessage,
440 ": error linking in '" + Files[i] + "'");
450 // Function: LinkLibraries ()
453 // This function takes the specified library files and links them into the
454 // main bytecode object file.
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.
465 // HeadModule - The module will have all necessary libraries linked in.
471 bool LinkLibraries(const char *progname,
473 const std::vector<std::string> &Libraries,
474 const std::vector<std::string> &LibPaths,
478 // String in which to receive error messages.
479 std::string ErrorMessage;
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
489 PrintAndReturn(progname, "Cannot find " + Libraries[i]);
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)) {
498 std::cerr << "Linking archive '" << Libraries[i] << "'\n";
500 if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
501 PrintAndReturn(progname, ErrorMessage,
502 ": Error linking in '" + Libraries[i] + "'");
507 std::cerr << "Linking file '" << Libraries[i] << "'\n";
509 if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
510 PrintAndReturn(progname, ErrorMessage,
511 ": error linking in '" + Libraries[i] + "'");