Squelch compilation warnings on Sparc
[oota-llvm.git] / tools / llvm-link / llvm-link.cpp
1 //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
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 utility may be invoked in the following manner:
11 //  llvm-link a.bc b.bc c.bc -o x.bc
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Module.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Bytecode/Reader.h"
18 #include "llvm/Bytecode/Writer.h"
19 #include "llvm/Support/Linker.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/System/Signals.h"
23 #include "llvm/System/Path.h"
24 #include "llvm/ADT/SetVector.h"
25 #include <fstream>
26 #include <iostream>
27 #include <memory>
28
29 using namespace llvm;
30
31 static cl::list<std::string>
32 InputFilenames(cl::Positional, cl::OneOrMore,
33                cl::desc("<input bytecode files>"));
34
35 static cl::opt<std::string>
36 OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
37                cl::value_desc("filename"));
38
39 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
40
41 static cl::opt<bool>
42 Verbose("v", cl::desc("Print information about actions taken"));
43
44 static cl::opt<bool>
45 DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
46
47 static cl::list<std::string>
48 LibPaths("L", cl::desc("Specify a library search path"), cl::ZeroOrMore,
49          cl::value_desc("directory"), cl::Prefix);
50
51 static cl::list<std::string>
52 Libraries("l", cl::desc("Specify library names to link with"), cl::ZeroOrMore,
53           cl::Prefix, cl::value_desc("library name"));
54
55 // GetModule - This function is just factored out of the functions below
56 static inline Module* GetModule(const sys::Path& Filename) {
57   if (Verbose) std::cerr << "Loading '" << Filename.c_str() << "'\n";
58   std::string ErrorMessage;
59   if (Filename.exists()) {
60     Module* Result = ParseBytecodeFile(Filename.get(), &ErrorMessage);
61     if (Result) return Result;   // Load successful!
62
63     if (Verbose) {
64       std::cerr << "Error opening bytecode file: '" << Filename.c_str() << "'";
65       if (ErrorMessage.size()) std::cerr << ": " << ErrorMessage;
66       std::cerr << "\n";
67     }
68   } else {
69     std::cerr << "Bytecode file: '" << Filename.c_str() 
70               << "' does not exist.\n";
71   }
72   return 0;
73 }
74
75 // LoadFile - Read the specified bytecode file in and return it.  This routine
76 // searches the link path for the specified file to try to find it...
77 //
78 static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
79   sys::Path Filename;
80   if (!Filename.set_file(FN)) {
81     std::cerr << "Invalid file name: '" << Filename.c_str() << "'\n";
82     return std::auto_ptr<Module>();
83   }
84
85   if (Module* Result = GetModule(Filename)) 
86     return std::auto_ptr<Module>(Result);
87
88   bool FoundAFile = false;
89
90   for (unsigned i = 0; i < LibPaths.size(); i++) {
91     if (!Filename.set_directory(LibPaths[i])) {
92       std::cerr << "Invalid library path: '" << LibPaths[i] << "'\n";
93     } else if (!Filename.append_file(FN)) {
94       std::cerr << "Invalid library path: '" << LibPaths[i]
95                 << "/" << FN.c_str() << "'\n";
96     } else if (Filename.exists()) {
97       FoundAFile = true;
98       if (Module *Result = GetModule(Filename))
99         return std::auto_ptr<Module>(Result);   // Load successful!
100     }
101   }
102
103   if (FoundAFile)
104     std::cerr << "Bytecode file '" << FN << "' corrupt!  "
105               << "Use 'llvm-link -v ...' for more info.\n";
106   else
107     std::cerr << "Could not locate bytecode file: '" << FN << "'\n";
108   return std::auto_ptr<Module>();
109 }
110
111 sys::Path GetPathForLinkageItem(const std::string& link_item,
112                                 const std::string& dir) {
113   sys::Path fullpath;
114   fullpath.set_directory(dir);
115
116   // Try *.o
117   fullpath.append_file(link_item);
118   fullpath.append_suffix("o");
119   if (fullpath.readable()) 
120     return fullpath;
121
122   // Try *.bc
123   fullpath.elide_suffix();
124   fullpath.append_suffix("bc");
125   if (fullpath.readable()) 
126     return fullpath;
127
128   // Try *.so
129   fullpath.elide_suffix();
130   fullpath.append_suffix(sys::Path::GetDLLSuffix());
131   if (fullpath.readable())
132     return fullpath;
133
134   // Try lib*.a
135   fullpath.set_directory(dir);
136   fullpath.append_file(std::string("lib") + link_item);
137   fullpath.append_suffix("a");
138   if (fullpath.readable())
139     return fullpath;
140
141   // Didn't find one.
142   fullpath.clear();
143   return fullpath;
144 }
145
146 static inline bool LoadLibrary(const std::string &FN, Module*& Result) {
147   Result = 0;
148   sys::Path Filename;
149   if (!Filename.set_file(FN)) {
150     return false;
151   }
152
153   if (Filename.readable() && Filename.is_bytecode_file()) {
154     if ((Result = GetModule(Filename)))
155       return true;
156   }
157
158   bool foundAFile = false;
159
160   for (unsigned I = 0; I < LibPaths.size(); I++) {
161     sys::Path path = GetPathForLinkageItem(FN,LibPaths[I]);
162     if (!path.is_empty()) {
163       if (path.is_bytecode_file()) {
164         if ((Result = GetModule(path))) {
165           return true;
166         } else {
167           // We found file but its not a valid bytecode file so we 
168           // return false and leave Result null.
169           return false;
170         }
171       } else {
172         // We found a file, but its not a bytecode file so we return
173         // false and leave Result null.
174         return false;
175       }
176     }
177   }
178
179   // We didn't find a file so we leave Result null and return
180   // false to indicate that the library should be just left in the
181   // emitted module as resolvable at runtime.
182   return false;
183 }
184
185 int main(int argc, char **argv) {
186   cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
187   sys::PrintStackTraceOnErrorSignal();
188   assert(InputFilenames.size() > 0 && "OneOrMore is not working");
189
190   unsigned BaseArg = 0;
191   std::string ErrorMessage;
192
193   std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
194   if (Composite.get() == 0) return 1;
195
196   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
197     std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
198     if (M.get() == 0) return 1;
199
200     if (Verbose) std::cerr << "Linking in '" << InputFilenames[i] << "'\n";
201
202     if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
203       std::cerr << argv[0] << ": link error in '" << InputFilenames[i]
204                 << "': " << ErrorMessage << "\n";
205       return 1;
206     }
207   }
208
209   // Get the list of dependent libraries from the composite module
210   const Module::LibraryListType& libs = Composite.get()->getLibraries();
211
212   // Iterate over the list of dependent libraries, linking them in as we
213   // find them
214   Module::LibraryListType::const_iterator I = libs.begin();
215   while (I != libs.end()) {
216     Module* Mod = 0;
217     if (LoadLibrary(*I,Mod)) {
218       if (Mod != 0) {
219         std::auto_ptr<Module> M(Mod);
220         if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
221           std::cerr << argv[0] << ": link error in '" << *I
222                 << "': " << ErrorMessage << "\n";
223           return 1;
224         }
225       } else {
226         std::cerr << argv[0] << ": confused loading library '" << *I
227           << "'. Aborting\n";
228         return 2;
229       }
230     }
231     ++I;
232   }
233
234   // TODO: Iterate over the -l list and link in any modules containing
235   // global symbols that have not been resolved so far.
236
237   if (DumpAsm) std::cerr << "Here's the assembly:\n" << Composite.get();
238
239   std::ostream *Out = &std::cout;  // Default to printing to stdout...
240   if (OutputFilename != "-") {
241     if (!Force && std::ifstream(OutputFilename.c_str())) {
242       // If force is not specified, make sure not to overwrite a file!
243       std::cerr << argv[0] << ": error opening '" << OutputFilename
244                 << "': file exists!\n"
245                 << "Use -f command line argument to force output\n";
246       return 1;
247     }
248     Out = new std::ofstream(OutputFilename.c_str());
249     if (!Out->good()) {
250       std::cerr << argv[0] << ": error opening '" << OutputFilename << "'!\n";
251       return 1;
252     }
253
254     // Make sure that the Out file gets unlinked from the disk if we get a
255     // SIGINT
256     sys::RemoveFileOnSignal(OutputFilename);
257   }
258
259   if (verifyModule(*Composite.get())) {
260     std::cerr << argv[0] << ": linked module is broken!\n";
261     return 1;
262   }
263
264   if (Verbose) std::cerr << "Writing bytecode...\n";
265   WriteBytecodeToFile(Composite.get(), *Out);
266
267   if (Out != &std::cout) delete Out;
268   return 0;
269 }