blob: 1d4c5205cffb676b1fe7ddefa6db19037b542fa8 [file] [log] [blame]
Chris Lattnera58d2be2003-09-30 03:24:28 +00001//===- GenerateCode.cpp - Functions for generating executable files ------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
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//===----------------------------------------------------------------------===//
John Criswelldc0de4f2003-09-18 16:22:26 +00009//
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
Misha Brukmanbb5a4d02003-09-30 17:33:12 +000016#include "gccld.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000017#include "llvm/System/Program.h"
John Criswelldc0de4f2003-09-18 16:22:26 +000018#include "llvm/Module.h"
19#include "llvm/PassManager.h"
Chris Lattnercc650b62003-11-09 19:55:09 +000020#include "llvm/Analysis/LoadValueNumbering.h"
Chris Lattner2d26ffb2004-07-27 08:13:15 +000021#include "llvm/Analysis/Passes.h"
Brian Gaeke1ab90d42003-11-16 23:07:28 +000022#include "llvm/Analysis/Verifier.h"
John Criswelldc0de4f2003-09-18 16:22:26 +000023#include "llvm/Bytecode/WriteBytecodePass.h"
Misha Brukmanbb5a4d02003-09-30 17:33:12 +000024#include "llvm/Target/TargetData.h"
25#include "llvm/Transforms/IPO.h"
26#include "llvm/Transforms/Scalar.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/Support/SystemUtils.h"
28#include "llvm/Support/CommandLine.h"
Reid Spencer6da1e0d2004-12-14 04:20:08 +000029
Brian Gaeked0fde302003-11-11 22:41:34 +000030using namespace llvm;
31
Chris Lattner246ce3c2003-10-24 18:09:23 +000032namespace {
33 cl::opt<bool>
34 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
Brian Gaeke1ab90d42003-11-16 23:07:28 +000035
36 cl::opt<bool>
37 Verify("verify", cl::desc("Verify intermediate results of all passes"));
38
39 cl::opt<bool>
40 DisableOptimizations("disable-opt",
41 cl::desc("Do not run any optimization passes"));
Chris Lattner246ce3c2003-10-24 18:09:23 +000042}
43
Chris Lattner0ebee742004-06-02 00:22:24 +000044/// 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.
47///
48/// Inputs:
49/// envp - An array of C strings containing an environment.
50///
51/// Return value:
52/// NULL - An error occurred.
53///
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).
57///
58static 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++)
62 /*empty*/;
63
64 // Add one more entry for the NULL pointer that ends the list.
65 ++entries;
66
67 // If there are no entries at all, just return NULL.
68 if (entries == 0)
69 return NULL;
70
71 // Allocate a new environment list.
72 char **newenv = new char* [entries];
73 if ((newenv = new char* [entries]) == NULL)
74 return NULL;
75
76 // Make a copy of the list. Don't forget the NULL that ends the list.
77 entries = 0;
78 while (envp[entries] != NULL) {
79 newenv[entries] = new char[strlen (envp[entries]) + 1];
80 strcpy (newenv[entries], envp[entries]);
81 ++entries;
82 }
83 newenv[entries] = NULL;
84
85 return newenv;
86}
87
88
89/// RemoveEnv - Remove the specified environment variable from the environment
90/// array.
91///
92/// Inputs:
93/// name - The name of the variable to remove. It cannot be NULL.
94/// envp - The array of environment variables. It cannot be NULL.
95///
96/// Notes:
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).
101///
102static 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], '=');
106 if (p == NULL)
107 continue;
108 else
109 *p = '\0';
110
111 // Compare the two strings. If they are equal, zap this string.
112 // Otherwise, restore it.
113 if (!strcmp(name, envp[index]))
114 *envp[index] = '\0';
115 else
116 *p = '=';
117 }
118
119 return;
120}
121
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000122static inline void addPass(PassManager &PM, Pass *P) {
123 // Add the pass to the pass manager...
124 PM.add(P);
125
126 // If we are verifying all of the intermediate steps, add the verifier...
127 if (Verify) PM.add(createVerifierPass());
128}
129
Misha Brukman1c534052003-09-30 17:42:57 +0000130/// GenerateBytecode - generates a bytecode file from the specified module.
131///
132/// Inputs:
133/// M - The module for which bytecode should be generated.
Chris Lattner3f14fb12004-12-02 21:26:10 +0000134/// StripLevel - 2 if we should strip all symbols, 1 if we should strip
135/// debug info.
Misha Brukman1c534052003-09-30 17:42:57 +0000136/// Internalize - Flags whether all symbols should be marked internal.
137/// Out - Pointer to file stream to which to write the output.
138///
Misha Brukman1c534052003-09-30 17:42:57 +0000139/// Returns non-zero value on error.
140///
Chris Lattner3f14fb12004-12-02 21:26:10 +0000141int llvm::GenerateBytecode(Module *M, int StripLevel, bool Internalize,
Chris Lattner27a9b272004-04-06 16:54:04 +0000142 std::ostream *Out) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000143 // In addition to just linking the input from GCC, we also want to spiff it up
144 // a little bit. Do this now.
145 PassManager Passes;
146
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000147 if (Verify) Passes.add(createVerifierPass());
148
John Criswelldc0de4f2003-09-18 16:22:26 +0000149 // Add an appropriate TargetData instance for this module...
Misha Brukman438e3642003-11-20 06:26:15 +0000150 addPass(Passes, new TargetData("gccld", M));
John Criswelldc0de4f2003-09-18 16:22:26 +0000151
Chris Lattner548e8132003-11-28 09:44:03 +0000152 // 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());
157
Chris Lattner429a9cb2004-11-16 18:59:20 +0000158 if (!DisableOptimizations) {
Chris Lattner86f42db2004-11-17 16:41:19 +0000159 if (Internalize) {
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
162 // internal.
163 addPass(Passes, createInternalizePass());
164 }
165
Chris Lattner93a00e42004-10-07 04:12:02 +0000166 // Now that we internalized some globals, see if we can hack on them!
167 addPass(Passes, createGlobalOptimizerPass());
Chris Lattnerdd429c62004-02-25 21:35:13 +0000168
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000169 // Linking modules together can lead to duplicated global constants, only
170 // keep one copy of each constant...
Misha Brukman438e3642003-11-20 06:26:15 +0000171 addPass(Passes, createConstantMergePass());
John Criswelldc0de4f2003-09-18 16:22:26 +0000172
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000173 // Propagate constants at call sites into the functions they call.
Chris Lattnerb4a400a2004-12-10 08:03:43 +0000174 addPass(Passes, createIPSCCPPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000175
176 // Remove unused arguments from functions...
Misha Brukman438e3642003-11-20 06:26:15 +0000177 addPass(Passes, createDeadArgEliminationPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000178
179 if (!DisableInline)
Misha Brukman438e3642003-11-20 06:26:15 +0000180 addPass(Passes, createFunctionInliningPass()); // Inline small functions
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000181
Chris Lattnerf9c455d2004-04-12 05:38:15 +0000182 addPass(Passes, createPruneEHPass()); // Remove dead EH info
Chris Lattnere3ef9b52004-10-11 04:47:18 +0000183 addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again.
Chris Lattnerf9c455d2004-04-12 05:38:15 +0000184 addPass(Passes, createGlobalDCEPass()); // Remove dead functions
185
Chris Lattnerf8338c42004-03-07 22:12:40 +0000186 // 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());
189
Chris Lattnerf74a4012004-02-26 03:34:30 +0000190 // The IPO passes may leave cruft around. Clean up after them.
191 addPass(Passes, createInstructionCombiningPass());
192
193 addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
194
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000195 // Run a few AA driven optimizations here and now, to cleanup the code.
Chris Lattner93127fb2004-08-02 10:10:08 +0000196 addPass(Passes, createGlobalsModRefPass()); // IP alias analysis
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000197
Misha Brukman438e3642003-11-20 06:26:15 +0000198 addPass(Passes, createLICMPass()); // Hoist loop invariants
199 addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
200 addPass(Passes, createGCSEPass()); // Remove common subexprs
Chris Lattner2d26ffb2004-07-27 08:13:15 +0000201 addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000202
Chris Lattnerf74a4012004-02-26 03:34:30 +0000203 // Cleanup and simplify the code after the scalar optimizations.
Misha Brukman438e3642003-11-20 06:26:15 +0000204 addPass(Passes, createInstructionCombiningPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000205
206 // Delete basic blocks, which optimization passes may have killed...
Misha Brukman438e3642003-11-20 06:26:15 +0000207 addPass(Passes, createCFGSimplificationPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000208
209 // Now that we have optimized the program, discard unreachable functions...
Misha Brukman438e3642003-11-20 06:26:15 +0000210 addPass(Passes, createGlobalDCEPass());
John Criswelldc0de4f2003-09-18 16:22:26 +0000211 }
212
Chris Lattner3f14fb12004-12-02 21:26:10 +0000213 // 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.
216 if (StripLevel)
217 addPass(Passes, createStripSymbolsPass(StripLevel == 1));
Chris Lattner429a9cb2004-11-16 18:59:20 +0000218
Chris Lattner0cccb182004-01-14 03:39:46 +0000219 // Make sure everything is still good.
220 Passes.add(createVerifierPass());
221
John Criswelldc0de4f2003-09-18 16:22:26 +0000222 // Add the pass that writes bytecode to the output file...
Misha Brukman438e3642003-11-20 06:26:15 +0000223 addPass(Passes, new WriteBytecodePass(Out));
John Criswelldc0de4f2003-09-18 16:22:26 +0000224
225 // Run our queue of passes all at once now, efficiently.
226 Passes.run(*M);
227
228 return 0;
229}
230
Misha Brukman1c534052003-09-30 17:42:57 +0000231/// GenerateAssembly - generates a native assembly language source file from the
232/// specified bytecode file.
233///
234/// Inputs:
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.
Misha Brukman1c534052003-09-30 17:42:57 +0000238///
Misha Brukman1c534052003-09-30 17:42:57 +0000239/// Return non-zero value on error.
240///
Chris Lattner27a9b272004-04-06 16:54:04 +0000241int llvm::GenerateAssembly(const std::string &OutputFilename,
242 const std::string &InputFilename,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000243 const sys::Path &llc) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000244 // Run LLC to convert the bytecode file into assembly code.
Reid Spencerf6358c72004-12-19 18:00:56 +0000245 std::vector<const char*> args;
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000246 args.push_back("-f");
247 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000248 args.push_back(OutputFilename.c_str());
249 args.push_back(InputFilename.c_str());
Chris Lattnered5fa582005-02-13 23:02:34 +0000250 args.push_back(0);
John Criswelldc0de4f2003-09-18 16:22:26 +0000251
Reid Spencerf6358c72004-12-19 18:00:56 +0000252 return sys::Program::ExecuteAndWait(llc, &args[0]);
John Criswelldc0de4f2003-09-18 16:22:26 +0000253}
254
Chris Lattner69e8d282004-04-06 16:43:13 +0000255/// GenerateAssembly - generates a native assembly language source file from the
256/// specified bytecode file.
Chris Lattner27a9b272004-04-06 16:54:04 +0000257int llvm::GenerateCFile(const std::string &OutputFile,
258 const std::string &InputFile,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000259 const sys::Path &llc ) {
Chris Lattner69e8d282004-04-06 16:43:13 +0000260 // Run LLC to convert the bytecode file into C.
Reid Spencerf6358c72004-12-19 18:00:56 +0000261 std::vector<const char*> args;
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000262 args.push_back("-march=c");
263 args.push_back("-f");
264 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000265 args.push_back(OutputFile.c_str());
266 args.push_back(InputFile.c_str());
Chris Lattnered5fa582005-02-13 23:02:34 +0000267 args.push_back(0);
Reid Spencerf6358c72004-12-19 18:00:56 +0000268 return sys::Program::ExecuteAndWait(llc, &args[0]);
Chris Lattner69e8d282004-04-06 16:43:13 +0000269}
270
Misha Brukman1c534052003-09-30 17:42:57 +0000271/// GenerateNative - generates a native assembly language source file from the
272/// specified assembly source file.
273///
274/// Inputs:
275/// InputFilename - The name of the output bytecode file.
276/// OutputFilename - The name of the file to generate.
277/// Libraries - The list of libraries with which to link.
Misha Brukman1c534052003-09-30 17:42:57 +0000278/// gcc - The pathname to use for GGC.
279/// envp - A copy of the process's current environment.
280///
281/// Outputs:
282/// None.
283///
284/// Returns non-zero value on error.
285///
Chris Lattner27a9b272004-04-06 16:54:04 +0000286int llvm::GenerateNative(const std::string &OutputFilename,
287 const std::string &InputFilename,
288 const std::vector<std::string> &Libraries,
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000289 const sys::Path &gcc, char ** const envp) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000290 // Remove these environment variables from the environment of the
291 // programs that we will execute. It appears that GCC sets these
292 // environment variables so that the programs it uses can configure
293 // themselves identically.
294 //
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000295 // However, when we invoke GCC below, we want it to use its normal
296 // configuration. Hence, we must sanitize its environment.
297 char ** clean_env = CopyEnv(envp);
John Criswelldc0de4f2003-09-18 16:22:26 +0000298 if (clean_env == NULL)
John Criswelldc0de4f2003-09-18 16:22:26 +0000299 return 1;
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000300 RemoveEnv("LIBRARY_PATH", clean_env);
301 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
302 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
303 RemoveEnv("COMPILER_PATH", clean_env);
304 RemoveEnv("COLLECT_GCC", clean_env);
John Criswelldc0de4f2003-09-18 16:22:26 +0000305
John Criswelldc0de4f2003-09-18 16:22:26 +0000306
John Criswelldc0de4f2003-09-18 16:22:26 +0000307 // Run GCC to assemble and link the program into native code.
308 //
309 // Note:
310 // We can't just assemble and link the file with the system assembler
311 // and linker because we don't know where to put the _start symbol.
312 // GCC mysteriously knows how to do it.
Reid Spencerf6358c72004-12-19 18:00:56 +0000313 std::vector<const char*> args;
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000314 args.push_back("-fno-strict-aliasing");
315 args.push_back("-O3");
316 args.push_back("-o");
Reid Spencerf6358c72004-12-19 18:00:56 +0000317 args.push_back(OutputFilename.c_str());
318 args.push_back(InputFilename.c_str());
John Criswell71478b72003-09-19 20:24:23 +0000319
John Criswell71478b72003-09-19 20:24:23 +0000320 // Add in the libraries to link.
Reid Spencer6da1e0d2004-12-14 04:20:08 +0000321 for (unsigned index = 0; index < Libraries.size(); index++) {
Reid Spencerf6358c72004-12-19 18:00:56 +0000322 if (Libraries[index] != "crtend") {
323 args.push_back("-l");
324 args.push_back(Libraries[index].c_str());
325 }
John Criswell71478b72003-09-19 20:24:23 +0000326 }
Chris Lattnered5fa582005-02-13 23:02:34 +0000327 args.push_back(0);
John Criswell71478b72003-09-19 20:24:23 +0000328
John Criswell71478b72003-09-19 20:24:23 +0000329 // Run the compiler to assembly and link together the program.
Reid Spencerf6358c72004-12-19 18:00:56 +0000330 return sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
John Criswelldc0de4f2003-09-18 16:22:26 +0000331}
Chris Lattner0ebee742004-06-02 00:22:24 +0000332