4c32c18089a977b27d4bfe9ab5298507690fd44f
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.cpp - LLVM 'ld' compatible 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 is intended to be compatible with GCC, and follows standard
11 // system 'ld' conventions.  As such, the default output file is ./a.out.
12 // Additionally, this program outputs a shell script that is used to invoke LLI
13 // to execute the program.  In this manner, the generated executable (a.out for
14 // example), is directly executable, whereas the bytecode file actually lives in
15 // the a.out.bc file generated by this program.  Also, Force is on by default.
16 //
17 // Note that if someone (or a script) deletes the executable program generated,
18 // the .bc file will be left around.  Considering that this is a temporary hack,
19 // I'm not too worried about this.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "gccld.h"
24 #include "llvm/Module.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Bytecode/Reader.h"
27 #include "llvm/Bytecode/WriteBytecodePass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Utils/Linker.h"
32 #include "Support/CommandLine.h"
33 #include "Support/FileUtilities.h"
34 #include "Support/Signals.h"
35 #include "Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38
39 using namespace llvm;
40
41 namespace {
42   cl::list<std::string> 
43   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
44                  cl::OneOrMore);
45
46   cl::opt<std::string> 
47   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
48                  cl::value_desc("filename"));
49
50   cl::opt<bool>    
51   Verbose("v", cl::desc("Print information about actions taken"));
52   
53   cl::list<std::string> 
54   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
55            cl::value_desc("directory"));
56
57   cl::list<std::string> 
58   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
59             cl::value_desc("library prefix"));
60
61   cl::opt<bool>
62   Strip("s", cl::desc("Strip symbol info from executable"));
63
64   cl::opt<bool>
65   NoInternalize("disable-internalize",
66                 cl::desc("Do not mark all symbols as internal"));
67   cl::alias
68   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
69                 cl::aliasopt(NoInternalize));
70
71   cl::opt<bool>
72   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
73                                             " library, not an executable"));
74   cl::alias
75   Relink("r", cl::desc("Alias for -link-as-library"),
76          cl::aliasopt(LinkAsLibrary));
77
78   cl::opt<bool>    
79   Native("native",
80          cl::desc("Generate a native binary instead of a shell script"));
81   
82   // Compatibility options that are ignored but supported by LD
83   cl::opt<std::string>
84   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
85   cl::opt<std::string>
86   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
87   cl::opt<bool>
88   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
89 }
90
91 namespace llvm {
92
93 /// PrintAndReturn - Prints a message to standard error and returns a value
94 /// usable for an exit status.
95 ///
96 /// Inputs:
97 ///  progname - The name of the program (i.e. argv[0]).
98 ///  Message  - The message to print to standard error.
99 ///  Extra    - Extra information to print between the program name and thei
100 ///             message.  It is optional.
101 ///
102 /// Return value:
103 ///  Returns a value that can be used as the exit status (i.e. for exit()).
104 ///
105 int
106 PrintAndReturn(const char *progname,
107                const std::string &Message,
108                const std::string &Extra)
109 {
110   std::cerr << progname << Extra << ": " << Message << "\n";
111   return 1;
112 }
113
114 /// CopyEnv - This function takes an array of environment variables and makes a
115 /// copy of it.  This copy can then be manipulated any way the caller likes
116 /// without affecting the process's real environment.
117 ///
118 /// Inputs:
119 ///  envp - An array of C strings containing an environment.
120 ///
121 /// Return value:
122 ///  NULL - An error occurred.
123 ///
124 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
125 ///  in the array is a duplicate of the one in the original array (i.e. we do
126 ///  not copy the char *'s from one array to another).
127 ///
128 char ** CopyEnv(char ** const envp) {
129   // Count the number of entries in the old list;
130   unsigned entries;   // The number of entries in the old environment list
131   for (entries = 0; envp[entries] != NULL; entries++)
132     /*empty*/;
133
134   // Add one more entry for the NULL pointer that ends the list.
135   ++entries;
136
137   // If there are no entries at all, just return NULL.
138   if (entries == 0)
139     return NULL;
140
141   // Allocate a new environment list.
142   char **newenv = new char* [entries];
143   if ((newenv = new char* [entries]) == NULL)
144     return NULL;
145
146   // Make a copy of the list.  Don't forget the NULL that ends the list.
147   entries = 0;
148   while (envp[entries] != NULL) {
149     newenv[entries] = new char[strlen (envp[entries]) + 1];
150     strcpy (newenv[entries], envp[entries]);
151     ++entries;
152   }
153   newenv[entries] = NULL;
154
155   return newenv;
156 }
157
158
159 /// RemoveEnv - Remove the specified environment variable from the environment
160 /// array.
161 ///
162 /// Inputs:
163 ///  name - The name of the variable to remove.  It cannot be NULL.
164 ///  envp - The array of environment variables.  It cannot be NULL.
165 ///
166 /// Notes:
167 ///  This is mainly done because functions to remove items from the environment
168 ///  are not available across all platforms.  In particular, Solaris does not
169 ///  seem to have an unsetenv() function or a setenv() function (or they are
170 ///  undocumented if they do exist).
171 ///
172 void RemoveEnv(const char * name, char ** const envp) {
173   for (unsigned index=0; envp[index] != NULL; index++) {
174     // Find the first equals sign in the array and make it an EOS character.
175     char *p = strchr (envp[index], '=');
176     if (p == NULL)
177       continue;
178     else
179       *p = '\0';
180
181     // Compare the two strings.  If they are equal, zap this string.
182     // Otherwise, restore it.
183     if (!strcmp(name, envp[index]))
184       *envp[index] = '\0';
185     else
186       *p = '=';
187   }
188
189   return;
190 }
191
192 } // End llvm namespace
193
194 int main(int argc, char **argv, char **envp) {
195   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
196
197   std::string ModuleID("gccld-output");
198   std::auto_ptr<Module> Composite(new Module(ModuleID));
199
200   // We always look first in the current directory when searching for libraries.
201   LibPaths.insert(LibPaths.begin(), ".");
202
203   // If the user specified an extra search path in their environment, respect
204   // it.
205   if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
206     LibPaths.push_back(SearchPath);
207
208   // Remove any consecutive duplicates of the same library...
209   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
210                   Libraries.end());
211
212   // Link in all of the files
213   if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
214     return 1; // Error already printed
215
216   if (!LinkAsLibrary)
217     LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
218                   Verbose, Native);
219
220   // Link in all of the libraries next...
221
222   // Create the output file.
223   std::string RealBytecodeOutput = OutputFilename;
224   if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
225   std::ofstream Out(RealBytecodeOutput.c_str());
226   if (!Out.good())
227     return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
228                                    "' for writing!");
229
230   // Ensure that the bytecode file gets removed from the disk if we get a
231   // SIGINT signal.
232   RemoveFileOnSignal(RealBytecodeOutput);
233
234   // Generate the bytecode file.
235   if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
236     Out.close();
237     return PrintAndReturn(argv[0], "error generating bytecode");
238   }
239
240   // Close the bytecode file.
241   Out.close();
242
243   // If we are not linking a library, generate either a native executable
244   // or a JIT shell script, depending upon what the user wants.
245   if (!LinkAsLibrary) {
246     // If the user wants to generate a native executable, compile it from the
247     // bytecode file.
248     //
249     // Otherwise, create a script that will run the bytecode through the JIT.
250     if (Native) {
251       // Name of the Assembly Language output file
252       std::string AssemblyFile = OutputFilename + ".s";
253
254       // Mark the output files for removal if we get an interrupt.
255       RemoveFileOnSignal(AssemblyFile);
256       RemoveFileOnSignal(OutputFilename);
257
258       // Determine the locations of the llc and gcc programs.
259       std::string llc = FindExecutable("llc", argv[0]);
260       std::string gcc = FindExecutable("gcc", argv[0]);
261       if (llc.empty())
262         return PrintAndReturn(argv[0], "Failed to find llc");
263
264       if (gcc.empty())
265         return PrintAndReturn(argv[0], "Failed to find gcc");
266
267       // Generate an assembly language file for the bytecode.
268       if (Verbose) std::cout << "Generating Assembly Code\n";
269       GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
270       if (Verbose) std::cout << "Generating Native Code\n";
271       GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
272                      gcc, envp);
273
274       // Remove the assembly language file.
275       removeFile (AssemblyFile);
276     } else {
277       // Output the script to start the program...
278       std::ofstream Out2(OutputFilename.c_str());
279       if (!Out2.good())
280         return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
281                                        "' for writing!");
282       Out2 << "#!/bin/sh\nlli \\\n";
283       // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
284       LibPaths.push_back("/lib");
285       LibPaths.push_back("/usr/lib");
286       LibPaths.push_back("/usr/X11R6/lib");
287       // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
288       // shared object at all! See RH 8: plain text.
289       std::vector<std::string>::iterator libc = 
290         std::find(Libraries.begin(), Libraries.end(), "c");
291       if (libc != Libraries.end()) Libraries.erase(libc);
292       // List all the shared object (native) libraries this executable will need
293       // on the command line, so that we don't have to do this manually!
294       for (std::vector<std::string>::iterator i = Libraries.begin(), 
295              e = Libraries.end(); i != e; ++i) {
296         std::string FullLibraryPath = FindLib(*i, LibPaths, true);
297         if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
298           Out2 << "    -load=" << FullLibraryPath << " \\\n";
299       }
300       Out2 << "    $0.bc $*\n";
301       Out2.close();
302     }
303   
304     // Make the script executable...
305     MakeFileExecutable(OutputFilename);
306
307     // Make the bytecode file readable and directly executable in LLEE as well
308     MakeFileExecutable(RealBytecodeOutput);
309     MakeFileReadable(RealBytecodeOutput);
310   }
311
312   return 0;
313 }