Revert previous patch, I'm a moron :)
[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/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Analysis/LoadValueNumbering.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Transforms/Utils/Linker.h"
26 #include "Support/SystemUtils.h"
27 #include "Support/CommandLine.h"
28 using namespace llvm;
29
30 namespace {
31   cl::opt<bool>
32   DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
33
34   cl::opt<bool>
35   Verify("verify", cl::desc("Verify intermediate results of all passes"));
36
37   cl::opt<bool>
38   DisableOptimizations("disable-opt",
39                        cl::desc("Do not run any optimization passes"));
40 }
41
42 static inline void addPass(PassManager &PM, Pass *P) {
43   // Add the pass to the pass manager...
44   PM.add(P);
45   
46   // If we are verifying all of the intermediate steps, add the verifier...
47   if (Verify) PM.add(createVerifierPass());
48 }
49
50 /// GenerateBytecode - generates a bytecode file from the specified module.
51 ///
52 /// Inputs:
53 ///  M           - The module for which bytecode should be generated.
54 ///  Strip       - Flags whether symbols should be stripped from the output.
55 ///  Internalize - Flags whether all symbols should be marked internal.
56 ///  Out         - Pointer to file stream to which to write the output.
57 ///
58 /// Returns non-zero value on error.
59 ///
60 int llvm::GenerateBytecode(Module *M, bool Strip, bool Internalize,
61                            std::ostream *Out) {
62   // In addition to just linking the input from GCC, we also want to spiff it up
63   // a little bit.  Do this now.
64   PassManager Passes;
65
66   if (Verify) Passes.add(createVerifierPass());
67
68   // Add an appropriate TargetData instance for this module...
69   addPass(Passes, new TargetData("gccld", M));
70
71   // Often if the programmer does not specify proper prototypes for the
72   // functions they are calling, they end up calling a vararg version of the
73   // function that does not get a body filled in (the real function has typed
74   // arguments).  This pass merges the two functions.
75   addPass(Passes, createFunctionResolvingPass());
76
77   if (!DisableOptimizations) {
78     if (Internalize) {
79       // Now that composite has been compiled, scan through the module, looking
80       // for a main function.  If main is defined, mark all other functions
81       // internal.
82       addPass(Passes, createInternalizePass());
83     }
84
85     // Now that we internalized some globals, see if we can mark any globals as
86     // being constant!
87     addPass(Passes, createGlobalConstifierPass());
88
89     // Linking modules together can lead to duplicated global constants, only
90     // keep one copy of each constant...
91     addPass(Passes, createConstantMergePass());
92
93     // If the -s command line option was specified, strip the symbols out of the
94     // resulting program to make it smaller.  -s is a GCC option that we are
95     // supporting.
96     if (Strip)
97       addPass(Passes, createSymbolStrippingPass());
98
99     // Propagate constants at call sites into the functions they call.
100     addPass(Passes, createIPConstantPropagationPass());
101
102     // Remove unused arguments from functions...
103     addPass(Passes, createDeadArgEliminationPass());
104
105     if (!DisableInline)
106       addPass(Passes, createFunctionInliningPass()); // Inline small functions
107
108     // If we didn't decide to inline a function, check to see if we can
109     // transform it to pass arguments by value instead of by reference.
110     addPass(Passes, createArgumentPromotionPass());
111
112     // The IPO passes may leave cruft around.  Clean up after them.
113     addPass(Passes, createInstructionCombiningPass());
114
115     addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
116
117     // Run a few AA driven optimizations here and now, to cleanup the code.
118     // Eventually we should put an IP AA in place here.
119
120     addPass(Passes, createLICMPass());               // Hoist loop invariants
121     addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
122     addPass(Passes, createGCSEPass());               // Remove common subexprs
123
124     // Cleanup and simplify the code after the scalar optimizations.
125     addPass(Passes, createInstructionCombiningPass());
126
127     // Delete basic blocks, which optimization passes may have killed...
128     addPass(Passes, createCFGSimplificationPass());
129
130     // Now that we have optimized the program, discard unreachable functions...
131     addPass(Passes, createGlobalDCEPass());
132   }
133
134   // Make sure everything is still good.
135   Passes.add(createVerifierPass());
136
137   // Add the pass that writes bytecode to the output file...
138   addPass(Passes, new WriteBytecodePass(Out));
139
140   // Run our queue of passes all at once now, efficiently.
141   Passes.run(*M);
142
143   return 0;
144 }
145
146 /// GenerateAssembly - generates a native assembly language source file from the
147 /// specified bytecode file.
148 ///
149 /// Inputs:
150 ///  InputFilename  - The name of the output bytecode file.
151 ///  OutputFilename - The name of the file to generate.
152 ///  llc            - The pathname to use for LLC.
153 ///  envp           - The environment to use when running LLC.
154 ///
155 /// Return non-zero value on error.
156 ///
157 int llvm::GenerateAssembly(const std::string &OutputFilename,
158                            const std::string &InputFilename,
159                            const std::string &llc,
160                            char ** const envp) {
161   // Run LLC to convert the bytecode file into assembly code.
162   const char *cmd[6];
163   cmd[0] = llc.c_str();
164   cmd[1] = "-f";
165   cmd[2] = "-o";
166   cmd[3] = OutputFilename.c_str();
167   cmd[4] = InputFilename.c_str();
168   cmd[5] = 0;
169
170   return ExecWait(cmd, envp);
171 }
172
173 /// GenerateAssembly - generates a native assembly language source file from the
174 /// specified bytecode file.
175 int llvm::GenerateCFile(const std::string &OutputFile,
176                         const std::string &InputFile,
177                         const std::string &llc, char ** const envp) {
178   // Run LLC to convert the bytecode file into C.
179   const char *cmd[7];
180
181   cmd[0] = llc.c_str();
182   cmd[1] = "-march=c";
183   cmd[2] = "-f";
184   cmd[3] = "-o";
185   cmd[4] = OutputFile.c_str();
186   cmd[5] = InputFile.c_str();
187   cmd[6] = 0;
188   return ExecWait(cmd, envp);
189 }
190
191 /// GenerateNative - generates a native assembly language source file from the
192 /// specified assembly source file.
193 ///
194 /// Inputs:
195 ///  InputFilename  - The name of the output bytecode file.
196 ///  OutputFilename - The name of the file to generate.
197 ///  Libraries      - The list of libraries with which to link.
198 ///  LibPaths       - The list of directories in which to find libraries.
199 ///  gcc            - The pathname to use for GGC.
200 ///  envp           - A copy of the process's current environment.
201 ///
202 /// Outputs:
203 ///  None.
204 ///
205 /// Returns non-zero value on error.
206 ///
207 int llvm::GenerateNative(const std::string &OutputFilename,
208                          const std::string &InputFilename,
209                          const std::vector<std::string> &Libraries,
210                          const std::vector<std::string> &LibPaths,
211                          const std::string &gcc, char ** const envp) {
212   // Remove these environment variables from the environment of the
213   // programs that we will execute.  It appears that GCC sets these
214   // environment variables so that the programs it uses can configure
215   // themselves identically.
216   //
217   // However, when we invoke GCC below, we want it to use its normal
218   // configuration.  Hence, we must sanitize its environment.
219   char ** clean_env = CopyEnv(envp);
220   if (clean_env == NULL)
221     return 1;
222   RemoveEnv("LIBRARY_PATH", clean_env);
223   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
224   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
225   RemoveEnv("COMPILER_PATH", clean_env);
226   RemoveEnv("COLLECT_GCC", clean_env);
227
228   std::vector<const char *> cmd;
229
230   // Run GCC to assemble and link the program into native code.
231   //
232   // Note:
233   //  We can't just assemble and link the file with the system assembler
234   //  and linker because we don't know where to put the _start symbol.
235   //  GCC mysteriously knows how to do it.
236   cmd.push_back(gcc.c_str());
237   cmd.push_back("-O3");
238   cmd.push_back("-o");
239   cmd.push_back(OutputFilename.c_str());
240   cmd.push_back(InputFilename.c_str());
241
242   // Adding the library paths creates a problem for native generation.  If we
243   // include the search paths from llvmgcc, then we'll be telling normal gcc
244   // to look inside of llvmgcc's library directories for libraries.  This is
245   // bad because those libraries hold only bytecode files (not native object
246   // files).  In the end, we attempt to link the bytecode libgcc into a native
247   // program.
248 #if 0
249   // Add in the library path options.
250   for (unsigned index=0; index < LibPaths.size(); index++) {
251     cmd.push_back("-L");
252     cmd.push_back(LibPaths[index].c_str());
253   }
254 #endif
255
256   // Add in the libraries to link.
257   std::vector<std::string> Libs(Libraries);
258   for (unsigned index = 0; index < Libs.size(); index++) {
259     if (Libs[index] != "crtend") {
260       Libs[index] = "-l" + Libs[index];
261       cmd.push_back(Libs[index].c_str());
262     }
263   }
264   cmd.push_back(NULL);
265
266   // Run the compiler to assembly and link together the program.
267   return ExecWait(&(cmd[0]), clean_env);
268 }