llvm.org GIT mirror llvm / 634bd85
[Linker] Drop support for IR-level extended linking support (archives, etc.). - This code is dead, and the "right" way to get this support is to use the platform-specific linker-integrated LTO mechanisms, or the forthcoming LLVM linker. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@172749 91177308-0d34-0410-b5e6-96231b3b80d8 Daniel Dunbar 7 years ago
6 changed file(s) with 3 addition(s) and 577 deletion(s). Raw diff Collapse all Expand all
499499 The ``TargetData`` structure has been renamed to ``DataLayout`` and moved to
500500 ``VMCore`` to remove a dependency on ``Target``.
501501
502 #. ...
502 #. The IR-level extended linker APIs (for example, to link bitcode files out of
503 archives) have been removed. Any existing clients of these features should
504 move to using a linker with integrated LTO support.
503505
504506 Tools Changes
505507 -------------
152152 /// @brief Set control flags.
153153 void setFlags(unsigned flags) { Flags = flags; }
154154
155 /// This method is the main interface to the linker. It can be used to
156 /// link a set of linkage items into a module. A linkage item is either a
157 /// file name with fully qualified path, or a library for which the Linker's
158 /// LibraryPath will be utilized to locate the library. The bool value in
159 /// the LinkItemKind should be set to true for libraries. This function
160 /// allows linking to preserve the order of specification associated with
161 /// the command line, or for other purposes. Each item will be linked in
162 /// turn as it occurs in \p Items.
163 /// @returns true if an error occurred, false otherwise
164 /// @see LinkItemKind
165 /// @see getLastError
166 bool LinkInItems (
167 const ItemList& Items, ///< Set of libraries/files to link in
168 ItemList& NativeItems ///< Output list of native files/libs
169 );
170
171 /// This function links the bitcode \p Files into the composite module.
172 /// Note that this does not do any linking of unresolved symbols. The \p
173 /// Files are all completely linked into \p HeadModule regardless of
174 /// unresolved symbols. This function just loads each bitcode file and
175 /// calls LinkInModule on them.
176 /// @returns true if an error occurs, false otherwise
177 /// @see getLastError
178 /// @brief Link in multiple files.
179 bool LinkInFiles (
180 const std::vector & Files ///< Files to link in
181 );
182
183 /// This function links a single bitcode file, \p File, into the composite
184 /// module. Note that this does not attempt to resolve symbols. This method
185 /// just loads the bitcode file and calls LinkInModule on it. If an error
186 /// occurs, the Linker's error string is set.
187 /// @returns true if an error occurs, false otherwise
188 /// @see getLastError
189 /// @brief Link in a single file.
190 bool LinkInFile(
191 const sys::Path& File, ///< File to link in.
192 bool &is_native ///< Indicates if the file is native object file
193 );
194
195 /// This function provides a way to selectively link in a set of modules,
196 /// found in libraries, based on the unresolved symbols in the composite
197 /// module. Each item in \p Libraries should be the base name of a library,
198 /// as if given with the -l option of a linker tool. The Linker's LibPaths
199 /// are searched for the \p Libraries and any found will be linked in with
200 /// LinkInArchive. If an error occurs, the Linker's error string is set.
201 /// @see LinkInArchive
202 /// @see getLastError
203 /// @returns true if an error occurs, false otherwise
204 /// @brief Link libraries into the module
205 bool LinkInLibraries (
206 const std::vector & Libraries ///< Libraries to link in
207 );
208
209 /// This function provides a way to selectively link in a set of modules,
210 /// found in one library, based on the unresolved symbols in the composite
211 /// module.The \p Library should be the base name of a library, as if given
212 /// with the -l option of a linker tool. The Linker's LibPaths are searched
213 /// for the \p Library and if found, it will be linked in with via the
214 /// LinkInArchive method. If an error occurs, the Linker's error string is
215 /// set.
216 /// @see LinkInArchive
217 /// @see getLastError
218 /// @returns true if an error occurs, false otherwise
219 /// @brief Link one library into the module
220 bool LinkInLibrary (
221 StringRef Library, ///< The library to link in
222 bool& is_native ///< Indicates if lib a native library
223 );
224
225 /// This function links one bitcode archive, \p Filename, into the module.
226 /// The archive is searched to resolve outstanding symbols. Any modules in
227 /// the archive that resolve outstanding symbols will be linked in. The
228 /// library is searched repeatedly until no more modules that resolve
229 /// symbols can be found. If an error occurs, the error string is set.
230 /// To speed up this function, ensure the archive has been processed
231 /// llvm-ranlib or the S option was given to llvm-ar when the archive was
232 /// created. These tools add a symbol table to the archive which makes the
233 /// search for undefined symbols much faster.
234 /// @see getLastError
235 /// @returns true if an error occurs, otherwise false.
236 /// @brief Link in one archive.
237 bool LinkInArchive(
238 const sys::Path& Filename, ///< Filename of the archive to link
239 bool& is_native ///< Indicates if archive is a native archive
240 );
241
242155 /// This method links the \p Src module into the Linker's Composite module
243156 /// by calling LinkModules. All the other LinkIn* methods eventually
244157 /// result in calling this method to link a Module into the Linker's
267180 static bool LinkModules(Module* Dest, Module* Src, unsigned Mode,
268181 std::string* ErrorMsg);
269182
270 /// This function looks through the Linker's LibPaths to find a library with
271 /// the name \p Filename. If the library cannot be found, the returned path
272 /// will be empty (i.e. sys::Path::isEmpty() will return true).
273 /// @returns A sys::Path to the found library
274 /// @brief Find a library from its short name.
275 sys::Path FindLib(StringRef Filename);
276
277183 /// @}
278184 /// @name Implementation
279185 /// @{
0 add_llvm_library(LLVMLinker
1 LinkArchives.cpp
2 LinkItems.cpp
31 LinkModules.cpp
42 Linker.cpp
53 )
+0
-197
lib/Linker/LinkArchives.cpp less more
None //===- lib/Linker/LinkArchives.cpp - Link LLVM objects and libraries ------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains routines to handle linking together LLVM bitcode files,
10 // and to handle annoying things like static libraries.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker.h"
15 #include "llvm/ADT/SetOperations.h"
16 #include "llvm/Bitcode/Archive.h"
17 #include "llvm/IR/Module.h"
18 #include
19 #include
20 using namespace llvm;
21
22 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
23 /// exist in an LLVM module. This is a bit tricky because there may be two
24 /// symbols with the same name but different LLVM types that will be resolved to
25 /// each other but aren't currently (thus we need to treat it as resolved).
26 ///
27 /// Inputs:
28 /// M - The module in which to find undefined symbols.
29 ///
30 /// Outputs:
31 /// UndefinedSymbols - A set of C++ strings containing the name of all
32 /// undefined symbols.
33 ///
34 static void
35 GetAllUndefinedSymbols(Module *M, std::set &UndefinedSymbols) {
36 std::set DefinedSymbols;
37 UndefinedSymbols.clear();
38
39 // If the program doesn't define a main, try pulling one in from a .a file.
40 // This is needed for programs where the main function is defined in an
41 // archive, such f2c'd programs.
42 Function *Main = M->getFunction("main");
43 if (Main == 0 || Main->isDeclaration())
44 UndefinedSymbols.insert("main");
45
46 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
47 if (I->hasName()) {
48 if (I->isDeclaration())
49 UndefinedSymbols.insert(I->getName());
50 else if (!I->hasLocalLinkage()) {
51 assert(!I->hasDLLImportLinkage()
52 && "Found dllimported non-external symbol!");
53 DefinedSymbols.insert(I->getName());
54 }
55 }
56
57 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
58 I != E; ++I)
59 if (I->hasName()) {
60 if (I->isDeclaration())
61 UndefinedSymbols.insert(I->getName());
62 else if (!I->hasLocalLinkage()) {
63 assert(!I->hasDLLImportLinkage()
64 && "Found dllimported non-external symbol!");
65 DefinedSymbols.insert(I->getName());
66 }
67 }
68
69 for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
70 I != E; ++I)
71 if (I->hasName())
72 DefinedSymbols.insert(I->getName());
73
74 // Prune out any defined symbols from the undefined symbols set...
75 for (std::set::iterator I = UndefinedSymbols.begin();
76 I != UndefinedSymbols.end(); )
77 if (DefinedSymbols.count(*I))
78 UndefinedSymbols.erase(I++); // This symbol really is defined!
79 else
80 ++I; // Keep this symbol in the undefined symbols list
81 }
82
83 /// LinkInArchive - opens an archive library and link in all objects which
84 /// provide symbols that are currently undefined.
85 ///
86 /// Inputs:
87 /// Filename - The pathname of the archive.
88 ///
89 /// Return Value:
90 /// TRUE - An error occurred.
91 /// FALSE - No errors.
92 bool
93 Linker::LinkInArchive(const sys::Path &Filename, bool &is_native) {
94 // Make sure this is an archive file we're dealing with
95 if (!Filename.isArchive())
96 return error("File '" + Filename.str() + "' is not an archive.");
97
98 // Open the archive file
99 verbose("Linking archive file '" + Filename.str() + "'");
100
101 // Find all of the symbols currently undefined in the bitcode program.
102 // If all the symbols are defined, the program is complete, and there is
103 // no reason to link in any archive files.
104 std::set UndefinedSymbols;
105 GetAllUndefinedSymbols(Composite, UndefinedSymbols);
106
107 if (UndefinedSymbols.empty()) {
108 verbose("No symbols undefined, skipping library '" + Filename.str() + "'");
109 return false; // No need to link anything in!
110 }
111
112 std::string ErrMsg;
113 std::auto_ptr AutoArch (
114 Archive::OpenAndLoadSymbols(Filename, Context, &ErrMsg));
115
116 Archive* arch = AutoArch.get();
117
118 if (!arch)
119 return error("Cannot read archive '" + Filename.str() +
120 "': " + ErrMsg);
121 if (!arch->isBitcodeArchive()) {
122 is_native = true;
123 return false;
124 }
125 is_native = false;
126
127 // Save a set of symbols that are not defined by the archive. Since we're
128 // entering a loop, there's no point searching for these multiple times. This
129 // variable is used to "set_subtract" from the set of undefined symbols.
130 std::set NotDefinedByArchive;
131
132 // Save the current set of undefined symbols, because we may have to make
133 // multiple passes over the archive:
134 std::set CurrentlyUndefinedSymbols;
135
136 do {
137 CurrentlyUndefinedSymbols = UndefinedSymbols;
138
139 // Find the modules we need to link into the target module. Note that arch
140 // keeps ownership of these modules and may return the same Module* from a
141 // subsequent call.
142 SmallVector Modules;
143 if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrMsg))
144 return error("Cannot find symbols in '" + Filename.str() +
145 "': " + ErrMsg);
146
147 // If we didn't find any more modules to link this time, we are done
148 // searching this archive.
149 if (Modules.empty())
150 break;
151
152 // Any symbols remaining in UndefinedSymbols after
153 // findModulesDefiningSymbols are ones that the archive does not define. So
154 // we add them to the NotDefinedByArchive variable now.
155 NotDefinedByArchive.insert(UndefinedSymbols.begin(),
156 UndefinedSymbols.end());
157
158 // Loop over all the Modules that we got back from the archive
159 for (SmallVectorImpl::iterator I=Modules.begin(), E=Modules.end();
160 I != E; ++I) {
161
162 // Get the module we must link in.
163 std::string moduleErrorMsg;
164 Module* aModule = *I;
165 if (aModule != NULL) {
166 if (aModule->MaterializeAll(&moduleErrorMsg))
167 return error("Could not load a module: " + moduleErrorMsg);
168
169 verbose(" Linking in module: " + aModule->getModuleIdentifier());
170
171 // Link it in
172 if (LinkInModule(aModule, &moduleErrorMsg))
173 return error("Cannot link in module '" +
174 aModule->getModuleIdentifier() + "': " + moduleErrorMsg);
175 }
176 }
177
178 // Get the undefined symbols from the aggregate module. This recomputes the
179 // symbols we still need after the new modules have been linked in.
180 GetAllUndefinedSymbols(Composite, UndefinedSymbols);
181
182 // At this point we have two sets of undefined symbols: UndefinedSymbols
183 // which holds the undefined symbols from all the modules, and
184 // NotDefinedByArchive which holds symbols we know the archive doesn't
185 // define. There's no point searching for symbols that we won't find in the
186 // archive so we subtract these sets.
187 set_subtract(UndefinedSymbols, NotDefinedByArchive);
188
189 // If there's no symbols left, no point in continuing to search the
190 // archive.
191 if (UndefinedSymbols.empty())
192 break;
193 } while (CurrentlyUndefinedSymbols != UndefinedSymbols);
194
195 return false;
196 }
+0
-216
lib/Linker/LinkItems.cpp less more
None //===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains routines to handle linking together LLVM bitcode files,
10 // and to handle annoying things like static libraries.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker.h"
15 #include "llvm/Bitcode/ReaderWriter.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/system_error.h"
21 using namespace llvm;
22
23 // LinkItems - This function is the main entry point into linking. It takes a
24 // list of LinkItem which indicates the order the files should be linked and
25 // how each file should be treated (plain file or with library search). The
26 // function only links bitcode and produces a result list of items that are
27 // native objects.
28 bool
29 Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) {
30 // Clear the NativeItems just in case
31 NativeItems.clear();
32
33 // For each linkage item ...
34 for (ItemList::const_iterator I = Items.begin(), E = Items.end();
35 I != E; ++I) {
36 if (I->second) {
37 // Link in the library suggested.
38 bool is_native = false;
39 if (LinkInLibrary(I->first, is_native))
40 return true;
41 if (is_native)
42 NativeItems.push_back(*I);
43 } else {
44 // Link in the file suggested
45 bool is_native = false;
46 if (LinkInFile(sys::Path(I->first), is_native))
47 return true;
48 if (is_native)
49 NativeItems.push_back(*I);
50 }
51 }
52
53 return false;
54 }
55
56
57 /// LinkInLibrary - links one library into the HeadModule.
58 ///
59 bool Linker::LinkInLibrary(StringRef Lib, bool& is_native) {
60 is_native = false;
61 // Determine where this library lives.
62 sys::Path Pathname = FindLib(Lib);
63 if (Pathname.isEmpty())
64 return error("Cannot find library '" + Lib.str() + "'");
65
66 // If its an archive, try to link it in
67 std::string Magic;
68 Pathname.getMagicNumber(Magic, 64);
69 switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
70 default: llvm_unreachable("Bad file type identification");
71 case sys::Unknown_FileType:
72 return warning("Supposed library '" + Lib.str() + "' isn't a library.");
73
74 case sys::Bitcode_FileType:
75 // LLVM ".so" file.
76 if (LinkInFile(Pathname, is_native))
77 return true;
78 break;
79
80 case sys::Archive_FileType:
81 if (LinkInArchive(Pathname, is_native))
82 return error("Cannot link archive '" + Pathname.str() + "'");
83 break;
84
85 case sys::ELF_Relocatable_FileType:
86 case sys::ELF_SharedObject_FileType:
87 case sys::Mach_O_Object_FileType:
88 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
89 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
90 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
91 case sys::COFF_FileType:
92 is_native = true;
93 break;
94 }
95 return false;
96 }
97
98 /// LinkLibraries - takes the specified library files and links them into the
99 /// main bitcode object file.
100 ///
101 /// Inputs:
102 /// Libraries - The list of libraries to link into the module.
103 ///
104 /// Return value:
105 /// FALSE - No error.
106 /// TRUE - Error.
107 ///
108 bool Linker::LinkInLibraries(const std::vector &Libraries) {
109
110 // Process the set of libraries we've been provided.
111 bool is_native = false;
112 for (unsigned i = 0; i < Libraries.size(); ++i)
113 if (LinkInLibrary(Libraries[i], is_native))
114 return true;
115
116 return false;
117 }
118
119 /// LinkInFile - opens a bitcode file and links in all objects which
120 /// provide symbols that are currently undefined.
121 ///
122 /// Inputs:
123 /// File - The pathname of the bitcode file.
124 ///
125 /// Outputs:
126 /// ErrorMessage - A C++ string detailing what error occurred, if any.
127 ///
128 /// Return Value:
129 /// TRUE - An error occurred.
130 /// FALSE - No errors.
131 ///
132 bool Linker::LinkInFile(const sys::Path &File, bool &is_native) {
133 is_native = false;
134
135 // Check for a file of name "-", which means "read standard input"
136 if (File.str() == "-") {
137 std::auto_ptr M;
138 OwningPtr Buffer;
139 error_code ec;
140 if (!(ec = MemoryBuffer::getSTDIN(Buffer))) {
141 if (!Buffer->getBufferSize()) {
142 Error = "standard input is empty";
143 } else {
144 M.reset(ParseBitcodeFile(Buffer.get(), Context, &Error));
145 if (M.get())
146 if (!LinkInModule(M.get(), &Error))
147 return false;
148 }
149 }
150 return error("Cannot link stdin: " + ec.message());
151 }
152
153 // Determine what variety of file it is.
154 std::string Magic;
155 if (!File.getMagicNumber(Magic, 64))
156 return error("Cannot find linker input '" + File.str() + "'");
157
158 switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
159 default: llvm_unreachable("Bad file type identification");
160 case sys::Unknown_FileType:
161 return warning("Ignoring file '" + File.str() +
162 "' because does not contain bitcode.");
163
164 case sys::Archive_FileType:
165 // A user may specify an ar archive without -l, perhaps because it
166 // is not installed as a library. Detect that and link the archive.
167 if (LinkInArchive(File, is_native))
168 return true;
169 break;
170
171 case sys::Bitcode_FileType: {
172 verbose("Linking bitcode file '" + File.str() + "'");
173 std::auto_ptr M(LoadObject(File));
174 if (M.get() == 0)
175 return error("Cannot load file '" + File.str() + "': " + Error);
176 if (LinkInModule(M.get(), &Error))
177 return error("Cannot link file '" + File.str() + "': " + Error);
178
179 verbose("Linked in file '" + File.str() + "'");
180 break;
181 }
182
183 case sys::ELF_Relocatable_FileType:
184 case sys::ELF_SharedObject_FileType:
185 case sys::Mach_O_Object_FileType:
186 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
187 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
188 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
189 case sys::COFF_FileType:
190 is_native = true;
191 break;
192 }
193 return false;
194 }
195
196 /// LinkFiles - takes a module and a list of files and links them all together.
197 /// It locates the file either in the current directory, as its absolute
198 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
199 ///
200 /// Inputs:
201 /// Files - A vector of sys::Path indicating the LLVM bitcode filenames
202 /// to be linked. The names can refer to a mixture of pure LLVM
203 /// bitcode files and archive (ar) formatted files.
204 ///
205 /// Return value:
206 /// FALSE - No errors.
207 /// TRUE - Some error occurred.
208 ///
209 bool Linker::LinkInFiles(const std::vector &Files) {
210 bool is_native;
211 for (unsigned i = 0; i < Files.size(); ++i)
212 if (LinkInFile(Files[i], is_native))
213 return true;
214 return false;
215 }
111111 Error += ": " + ParseErrorMessage;
112112 return std::auto_ptr();
113113 }
114
115 // IsLibrary - Determine if "Name" is a library in "Directory". Return
116 // a non-empty sys::Path if its found, an empty one otherwise.
117 static inline sys::Path IsLibrary(StringRef Name,
118 const sys::Path &Directory) {
119
120 sys::Path FullPath(Directory);
121
122 // Try the libX.a form
123 FullPath.appendComponent(("lib" + Name).str());
124 FullPath.appendSuffix("a");
125 if (FullPath.isArchive())
126 return FullPath;
127
128 // Try the libX.bca form
129 FullPath.eraseSuffix();
130 FullPath.appendSuffix("bca");
131 if (FullPath.isArchive())
132 return FullPath;
133
134 // Try the libX.so (or .dylib) form
135 FullPath.eraseSuffix();
136 FullPath.appendSuffix(sys::Path::GetDLLSuffix());
137 if (FullPath.isDynamicLibrary()) // Native shared library?
138 return FullPath;
139 if (FullPath.isBitcodeFile()) // .so file containing bitcode?
140 return FullPath;
141
142 // Try libX form, to make it possible to add dependency on the
143 // specific version of .so, like liblzma.so.1.0.0
144 FullPath.eraseSuffix();
145 if (FullPath.isDynamicLibrary()) // Native shared library?
146 return FullPath;
147 if (FullPath.isBitcodeFile()) // .so file containing bitcode?
148 return FullPath;
149
150 // Not found .. fall through
151
152 // Indicate that the library was not found in the directory.
153 FullPath.clear();
154 return FullPath;
155 }
156
157 /// FindLib - Try to convert Filename into the name of a file that we can open,
158 /// if it does not already name a file we can open, by first trying to open
159 /// Filename, then libFilename.[suffix] for each of a set of several common
160 /// library suffixes, in each of the directories in LibPaths. Returns an empty
161 /// Path if no matching file can be found.
162 ///
163 sys::Path
164 Linker::FindLib(StringRef Filename) {
165 // Determine if the pathname can be found as it stands.
166 sys::Path FilePath(Filename);
167 if (FilePath.canRead() &&
168 (FilePath.isArchive() || FilePath.isDynamicLibrary()))
169 return FilePath;
170
171 // Iterate over the directories in Paths to see if we can find the library
172 // there.
173 for (unsigned Index = 0; Index != LibPaths.size(); ++Index) {
174 sys::Path Directory(LibPaths[Index]);
175 sys::Path FullPath = IsLibrary(Filename, Directory);
176 if (!FullPath.isEmpty())
177 return FullPath;
178 }
179 return sys::Path();
180 }