Move ipsccp pass earlier to clean up obvious bogosities
[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
121 static void dumpArgs(const char **args) {
122   std::cerr << *args++;
123   while (*args)
124     std::cerr << ' ' << *args++;
125   std::cerr << '\n' << std::flush;
126 }
127
128 static inline void addPass(PassManager &PM, Pass *P) {
129   // Add the pass to the pass manager...
130   PM.add(P);
131
132   // If we are verifying all of the intermediate steps, add the verifier...
133   if (Verify) PM.add(createVerifierPass());
134 }
135
136 static bool isBytecodeLibrary(const sys::Path &FullPath) {
137   // Check for a bytecode file
138   if (FullPath.isBytecodeFile()) return true;
139   // Check for a dynamic library file
140   if (FullPath.isDynamicLibrary()) return false;
141   // Check for a true bytecode archive file
142   if (FullPath.isArchive() ) {
143     std::string ErrorMessage;
144     Archive* ar = Archive::OpenAndLoadSymbols( FullPath, &ErrorMessage );
145     return ar->isBytecodeArchive();
146   }
147   return false;
148 }
149
150 static bool isBytecodeLPath(const std::string &LibPath) {
151   sys::Path LPath(LibPath);
152
153   // Make sure it exists and is a directory
154   sys::FileStatus Status;
155   if (LPath.getFileStatus(Status) || !Status.isDir)
156     return false;
157   
158   // Grab the contents of the -L path
159   std::set<sys::Path> Files;
160   if (LPath.getDirectoryContents(Files, 0))
161     return false;
162   
163   // Iterate over the contents one by one to determine
164   // if this -L path has any bytecode shared libraries
165   // or archives
166   std::set<sys::Path>::iterator File = Files.begin();
167   std::string dllsuffix = sys::Path::GetDLLSuffix();
168   for (; File != Files.end(); ++File) {
169
170     // Not a file?
171     if (File->getFileStatus(Status) || Status.isDir)
172       continue;
173
174     std::string path = File->toString();
175
176     // Check for an ending '.dll', '.so' or '.a' suffix as all
177     // other files are not of interest to us here
178     if (path.find(dllsuffix, path.size()-dllsuffix.size()) == std::string::npos
179         && path.find(".a", path.size()-2) == std::string::npos)
180       continue;
181
182     // Finally, check to see if the file is a true bytecode file
183     if (isBytecodeLibrary(*File))
184       return true;
185   }
186   return false;
187 }
188
189 /// GenerateBytecode - generates a bytecode file from the specified module.
190 ///
191 /// Inputs:
192 ///  M           - The module for which bytecode should be generated.
193 ///  StripLevel  - 2 if we should strip all symbols, 1 if we should strip
194 ///                debug info.
195 ///  Internalize - Flags whether all symbols should be marked internal.
196 ///  Out         - Pointer to file stream to which to write the output.
197 ///
198 /// Returns non-zero value on error.
199 ///
200 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
201                            std::ostream *Out) {
202   // In addition to just linking the input from GCC, we also want to spiff it up
203   // a little bit.  Do this now.
204   PassManager Passes;
205
206   if (Verify) Passes.add(createVerifierPass());
207
208   // Add an appropriate TargetData instance for this module...
209   addPass(Passes, new TargetData(M));
210
211   // Often if the programmer does not specify proper prototypes for the
212   // functions they are calling, they end up calling a vararg version of the
213   // function that does not get a body filled in (the real function has typed
214   // arguments).  This pass merges the two functions.
215   addPass(Passes, createFunctionResolvingPass());
216
217   if (!DisableOptimizations) {
218     // Now that composite has been compiled, scan through the module, looking
219     // for a main function.  If main is defined, mark all other functions
220     // internal.
221     addPass(Passes, createInternalizePass(Internalize));
222
223     // Propagate constants at call sites into the functions they call.  This
224     // opens opportunities for globalopt (and inlining) by substituting function
225     // pointers passed as arguments to direct uses of functions.
226     addPass(Passes, createIPSCCPPass());
227     
228     // Now that we internalized some globals, see if we can hack on them!
229     addPass(Passes, createGlobalOptimizerPass());
230
231     // Linking modules together can lead to duplicated global constants, only
232     // keep one copy of each constant...
233     addPass(Passes, createConstantMergePass());
234
235     // Remove unused arguments from functions...
236     addPass(Passes, createDeadArgEliminationPass());
237
238     if (!DisableInline)
239       addPass(Passes, createFunctionInliningPass()); // Inline small functions
240
241     addPass(Passes, createPruneEHPass());            // Remove dead EH info
242     addPass(Passes, createGlobalOptimizerPass());    // Optimize globals again.
243     addPass(Passes, createGlobalDCEPass());          // Remove dead functions
244
245     // If we didn't decide to inline a function, check to see if we can
246     // transform it to pass arguments by value instead of by reference.
247     addPass(Passes, createArgumentPromotionPass());
248
249     // The IPO passes may leave cruft around.  Clean up after them.
250     addPass(Passes, createInstructionCombiningPass());
251
252     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
253
254     // Run a few AA driven optimizations here and now, to cleanup the code.
255     addPass(Passes, createGlobalsModRefPass());      // IP alias analysis
256
257     addPass(Passes, createLICMPass());               // Hoist loop invariants
258     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
259     addPass(Passes, createGCSEPass());               // Remove common subexprs
260     addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
261
262     // Cleanup and simplify the code after the scalar optimizations.
263     addPass(Passes, createInstructionCombiningPass());
264
265     // Delete basic blocks, which optimization passes may have killed...
266     addPass(Passes, createCFGSimplificationPass());
267
268     // Now that we have optimized the program, discard unreachable functions...
269     addPass(Passes, createGlobalDCEPass());
270   }
271
272   // If the -s or -S command line options were specified, strip the symbols out
273   // of the resulting program to make it smaller.  -s and -S are GLD options
274   // that we are supporting.
275   if (StripLevel)
276     addPass(Passes, createStripSymbolsPass(StripLevel == 1));
277
278   // Make sure everything is still good.
279   Passes.add(createVerifierPass());
280
281   // Add the pass that writes bytecode to the output file...
282   addPass(Passes, new WriteBytecodePass(Out));
283
284   // Run our queue of passes all at once now, efficiently.
285   Passes.run(*M);
286
287   return 0;
288 }
289
290 /// GenerateAssembly - generates a native assembly language source file from the
291 /// specified bytecode file.
292 ///
293 /// Inputs:
294 ///  InputFilename  - The name of the output bytecode file.
295 ///  OutputFilename - The name of the file to generate.
296 ///  llc            - The pathname to use for LLC.
297 ///
298 /// Return non-zero value on error.
299 ///
300 int llvm::GenerateAssembly(const std::string &OutputFilename,
301                            const std::string &InputFilename,
302                            const sys::Path &llc,
303                            std::string& ErrMsg,
304                            bool Verbose) {
305   // Run LLC to convert the bytecode file into assembly code.
306   std::vector<const char*> args;
307   args.push_back(llc.c_str());
308   args.push_back("-f");
309   args.push_back("-o");
310   args.push_back(OutputFilename.c_str());
311   args.push_back(InputFilename.c_str());
312   args.push_back(0);
313   if (Verbose) dumpArgs(&args[0]);
314   return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
315 }
316
317 /// GenerateCFile - generates a C source file from the specified bytecode file.
318 int llvm::GenerateCFile(const std::string &OutputFile,
319                         const std::string &InputFile,
320                         const sys::Path &llc,
321                         std::string& ErrMsg,
322                         bool Verbose) {
323   // Run LLC to convert the bytecode file into C.
324   std::vector<const char*> args;
325   args.push_back(llc.c_str());
326   args.push_back("-march=c");
327   args.push_back("-f");
328   args.push_back("-o");
329   args.push_back(OutputFile.c_str());
330   args.push_back(InputFile.c_str());
331   args.push_back(0);
332   if (Verbose) dumpArgs(&args[0]);
333   return sys::Program::ExecuteAndWait(llc, &args[0],0,0,0,&ErrMsg);
334 }
335
336 /// GenerateNative - generates a native executable file from the specified
337 /// assembly source file.
338 ///
339 /// Inputs:
340 ///  InputFilename  - The name of the output bytecode file.
341 ///  OutputFilename - The name of the file to generate.
342 ///  Libraries      - The list of libraries with which to link.
343 ///  gcc            - The pathname to use for GGC.
344 ///  envp           - A copy of the process's current environment.
345 ///
346 /// Outputs:
347 ///  None.
348 ///
349 /// Returns non-zero value on error.
350 ///
351 int llvm::GenerateNative(const std::string &OutputFilename,
352                          const std::string &InputFilename,
353                          const std::vector<std::string> &LibPaths,
354                          const std::vector<std::string> &Libraries,
355                          const sys::Path &gcc, char ** const envp,
356                          bool Shared,
357                          bool ExportAllAsDynamic,
358                          const std::vector<std::string> &RPaths,
359                          const std::string &SOName,
360                          std::string& ErrMsg,
361                          bool Verbose) {
362   // Remove these environment variables from the environment of the
363   // programs that we will execute.  It appears that GCC sets these
364   // environment variables so that the programs it uses can configure
365   // themselves identically.
366   //
367   // However, when we invoke GCC below, we want it to use its normal
368   // configuration.  Hence, we must sanitize its environment.
369   char ** clean_env = CopyEnv(envp);
370   if (clean_env == NULL)
371     return 1;
372   RemoveEnv("LIBRARY_PATH", clean_env);
373   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
374   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
375   RemoveEnv("COMPILER_PATH", clean_env);
376   RemoveEnv("COLLECT_GCC", clean_env);
377
378
379   // Run GCC to assemble and link the program into native code.
380   //
381   // Note:
382   //  We can't just assemble and link the file with the system assembler
383   //  and linker because we don't know where to put the _start symbol.
384   //  GCC mysteriously knows how to do it.
385   std::vector<const char*> args;
386   args.push_back(gcc.c_str());
387   args.push_back("-fno-strict-aliasing");
388   args.push_back("-O3");
389   args.push_back("-o");
390   args.push_back(OutputFilename.c_str());
391   args.push_back(InputFilename.c_str());
392
393   // StringsToDelete - We don't want to call c_str() on temporary strings.
394   // If we need a temporary string, copy it here so that the memory is not
395   // reclaimed until after the exec call.  All of these strings are allocated
396   // with strdup.
397   std::vector<char*> StringsToDelete;
398
399   if (Shared) args.push_back("-shared");
400   if (ExportAllAsDynamic) args.push_back("-export-dynamic");
401   if (!RPaths.empty()) {
402     for (std::vector<std::string>::const_iterator I = RPaths.begin(),
403         E = RPaths.end(); I != E; I++) {
404       std::string rp = "-Wl,-rpath," + *I;
405       StringsToDelete.push_back(strdup(rp.c_str()));
406       args.push_back(StringsToDelete.back());
407     }
408   }
409   if (!SOName.empty()) {
410     std::string so = "-Wl,-soname," + SOName;
411     StringsToDelete.push_back(strdup(so.c_str()));
412     args.push_back(StringsToDelete.back());
413   }
414
415   // Add in the libpaths to find the libraries.
416   //
417   // Note:
418   //  When gccld is called from the llvm-gxx frontends, the -L paths for
419   //  the LLVM cfrontend install paths are appended.  We don't want the
420   //  native linker to use these -L paths as they contain bytecode files.
421   //  Further, we don't want any -L paths that contain bytecode shared
422   //  libraries or true bytecode archive files.  We omit them in all such
423   //  cases.
424   for (unsigned index = 0; index < LibPaths.size(); index++)
425     if (!isBytecodeLPath(LibPaths[index])) {
426       std::string Tmp = "-L"+LibPaths[index];
427       StringsToDelete.push_back(strdup(Tmp.c_str()));
428       args.push_back(StringsToDelete.back());
429     }
430
431   // Add in the libraries to link.
432   for (unsigned index = 0; index < Libraries.size(); index++)
433     // HACK: If this is libg, discard it.  This gets added by the compiler
434     // driver when doing: 'llvm-gcc main.c -Wl,-native -o a.out -g'. Note that
435     // this should really be fixed by changing the llvm-gcc compiler driver.
436     if (Libraries[index] != "crtend" && Libraries[index] != "g") {
437       std::string Tmp = "-l"+Libraries[index];
438       StringsToDelete.push_back(strdup(Tmp.c_str()));
439       args.push_back(StringsToDelete.back());
440     }
441   args.push_back(0); // Null terminate.
442
443   // Run the compiler to assembly and link together the program.
444   if (Verbose) dumpArgs(&args[0]);
445   int Res = sys::Program::ExecuteAndWait(
446       gcc, &args[0],(const char**)clean_env,0,0,&ErrMsg);
447
448   delete [] clean_env;
449
450   while (!StringsToDelete.empty()) {
451     free(StringsToDelete.back());
452     StringsToDelete.pop_back();
453   }
454   return Res;
455 }
456