Remove trailing whitespace
[oota-llvm.git] / tools / gccld / GenerateCode.cpp
1 //===- GenerateCode.cpp - Functions for generating executable files  ------===//
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 file contains functions for generating executable files once linking
11 // has finished.  This includes generating a shell script to run the JIT or
12 // a native executable derived from the bytecode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "gccld.h"
17 #include "llvm/System/Program.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Analysis/LoadValueNumbering.h"
21 #include "llvm/Analysis/Passes.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Bytecode/Archive.h"
24 #include "llvm/Bytecode/WriteBytecodePass.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Support/SystemUtils.h"
29 #include "llvm/Support/CommandLine.h"
30
31 using namespace llvm;
32
33 namespace {
34   cl::opt<bool>
35   DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
36
37   cl::opt<bool>
38   Verify("verify", cl::desc("Verify intermediate results of all passes"));
39
40   cl::opt<bool>
41   DisableOptimizations("disable-opt",
42                        cl::desc("Do not run any optimization passes"));
43 }
44
45 /// CopyEnv - This function takes an array of environment variables and makes a
46 /// copy of it.  This copy can then be manipulated any way the caller likes
47 /// without affecting the process's real environment.
48 ///
49 /// Inputs:
50 ///  envp - An array of C strings containing an environment.
51 ///
52 /// Return value:
53 ///  NULL - An error occurred.
54 ///
55 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
56 ///  in the array is a duplicate of the one in the original array (i.e. we do
57 ///  not copy the char *'s from one array to another).
58 ///
59 static char ** CopyEnv(char ** const envp) {
60   // Count the number of entries in the old list;
61   unsigned entries;   // The number of entries in the old environment list
62   for (entries = 0; envp[entries] != NULL; entries++)
63     /*empty*/;
64
65   // Add one more entry for the NULL pointer that ends the list.
66   ++entries;
67
68   // If there are no entries at all, just return NULL.
69   if (entries == 0)
70     return NULL;
71
72   // Allocate a new environment list.
73   char **newenv = new char* [entries];
74   if ((newenv = new char* [entries]) == NULL)
75     return NULL;
76
77   // Make a copy of the list.  Don't forget the NULL that ends the list.
78   entries = 0;
79   while (envp[entries] != NULL) {
80     newenv[entries] = new char[strlen (envp[entries]) + 1];
81     strcpy (newenv[entries], envp[entries]);
82     ++entries;
83   }
84   newenv[entries] = NULL;
85
86   return newenv;
87 }
88
89
90 /// RemoveEnv - Remove the specified environment variable from the environment
91 /// array.
92 ///
93 /// Inputs:
94 ///  name - The name of the variable to remove.  It cannot be NULL.
95 ///  envp - The array of environment variables.  It cannot be NULL.
96 ///
97 /// Notes:
98 ///  This is mainly done because functions to remove items from the environment
99 ///  are not available across all platforms.  In particular, Solaris does not
100 ///  seem to have an unsetenv() function or a setenv() function (or they are
101 ///  undocumented if they do exist).
102 ///
103 static void RemoveEnv(const char * name, char ** const envp) {
104   for (unsigned index=0; envp[index] != NULL; index++) {
105     // Find the first equals sign in the array and make it an EOS character.
106     char *p = strchr (envp[index], '=');
107     if (p == NULL)
108       continue;
109     else
110       *p = '\0';
111
112     // Compare the two strings.  If they are equal, zap this string.
113     // Otherwise, restore it.
114     if (!strcmp(name, envp[index]))
115       *envp[index] = '\0';
116     else
117       *p = '=';
118   }
119
120   return;
121 }
122
123 static void dumpArgs(const char **args) {
124   std::cout << *args++;
125   while (*args)
126     std::cout << ' ' << *args++;
127   std::cout << '\n';
128 }
129
130 static inline void addPass(PassManager &PM, Pass *P) {
131   // Add the pass to the pass manager...
132   PM.add(P);
133
134   // If we are verifying all of the intermediate steps, add the verifier...
135   if (Verify) PM.add(createVerifierPass());
136 }
137
138 static bool isBytecodeLibrary(const sys::Path &FullPath) {
139   // Check for a bytecode file
140   if (FullPath.isBytecodeFile()) return true;
141   // Check for a dynamic library file
142   if (FullPath.isDynamicLibrary()) return false;
143   // Check for a true bytecode archive file
144   if (FullPath.isArchive() ) {
145     std::string ErrorMessage;
146     Archive* ar = Archive::OpenAndLoadSymbols( FullPath, &ErrorMessage );
147     return ar->isBytecodeArchive();
148   }
149   return false;
150 }
151
152 static bool isBytecodeLPath(const std::string &LibPath) {
153   bool isBytecodeLPath = false;
154
155   // Make sure the -L path has a '/' character
156   // because llvm-g++ passes them without the ending
157   // '/' char and sys::Path doesn't think it is a
158   // directory (see: sys::Path::isDirectory) without it
159   std::string dir = LibPath;
160   if ( dir[dir.length()-1] != '/' )
161   dir.append("/");
162
163   sys::Path LPath(dir);
164
165   // Grab the contents of the -L path
166   std::set<sys::Path> Files;
167   LPath.getDirectoryContents(Files);
168
169   // Iterate over the contents one by one to determine
170   // if this -L path has any bytecode shared libraries
171   // or archives
172   std::set<sys::Path>::iterator File = Files.begin();
173   for (; File != Files.end(); ++File) {
174
175     if ( File->isDirectory() )
176       continue;
177
178     std::string path = File->toString();
179     std::string dllsuffix = sys::Path::GetDLLSuffix();
180
181     // Check for an ending '.dll,.so' or '.a' suffix as all
182     // other files are not of interest to us here
183     if ( path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
184         && path.find(".a", path.size()-2) == std::string::npos )
185       continue;
186
187     // Finally, check to see if the file is a true bytecode file
188     if (isBytecodeLibrary(*File))
189       isBytecodeLPath = true;
190   }
191   return isBytecodeLPath;
192 }
193
194 /// GenerateBytecode - generates a bytecode file from the specified module.
195 ///
196 /// Inputs:
197 ///  M           - The module for which bytecode should be generated.
198 ///  StripLevel  - 2 if we should strip all symbols, 1 if we should strip
199 ///                debug info.
200 ///  Internalize - Flags whether all symbols should be marked internal.
201 ///  Out         - Pointer to file stream to which to write the output.
202 ///
203 /// Returns non-zero value on error.
204 ///
205 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
206                            std::ostream *Out) {
207   // In addition to just linking the input from GCC, we also want to spiff it up
208   // a little bit.  Do this now.
209   PassManager Passes;
210
211   if (Verify) Passes.add(createVerifierPass());
212
213   // Add an appropriate TargetData instance for this module...
214   addPass(Passes, new TargetData("gccld", M));
215
216   // Often if the programmer does not specify proper prototypes for the
217   // functions they are calling, they end up calling a vararg version of the
218   // function that does not get a body filled in (the real function has typed
219   // arguments).  This pass merges the two functions.
220   addPass(Passes, createFunctionResolvingPass());
221
222   if (!DisableOptimizations) {
223     if (Internalize) {
224       // Now that composite has been compiled, scan through the module, looking
225       // for a main function.  If main is defined, mark all other functions
226       // internal.
227       addPass(Passes, createInternalizePass());
228     }
229
230     // Now that we internalized some globals, see if we can hack on them!
231     addPass(Passes, createGlobalOptimizerPass());
232
233     // Linking modules together can lead to duplicated global constants, only
234     // keep one copy of each constant...
235     addPass(Passes, createConstantMergePass());
236
237     // Propagate constants at call sites into the functions they call.
238     addPass(Passes, createIPSCCPPass());
239
240     // Remove unused arguments from functions...
241     addPass(Passes, createDeadArgEliminationPass());
242
243     if (!DisableInline)
244       addPass(Passes, createFunctionInliningPass()); // Inline small functions
245
246     addPass(Passes, createPruneEHPass());            // Remove dead EH info
247     addPass(Passes, createGlobalOptimizerPass());    // Optimize globals again.
248     addPass(Passes, createGlobalDCEPass());          // Remove dead functions
249
250     // If we didn't decide to inline a function, check to see if we can
251     // transform it to pass arguments by value instead of by reference.
252     addPass(Passes, createArgumentPromotionPass());
253
254     // The IPO passes may leave cruft around.  Clean up after them.
255     addPass(Passes, createInstructionCombiningPass());
256
257     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
258
259     // Run a few AA driven optimizations here and now, to cleanup the code.
260     addPass(Passes, createGlobalsModRefPass());      // IP alias analysis
261
262     addPass(Passes, createLICMPass());               // Hoist loop invariants
263     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
264     addPass(Passes, createGCSEPass());               // Remove common subexprs
265     addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
266
267     // Cleanup and simplify the code after the scalar optimizations.
268     addPass(Passes, createInstructionCombiningPass());
269
270     // Delete basic blocks, which optimization passes may have killed...
271     addPass(Passes, createCFGSimplificationPass());
272
273     // Now that we have optimized the program, discard unreachable functions...
274     addPass(Passes, createGlobalDCEPass());
275   }
276
277   // If the -s or -S command line options were specified, strip the symbols out
278   // of the resulting program to make it smaller.  -s and -S are GLD options
279   // that we are supporting.
280   if (StripLevel)
281     addPass(Passes, createStripSymbolsPass(StripLevel == 1));
282
283   // Make sure everything is still good.
284   Passes.add(createVerifierPass());
285
286   // Add the pass that writes bytecode to the output file...
287   addPass(Passes, new WriteBytecodePass(Out));
288
289   // Run our queue of passes all at once now, efficiently.
290   Passes.run(*M);
291
292   return 0;
293 }
294
295 /// GenerateAssembly - generates a native assembly language source file from the
296 /// specified bytecode file.
297 ///
298 /// Inputs:
299 ///  InputFilename  - The name of the output bytecode file.
300 ///  OutputFilename - The name of the file to generate.
301 ///  llc            - The pathname to use for LLC.
302 ///
303 /// Return non-zero value on error.
304 ///
305 int llvm::GenerateAssembly(const std::string &OutputFilename,
306                            const std::string &InputFilename,
307                            const sys::Path &llc,
308                            bool Verbose) {
309   // Run LLC to convert the bytecode file into assembly code.
310   std::vector<const char*> args;
311   args.push_back(llc.c_str());
312   args.push_back("-f");
313   args.push_back("-o");
314   args.push_back(OutputFilename.c_str());
315   args.push_back(InputFilename.c_str());
316   args.push_back(0);
317   if (Verbose) dumpArgs(&args[0]);
318   return sys::Program::ExecuteAndWait(llc, &args[0]);
319 }
320
321 /// GenerateAssembly - generates a native assembly language source file from the
322 /// specified bytecode file.
323 int llvm::GenerateCFile(const std::string &OutputFile,
324                         const std::string &InputFile,
325                         const sys::Path &llc,
326                         bool Verbose) {
327   // Run LLC to convert the bytecode file into C.
328   std::vector<const char*> args;
329   args.push_back(llc.c_str());
330   args.push_back("-march=c");
331   args.push_back("-f");
332   args.push_back("-o");
333   args.push_back(OutputFile.c_str());
334   args.push_back(InputFile.c_str());
335   args.push_back(0);
336   if (Verbose) dumpArgs(&args[0]);
337   return sys::Program::ExecuteAndWait(llc, &args[0]);
338 }
339
340 /// GenerateNative - generates a native assembly language source file from the
341 /// specified assembly source file.
342 ///
343 /// Inputs:
344 ///  InputFilename  - The name of the output bytecode file.
345 ///  OutputFilename - The name of the file to generate.
346 ///  Libraries      - The list of libraries with which to link.
347 ///  gcc            - The pathname to use for GGC.
348 ///  envp           - A copy of the process's current environment.
349 ///
350 /// Outputs:
351 ///  None.
352 ///
353 /// Returns non-zero value on error.
354 ///
355 int llvm::GenerateNative(const std::string &OutputFilename,
356                          const std::string &InputFilename,
357                          const std::vector<std::string> &LibPaths,
358                          const std::vector<std::string> &Libraries,
359                          const sys::Path &gcc, char ** const envp,
360                          bool Shared,
361                          const std::string &RPath,
362                          const std::string &SOName,
363                          bool Verbose) {
364   // Remove these environment variables from the environment of the
365   // programs that we will execute.  It appears that GCC sets these
366   // environment variables so that the programs it uses can configure
367   // themselves identically.
368   //
369   // However, when we invoke GCC below, we want it to use its normal
370   // configuration.  Hence, we must sanitize its environment.
371   char ** clean_env = CopyEnv(envp);
372   if (clean_env == NULL)
373     return 1;
374   RemoveEnv("LIBRARY_PATH", clean_env);
375   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
376   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
377   RemoveEnv("COMPILER_PATH", clean_env);
378   RemoveEnv("COLLECT_GCC", clean_env);
379
380
381   // Run GCC to assemble and link the program into native code.
382   //
383   // Note:
384   //  We can't just assemble and link the file with the system assembler
385   //  and linker because we don't know where to put the _start symbol.
386   //  GCC mysteriously knows how to do it.
387   std::vector<const char*> args;
388   args.push_back(gcc.c_str());
389   args.push_back("-fno-strict-aliasing");
390   args.push_back("-O3");
391   args.push_back("-o");
392   args.push_back(OutputFilename.c_str());
393   args.push_back(InputFilename.c_str());
394
395   if (Shared) args.push_back("-shared");
396   if (!RPath.empty()) {
397     std::string rp = "-Wl,-rpath," + RPath;
398     args.push_back(rp.c_str());
399   }
400   if (!SOName.empty()) {
401     std::string so = "-Wl,-soname," + SOName;
402     args.push_back(so.c_str());
403   }
404
405   // Add in the libpaths to find the libraries.
406   //
407   // Note:
408   //  When gccld is called from the llvm-gxx frontends, the -L paths for
409   //  the LLVM cfrontend install paths are appended.  We don't want the
410   //  native linker to use these -L paths as they contain bytecode files.
411   //  Further, we don't want any -L paths that contain bytecode shared
412   //  libraries or true bytecode archive files.  We omit them in all such
413   //  cases.
414   for (unsigned index = 0; index < LibPaths.size(); index++) {
415     if (!isBytecodeLPath( LibPaths[index]) ) {
416       args.push_back("-L");
417       args.push_back(LibPaths[index].c_str());
418     }
419   }
420
421   // Add in the libraries to link.
422   for (unsigned index = 0; index < Libraries.size(); index++) {
423     if (Libraries[index] != "crtend") {
424       args.push_back("-l");
425       args.push_back(Libraries[index].c_str());
426     }
427   }
428   args.push_back(0);
429
430   // Run the compiler to assembly and link together the program.
431   if (Verbose) dumpArgs(&args[0]);
432   return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
433 }
434