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