Adding dllimport, dllexport and external weak linkage types.
[oota-llvm.git] / lib / Linker / LinkArchives.cpp
1 //===- lib/Linker/LinkArchives.cpp - Link 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/Linker.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/Archive.h"
21 #include "llvm/Config/config.h"
22 #include <memory>
23 #include <set>
24 using namespace llvm;
25
26 /// GetAllDefinedSymbols - Modifies its parameter DefinedSymbols to contain the
27 /// name of each externally-visible symbol defined in M.
28 ///
29 static void
30 GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
31   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
32     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
33       DefinedSymbols.insert(I->getName());
34   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
35        I != E; ++I)
36     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
37       DefinedSymbols.insert(I->getName());
38 }
39
40 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
41 /// exist in an LLVM module. This is a bit tricky because there may be two
42 /// symbols with the same name but different LLVM types that will be resolved to
43 /// each other but aren't currently (thus we need to treat it as resolved).
44 ///
45 /// Inputs:
46 ///  M - The module in which to find undefined symbols.
47 ///
48 /// Outputs:
49 ///  UndefinedSymbols - A set of C++ strings containing the name of all
50 ///                     undefined symbols.
51 ///
52 static void
53 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
54   std::set<std::string> DefinedSymbols;
55   UndefinedSymbols.clear();
56
57   // If the program doesn't define a main, try pulling one in from a .a file.
58   // This is needed for programs where the main function is defined in an
59   // archive, such f2c'd programs.
60   Function *Main = M->getMainFunction();
61   if (Main == 0 || Main->isExternal())
62     UndefinedSymbols.insert("main");
63
64   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
65     if (I->hasName()) {
66       if (I->isExternal())
67         UndefinedSymbols.insert(I->getName());
68       else if (!I->hasInternalLinkage()) {
69         assert(!I->hasDLLImportLinkage()
70                && "Found dllimported non-external symbol!");
71         DefinedSymbols.insert(I->getName());
72       }      
73     }
74   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
75        I != E; ++I)
76     if (I->hasName()) {
77       if (I->isExternal())
78         UndefinedSymbols.insert(I->getName());
79       else if (!I->hasInternalLinkage()) {
80         assert(!I->hasDLLImportLinkage()
81                && "Found dllimported non-external symbol!");
82         DefinedSymbols.insert(I->getName());
83       }      
84     }
85
86   // Prune out any defined symbols from the undefined symbols set...
87   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
88        I != UndefinedSymbols.end(); )
89     if (DefinedSymbols.count(*I))
90       UndefinedSymbols.erase(I++);  // This symbol really is defined!
91     else
92       ++I; // Keep this symbol in the undefined symbols list
93 }
94
95 /// LinkInArchive - opens an archive library and link in all objects which
96 /// provide symbols that are currently undefined.
97 ///
98 /// Inputs:
99 ///  Filename - The pathname of the archive.
100 ///
101 /// Return Value:
102 ///  TRUE  - An error occurred.
103 ///  FALSE - No errors.
104 bool
105 Linker::LinkInArchive(const sys::Path &Filename) {
106
107   // Make sure this is an archive file we're dealing with
108   if (!Filename.isArchive())
109     return error("File '" + Filename.toString() + "' is not an archive.");
110
111   // Open the archive file
112   verbose("Linking archive file '" + Filename.toString() + "'");
113
114   // Find all of the symbols currently undefined in the bytecode program.
115   // If all the symbols are defined, the program is complete, and there is
116   // no reason to link in any archive files.
117   std::set<std::string> UndefinedSymbols;
118   GetAllUndefinedSymbols(Composite, UndefinedSymbols);
119
120   if (UndefinedSymbols.empty()) {
121     verbose("No symbols undefined, skipping library '" +
122             Filename.toString() + "'");
123     return false;  // No need to link anything in!
124   }
125
126   std::string ErrMsg;
127   std::auto_ptr<Archive> AutoArch (
128     Archive::OpenAndLoadSymbols(Filename,&ErrMsg));
129
130   Archive* arch = AutoArch.get();
131
132   if (!arch)
133     return error("Cannot read archive '" + Filename.toString() +
134                  "': " + ErrMsg);
135
136   // Save a set of symbols that are not defined by the archive. Since we're
137   // entering a loop, there's no point searching for these multiple times. This
138   // variable is used to "set_subtract" from the set of undefined symbols.
139   std::set<std::string> NotDefinedByArchive;
140
141   // While we are linking in object files, loop.
142   while (true) {
143
144     // Find the modules we need to link into the target module
145     std::set<ModuleProvider*> Modules;
146     if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
147       return error("Cannot find symbols in '" + Filename.toString() + 
148                    "': " + ErrMsg);
149
150     // If we didn't find any more modules to link this time, we are done
151     // searching this archive.
152     if (Modules.empty())
153       break;
154
155     // Any symbols remaining in UndefinedSymbols after
156     // findModulesDefiningSymbols are ones that the archive does not define. So
157     // we add them to the NotDefinedByArchive variable now.
158     NotDefinedByArchive.insert(UndefinedSymbols.begin(),
159         UndefinedSymbols.end());
160
161     // Loop over all the ModuleProviders that we got back from the archive
162     for (std::set<ModuleProvider*>::iterator I=Modules.begin(), E=Modules.end();
163          I != E; ++I) {
164
165       // Get the module we must link in.
166       std::auto_ptr<Module> AutoModule( (*I)->releaseModule() );
167       Module* aModule = AutoModule.get();
168
169       verbose("  Linking in module: " + aModule->getModuleIdentifier());
170
171       // Link it in
172       if (LinkInModule(aModule))
173         return error("Cannot link in module '" +
174                      aModule->getModuleIdentifier() + "': " + Error);
175     }
176
177     // Get the undefined symbols from the aggregate module. This recomputes the
178     // symbols we still need after the new modules have been linked in.
179     GetAllUndefinedSymbols(Composite, UndefinedSymbols);
180
181     // At this point we have two sets of undefined symbols: UndefinedSymbols
182     // which holds the undefined symbols from all the modules, and
183     // NotDefinedByArchive which holds symbols we know the archive doesn't
184     // define. There's no point searching for symbols that we won't find in the
185     // archive so we subtract these sets.
186     set_subtract(UndefinedSymbols, NotDefinedByArchive);
187
188     // If there's no symbols left, no point in continuing to search the
189     // archive.
190     if (UndefinedSymbols.empty())
191       break;
192   }
193
194   return false;
195 }