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