1 //===- GenerateCode.cpp - Functions for generating executable files ------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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/WriteBytecodePass.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/IPO.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/CommandLine.h"
34 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
37 Verify("verify", cl::desc("Verify intermediate results of all passes"));
40 DisableOptimizations("disable-opt",
41 cl::desc("Do not run any optimization passes"));
44 /// CopyEnv - This function takes an array of environment variables and makes a
45 /// copy of it. This copy can then be manipulated any way the caller likes
46 /// without affecting the process's real environment.
49 /// envp - An array of C strings containing an environment.
52 /// NULL - An error occurred.
54 /// Otherwise, a pointer to a new array of C strings is returned. Every string
55 /// in the array is a duplicate of the one in the original array (i.e. we do
56 /// not copy the char *'s from one array to another).
58 static char ** CopyEnv(char ** const envp) {
59 // Count the number of entries in the old list;
60 unsigned entries; // The number of entries in the old environment list
61 for (entries = 0; envp[entries] != NULL; entries++)
64 // Add one more entry for the NULL pointer that ends the list.
67 // If there are no entries at all, just return NULL.
71 // Allocate a new environment list.
72 char **newenv = new char* [entries];
73 if ((newenv = new char* [entries]) == NULL)
76 // Make a copy of the list. Don't forget the NULL that ends the list.
78 while (envp[entries] != NULL) {
79 newenv[entries] = new char[strlen (envp[entries]) + 1];
80 strcpy (newenv[entries], envp[entries]);
83 newenv[entries] = NULL;
89 /// RemoveEnv - Remove the specified environment variable from the environment
93 /// name - The name of the variable to remove. It cannot be NULL.
94 /// envp - The array of environment variables. It cannot be NULL.
97 /// This is mainly done because functions to remove items from the environment
98 /// are not available across all platforms. In particular, Solaris does not
99 /// seem to have an unsetenv() function or a setenv() function (or they are
100 /// undocumented if they do exist).
102 static void RemoveEnv(const char * name, char ** const envp) {
103 for (unsigned index=0; envp[index] != NULL; index++) {
104 // Find the first equals sign in the array and make it an EOS character.
105 char *p = strchr (envp[index], '=');
111 // Compare the two strings. If they are equal, zap this string.
112 // Otherwise, restore it.
113 if (!strcmp(name, envp[index]))
122 static inline void addPass(PassManager &PM, Pass *P) {
123 // Add the pass to the pass manager...
126 // If we are verifying all of the intermediate steps, add the verifier...
127 if (Verify) PM.add(createVerifierPass());
130 /// GenerateBytecode - generates a bytecode file from the specified module.
133 /// M - The module for which bytecode should be generated.
134 /// StripLevel - 2 if we should strip all symbols, 1 if we should strip
136 /// Internalize - Flags whether all symbols should be marked internal.
137 /// Out - Pointer to file stream to which to write the output.
139 /// Returns non-zero value on error.
141 int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
143 // In addition to just linking the input from GCC, we also want to spiff it up
144 // a little bit. Do this now.
147 if (Verify) Passes.add(createVerifierPass());
149 // Add an appropriate TargetData instance for this module...
150 addPass(Passes, new TargetData("gccld", M));
152 // Often if the programmer does not specify proper prototypes for the
153 // functions they are calling, they end up calling a vararg version of the
154 // function that does not get a body filled in (the real function has typed
155 // arguments). This pass merges the two functions.
156 addPass(Passes, createFunctionResolvingPass());
158 if (!DisableOptimizations) {
160 // Now that composite has been compiled, scan through the module, looking
161 // for a main function. If main is defined, mark all other functions
163 addPass(Passes, createInternalizePass());
166 // Now that we internalized some globals, see if we can hack on them!
167 addPass(Passes, createGlobalOptimizerPass());
169 // Linking modules together can lead to duplicated global constants, only
170 // keep one copy of each constant...
171 addPass(Passes, createConstantMergePass());
173 // Propagate constants at call sites into the functions they call.
174 addPass(Passes, createIPSCCPPass());
176 // Remove unused arguments from functions...
177 addPass(Passes, createDeadArgEliminationPass());
180 addPass(Passes, createFunctionInliningPass()); // Inline small functions
182 addPass(Passes, createPruneEHPass()); // Remove dead EH info
183 addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again.
184 addPass(Passes, createGlobalDCEPass()); // Remove dead functions
186 // If we didn't decide to inline a function, check to see if we can
187 // transform it to pass arguments by value instead of by reference.
188 addPass(Passes, createArgumentPromotionPass());
190 // The IPO passes may leave cruft around. Clean up after them.
191 addPass(Passes, createInstructionCombiningPass());
193 addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
195 // Run a few AA driven optimizations here and now, to cleanup the code.
196 addPass(Passes, createGlobalsModRefPass()); // IP alias analysis
198 addPass(Passes, createLICMPass()); // Hoist loop invariants
199 addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
200 addPass(Passes, createGCSEPass()); // Remove common subexprs
201 addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
203 // Cleanup and simplify the code after the scalar optimizations.
204 addPass(Passes, createInstructionCombiningPass());
206 // Delete basic blocks, which optimization passes may have killed...
207 addPass(Passes, createCFGSimplificationPass());
209 // Now that we have optimized the program, discard unreachable functions...
210 addPass(Passes, createGlobalDCEPass());
213 // If the -s or -S command line options were specified, strip the symbols out
214 // of the resulting program to make it smaller. -s and -S are GLD options
215 // that we are supporting.
217 addPass(Passes, createStripSymbolsPass(StripLevel == 1));
219 // Make sure everything is still good.
220 Passes.add(createVerifierPass());
222 // Add the pass that writes bytecode to the output file...
223 addPass(Passes, new WriteBytecodePass(Out));
225 // Run our queue of passes all at once now, efficiently.
231 /// GenerateAssembly - generates a native assembly language source file from the
232 /// specified bytecode file.
235 /// InputFilename - The name of the output bytecode file.
236 /// OutputFilename - The name of the file to generate.
237 /// llc - The pathname to use for LLC.
239 /// Return non-zero value on error.
241 int llvm::GenerateAssembly(const std::string &OutputFilename,
242 const std::string &InputFilename,
243 const sys::Path &llc) {
244 // Run LLC to convert the bytecode file into assembly code.
245 std::vector<const char*> args;
246 args.push_back("-f");
247 args.push_back("-o");
248 args.push_back(OutputFilename.c_str());
249 args.push_back(InputFilename.c_str());
251 return sys::Program::ExecuteAndWait(llc, &args[0]);
254 /// GenerateAssembly - generates a native assembly language source file from the
255 /// specified bytecode file.
256 int llvm::GenerateCFile(const std::string &OutputFile,
257 const std::string &InputFile,
258 const sys::Path &llc ) {
259 // Run LLC to convert the bytecode file into C.
260 std::vector<const char*> args;
261 args.push_back("-march=c");
262 args.push_back("-f");
263 args.push_back("-o");
264 args.push_back(OutputFile.c_str());
265 args.push_back(InputFile.c_str());
266 return sys::Program::ExecuteAndWait(llc, &args[0]);
269 /// GenerateNative - generates a native assembly language source file from the
270 /// specified assembly source file.
273 /// InputFilename - The name of the output bytecode file.
274 /// OutputFilename - The name of the file to generate.
275 /// Libraries - The list of libraries with which to link.
276 /// gcc - The pathname to use for GGC.
277 /// envp - A copy of the process's current environment.
282 /// Returns non-zero value on error.
284 int llvm::GenerateNative(const std::string &OutputFilename,
285 const std::string &InputFilename,
286 const std::vector<std::string> &Libraries,
287 const sys::Path &gcc, char ** const envp) {
288 // Remove these environment variables from the environment of the
289 // programs that we will execute. It appears that GCC sets these
290 // environment variables so that the programs it uses can configure
291 // themselves identically.
293 // However, when we invoke GCC below, we want it to use its normal
294 // configuration. Hence, we must sanitize its environment.
295 char ** clean_env = CopyEnv(envp);
296 if (clean_env == NULL)
298 RemoveEnv("LIBRARY_PATH", clean_env);
299 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
300 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
301 RemoveEnv("COMPILER_PATH", clean_env);
302 RemoveEnv("COLLECT_GCC", clean_env);
305 // Run GCC to assemble and link the program into native code.
308 // We can't just assemble and link the file with the system assembler
309 // and linker because we don't know where to put the _start symbol.
310 // GCC mysteriously knows how to do it.
311 std::vector<const char*> args;
312 args.push_back("-fno-strict-aliasing");
313 args.push_back("-O3");
314 args.push_back("-o");
315 args.push_back(OutputFilename.c_str());
316 args.push_back(InputFilename.c_str());
318 // Add in the libraries to link.
319 for (unsigned index = 0; index < Libraries.size(); index++) {
320 if (Libraries[index] != "crtend") {
321 args.push_back("-l");
322 args.push_back(Libraries[index].c_str());
326 // Run the compiler to assembly and link together the program.
327 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);