* Implement linking to libraries
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM 'GCCLD' UTILITY 
3 //
4 // This utility is intended to be compatible with GCC, and follows standard
5 // system ld conventions.  As such, the default output file is ./a.out.
6 // Additionally, this program outputs a shell script that is used to invoke LLI
7 // to execute the program.  In this manner, the generated executable (a.out for
8 // example), is directly executable, whereas the bytecode file actually lives in
9 // the a.out.bc file generated by this program.  Also, Force is on by default.
10 //
11 // Note that if someone (or a script) deletes the executable program generated,
12 // the .bc file will be left around.  Considering that this is a temporary hack,
13 // I'm not to worried about this.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Linker.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/Writer.h"
20 #include "llvm/Module.h"
21 #include "llvm/Method.h"
22 #include "Support/CommandLine.h"
23 #include <fstream>
24 #include <memory>
25 #include <algorithm>
26 #include <sys/types.h>     // For FileExists
27 #include <sys/stat.h>
28
29
30 cl::StringList InputFilenames("", "Load <arg> files, linking them together", 
31                               cl::OneOrMore);
32 cl::String OutputFilename("o", "Override output filename", cl::NoFlags,"a.out");
33 cl::Flag   Verbose       ("v", "Print information about actions taken");
34 cl::StringList LibPaths  ("L", "Specify a library search path", cl::ZeroOrMore);
35 cl::StringList Libraries ("l", "Specify libraries to link to", cl::ZeroOrMore);
36
37
38 // FileExists - Return true if the specified string is an openable file...
39 static inline bool FileExists(const std::string &FN) {
40   struct stat StatBuf;
41   return stat(FN.c_str(), &StatBuf) != -1;
42 }
43
44 // LoadFile - Read the specified bytecode file in and return it.  This routine
45 // searches the link path for the specified file to try to find it...
46 //
47 static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
48   std::string Filename = FN;
49   std::string ErrorMessage;
50
51   unsigned NextLibPathIdx = 0;
52   bool FoundAFile = false;
53
54   while (1) {
55     if (Verbose) cerr << "Loading '" << Filename << "'\n";
56     if (FileExists(Filename)) FoundAFile = true;
57     Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
58     if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
59
60     if (Verbose) {
61       cerr << "Error opening bytecode file: '" << Filename << "'";
62       if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
63       cerr << endl;
64     }
65     
66     if (NextLibPathIdx == LibPaths.size()) break;
67     Filename = LibPaths[NextLibPathIdx++] + "/" + FN;
68   }
69
70   if (FoundAFile)
71     cerr << "Bytecode file '" << FN << "' corrupt!  "
72          << "Use 'link -v ...' for more info.\n";
73   else
74     cerr << "Could not locate bytecode file: '" << FN << "'\n";
75   return std::auto_ptr<Module>();
76 }
77
78
79
80
81 int main(int argc, char **argv) {
82   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n",
83                               cl::EnableSingleLetterArgValue |
84                               cl::DisableSingleLetterArgGrouping);
85   assert(InputFilenames.size() > 0 && "OneOrMore is not working");
86
87   unsigned BaseArg = 0;
88   std::string ErrorMessage;
89
90   if (!Libraries.empty()) {
91     // Sort libraries list...
92     sort(Libraries.begin(), Libraries.end());
93
94     // Remove duplicate libraries entries...
95     Libraries.erase(unique(Libraries.begin(), Libraries.end()),
96                     Libraries.end());
97
98     // Add all of the libraries to the end of the link line...
99     for (unsigned i = 0; i < Libraries.size(); ++i)
100       InputFilenames.push_back("lib" + Libraries[i] + ".bc");
101   }
102
103   std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
104   if (Composite.get() == 0) return 1;
105
106   for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
107     std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
108     if (M.get() == 0) return 1;
109
110     if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
111
112     if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
113       cerr << "Error linking in '" << InputFilenames[i] << "': "
114            << ErrorMessage << endl;
115       return 1;
116     }
117   }
118
119   std::ofstream Out((OutputFilename+".bc").c_str());
120   if (!Out.good()) {
121     cerr << "Error opening '" << OutputFilename << ".bc' for writing!\n";
122     return 1;
123   }
124
125   if (Verbose) cerr << "Writing bytecode...\n";
126   WriteBytecodeToFile(Composite.get(), Out);
127   Out.close();
128
129   // Output the script to start the program...
130   std::ofstream Out2(OutputFilename.c_str());
131   if (!Out2.good()) {
132     cerr << "Error openeing '" << OutputFilename << "' for writing!\n";
133     return 1;
134   }
135   Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
136   Out2.close();
137   
138   // Make the script executable...
139   chmod(OutputFilename.c_str(), 0755);
140
141   return 0;
142 }