blob: 74576bb1ba38732e1f1248c457f2b5ebadccc3b5 [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"
John Criswelldc0de4f2003-09-18 16:22:26 +000017#include "llvm/Module.h"
18#include "llvm/PassManager.h"
Chris Lattnercc650b62003-11-09 19:55:09 +000019#include "llvm/Analysis/LoadValueNumbering.h"
Chris Lattner2d26ffb2004-07-27 08:13:15 +000020#include "llvm/Analysis/Passes.h"
Brian Gaeke1ab90d42003-11-16 23:07:28 +000021#include "llvm/Analysis/Verifier.h"
John Criswelldc0de4f2003-09-18 16:22:26 +000022#include "llvm/Bytecode/WriteBytecodePass.h"
Misha Brukmanbb5a4d02003-09-30 17:33:12 +000023#include "llvm/Target/TargetData.h"
24#include "llvm/Transforms/IPO.h"
25#include "llvm/Transforms/Scalar.h"
Misha Brukman008248f2004-06-23 17:33:09 +000026#include "llvm/Support/Linker.h"
John Criswelldc0de4f2003-09-18 16:22:26 +000027#include "Support/SystemUtils.h"
Chris Lattner246ce3c2003-10-24 18:09:23 +000028#include "Support/CommandLine.h"
Brian Gaeked0fde302003-11-11 22:41:34 +000029using namespace llvm;
30
Chris Lattner246ce3c2003-10-24 18:09:23 +000031namespace {
32 cl::opt<bool>
33 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
Brian Gaeke1ab90d42003-11-16 23:07:28 +000034
35 cl::opt<bool>
36 Verify("verify", cl::desc("Verify intermediate results of all passes"));
37
38 cl::opt<bool>
39 DisableOptimizations("disable-opt",
40 cl::desc("Do not run any optimization passes"));
Chris Lattner2d26ffb2004-07-27 08:13:15 +000041 cl::opt<bool>
42 DisableGlobalsModRef("disable-globalsmodref", cl::Hidden,
43 cl::desc("Turn on the more aggressive alias analysis"));
Chris Lattner246ce3c2003-10-24 18:09:23 +000044}
45
Chris Lattner0ebee742004-06-02 00:22:24 +000046/// CopyEnv - This function takes an array of environment variables and makes a
47/// copy of it. This copy can then be manipulated any way the caller likes
48/// without affecting the process's real environment.
49///
50/// Inputs:
51/// envp - An array of C strings containing an environment.
52///
53/// Return value:
54/// NULL - An error occurred.
55///
56/// Otherwise, a pointer to a new array of C strings is returned. Every string
57/// in the array is a duplicate of the one in the original array (i.e. we do
58/// not copy the char *'s from one array to another).
59///
60static char ** CopyEnv(char ** const envp) {
61 // Count the number of entries in the old list;
62 unsigned entries; // The number of entries in the old environment list
63 for (entries = 0; envp[entries] != NULL; entries++)
64 /*empty*/;
65
66 // Add one more entry for the NULL pointer that ends the list.
67 ++entries;
68
69 // If there are no entries at all, just return NULL.
70 if (entries == 0)
71 return NULL;
72
73 // Allocate a new environment list.
74 char **newenv = new char* [entries];
75 if ((newenv = new char* [entries]) == NULL)
76 return NULL;
77
78 // Make a copy of the list. Don't forget the NULL that ends the list.
79 entries = 0;
80 while (envp[entries] != NULL) {
81 newenv[entries] = new char[strlen (envp[entries]) + 1];
82 strcpy (newenv[entries], envp[entries]);
83 ++entries;
84 }
85 newenv[entries] = NULL;
86
87 return newenv;
88}
89
90
91/// RemoveEnv - Remove the specified environment variable from the environment
92/// array.
93///
94/// Inputs:
95/// name - The name of the variable to remove. It cannot be NULL.
96/// envp - The array of environment variables. It cannot be NULL.
97///
98/// Notes:
99/// This is mainly done because functions to remove items from the environment
100/// are not available across all platforms. In particular, Solaris does not
101/// seem to have an unsetenv() function or a setenv() function (or they are
102/// undocumented if they do exist).
103///
104static void RemoveEnv(const char * name, char ** const envp) {
105 for (unsigned index=0; envp[index] != NULL; index++) {
106 // Find the first equals sign in the array and make it an EOS character.
107 char *p = strchr (envp[index], '=');
108 if (p == NULL)
109 continue;
110 else
111 *p = '\0';
112
113 // Compare the two strings. If they are equal, zap this string.
114 // Otherwise, restore it.
115 if (!strcmp(name, envp[index]))
116 *envp[index] = '\0';
117 else
118 *p = '=';
119 }
120
121 return;
122}
123
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000124static inline void addPass(PassManager &PM, Pass *P) {
125 // Add the pass to the pass manager...
126 PM.add(P);
127
128 // If we are verifying all of the intermediate steps, add the verifier...
129 if (Verify) PM.add(createVerifierPass());
130}
131
Misha Brukman1c534052003-09-30 17:42:57 +0000132/// GenerateBytecode - generates a bytecode file from the specified module.
133///
134/// Inputs:
135/// M - The module for which bytecode should be generated.
136/// Strip - Flags whether symbols should be stripped from the output.
137/// Internalize - Flags whether all symbols should be marked internal.
138/// Out - Pointer to file stream to which to write the output.
139///
Misha Brukman1c534052003-09-30 17:42:57 +0000140/// Returns non-zero value on error.
141///
Chris Lattner27a9b272004-04-06 16:54:04 +0000142int llvm::GenerateBytecode(Module *M, bool Strip, bool Internalize,
143 std::ostream *Out) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000144 // In addition to just linking the input from GCC, we also want to spiff it up
145 // a little bit. Do this now.
146 PassManager Passes;
147
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000148 if (Verify) Passes.add(createVerifierPass());
149
John Criswelldc0de4f2003-09-18 16:22:26 +0000150 // Add an appropriate TargetData instance for this module...
Misha Brukman438e3642003-11-20 06:26:15 +0000151 addPass(Passes, new TargetData("gccld", M));
John Criswelldc0de4f2003-09-18 16:22:26 +0000152
Chris Lattner548e8132003-11-28 09:44:03 +0000153 // Often if the programmer does not specify proper prototypes for the
154 // functions they are calling, they end up calling a vararg version of the
155 // function that does not get a body filled in (the real function has typed
156 // arguments). This pass merges the two functions.
157 addPass(Passes, createFunctionResolvingPass());
158
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000159 if (!DisableOptimizations) {
Chris Lattnerdd429c62004-02-25 21:35:13 +0000160 if (Internalize) {
161 // Now that composite has been compiled, scan through the module, looking
162 // for a main function. If main is defined, mark all other functions
163 // internal.
164 addPass(Passes, createInternalizePass());
165 }
166
167 // Now that we internalized some globals, see if we can mark any globals as
168 // being constant!
169 addPass(Passes, createGlobalConstifierPass());
170
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000171 // Linking modules together can lead to duplicated global constants, only
172 // keep one copy of each constant...
Misha Brukman438e3642003-11-20 06:26:15 +0000173 addPass(Passes, createConstantMergePass());
John Criswelldc0de4f2003-09-18 16:22:26 +0000174
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000175 // If the -s command line option was specified, strip the symbols out of the
176 // resulting program to make it smaller. -s is a GCC option that we are
177 // supporting.
178 if (Strip)
Misha Brukman438e3642003-11-20 06:26:15 +0000179 addPass(Passes, createSymbolStrippingPass());
John Criswelldc0de4f2003-09-18 16:22:26 +0000180
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000181 // Propagate constants at call sites into the functions they call.
Misha Brukman438e3642003-11-20 06:26:15 +0000182 addPass(Passes, createIPConstantPropagationPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000183
184 // Remove unused arguments from functions...
Misha Brukman438e3642003-11-20 06:26:15 +0000185 addPass(Passes, createDeadArgEliminationPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000186
187 if (!DisableInline)
Misha Brukman438e3642003-11-20 06:26:15 +0000188 addPass(Passes, createFunctionInliningPass()); // Inline small functions
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000189
Chris Lattnerf9c455d2004-04-12 05:38:15 +0000190 addPass(Passes, createPruneEHPass()); // Remove dead EH info
191 addPass(Passes, createGlobalDCEPass()); // Remove dead functions
192
Chris Lattnerf8338c42004-03-07 22:12:40 +0000193 // If we didn't decide to inline a function, check to see if we can
194 // transform it to pass arguments by value instead of by reference.
195 addPass(Passes, createArgumentPromotionPass());
196
Chris Lattnerf74a4012004-02-26 03:34:30 +0000197 // The IPO passes may leave cruft around. Clean up after them.
198 addPass(Passes, createInstructionCombiningPass());
199
200 addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
201
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000202 // Run a few AA driven optimizations here and now, to cleanup the code.
Chris Lattner2d26ffb2004-07-27 08:13:15 +0000203 if (!DisableGlobalsModRef)
204 addPass(Passes, createGlobalsModRefPass()); // IP alias analysis
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000205
Misha Brukman438e3642003-11-20 06:26:15 +0000206 addPass(Passes, createLICMPass()); // Hoist loop invariants
207 addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs
208 addPass(Passes, createGCSEPass()); // Remove common subexprs
Chris Lattner2d26ffb2004-07-27 08:13:15 +0000209 addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000210
Chris Lattnerf74a4012004-02-26 03:34:30 +0000211 // Cleanup and simplify the code after the scalar optimizations.
Misha Brukman438e3642003-11-20 06:26:15 +0000212 addPass(Passes, createInstructionCombiningPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000213
214 // Delete basic blocks, which optimization passes may have killed...
Misha Brukman438e3642003-11-20 06:26:15 +0000215 addPass(Passes, createCFGSimplificationPass());
Brian Gaeke1ab90d42003-11-16 23:07:28 +0000216
217 // Now that we have optimized the program, discard unreachable functions...
Misha Brukman438e3642003-11-20 06:26:15 +0000218 addPass(Passes, createGlobalDCEPass());
John Criswelldc0de4f2003-09-18 16:22:26 +0000219 }
220
Chris Lattner0cccb182004-01-14 03:39:46 +0000221 // Make sure everything is still good.
222 Passes.add(createVerifierPass());
223
John Criswelldc0de4f2003-09-18 16:22:26 +0000224 // Add the pass that writes bytecode to the output file...
Misha Brukman438e3642003-11-20 06:26:15 +0000225 addPass(Passes, new WriteBytecodePass(Out));
John Criswelldc0de4f2003-09-18 16:22:26 +0000226
227 // Run our queue of passes all at once now, efficiently.
228 Passes.run(*M);
229
230 return 0;
231}
232
Misha Brukman1c534052003-09-30 17:42:57 +0000233/// GenerateAssembly - generates a native assembly language source file from the
234/// specified bytecode file.
235///
236/// Inputs:
237/// InputFilename - The name of the output bytecode file.
238/// OutputFilename - The name of the file to generate.
239/// llc - The pathname to use for LLC.
240/// envp - The environment to use when running LLC.
241///
Misha Brukman1c534052003-09-30 17:42:57 +0000242/// Return non-zero value on error.
243///
Chris Lattner27a9b272004-04-06 16:54:04 +0000244int llvm::GenerateAssembly(const std::string &OutputFilename,
245 const std::string &InputFilename,
246 const std::string &llc,
247 char ** const envp) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000248 // Run LLC to convert the bytecode file into assembly code.
Chris Lattner27a9b272004-04-06 16:54:04 +0000249 const char *cmd[6];
Misha Brukmanb6b28432003-09-30 17:40:12 +0000250 cmd[0] = llc.c_str();
251 cmd[1] = "-f";
252 cmd[2] = "-o";
253 cmd[3] = OutputFilename.c_str();
254 cmd[4] = InputFilename.c_str();
Chris Lattner27a9b272004-04-06 16:54:04 +0000255 cmd[5] = 0;
John Criswelldc0de4f2003-09-18 16:22:26 +0000256
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000257 return ExecWait(cmd, envp);
John Criswelldc0de4f2003-09-18 16:22:26 +0000258}
259
Chris Lattner69e8d282004-04-06 16:43:13 +0000260/// GenerateAssembly - generates a native assembly language source file from the
261/// specified bytecode file.
Chris Lattner27a9b272004-04-06 16:54:04 +0000262int llvm::GenerateCFile(const std::string &OutputFile,
263 const std::string &InputFile,
264 const std::string &llc, char ** const envp) {
Chris Lattner69e8d282004-04-06 16:43:13 +0000265 // Run LLC to convert the bytecode file into C.
Chris Lattner67e0a342004-04-08 15:18:03 +0000266 const char *cmd[7];
Chris Lattner69e8d282004-04-06 16:43:13 +0000267
268 cmd[0] = llc.c_str();
269 cmd[1] = "-march=c";
270 cmd[2] = "-f";
Chris Lattner67e0a342004-04-08 15:18:03 +0000271 cmd[3] = "-o";
272 cmd[4] = OutputFile.c_str();
273 cmd[5] = InputFile.c_str();
274 cmd[6] = 0;
Chris Lattner69e8d282004-04-06 16:43:13 +0000275 return ExecWait(cmd, envp);
276}
277
Misha Brukman1c534052003-09-30 17:42:57 +0000278/// GenerateNative - generates a native assembly language source file from the
279/// specified assembly source file.
280///
281/// Inputs:
282/// InputFilename - The name of the output bytecode file.
283/// OutputFilename - The name of the file to generate.
284/// Libraries - The list of libraries with which to link.
285/// LibPaths - The list of directories in which to find libraries.
286/// gcc - The pathname to use for GGC.
287/// envp - A copy of the process's current environment.
288///
289/// Outputs:
290/// None.
291///
292/// Returns non-zero value on error.
293///
Chris Lattner27a9b272004-04-06 16:54:04 +0000294int llvm::GenerateNative(const std::string &OutputFilename,
295 const std::string &InputFilename,
296 const std::vector<std::string> &Libraries,
297 const std::vector<std::string> &LibPaths,
298 const std::string &gcc, char ** const envp) {
John Criswelldc0de4f2003-09-18 16:22:26 +0000299 // Remove these environment variables from the environment of the
300 // programs that we will execute. It appears that GCC sets these
301 // environment variables so that the programs it uses can configure
302 // themselves identically.
303 //
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000304 // However, when we invoke GCC below, we want it to use its normal
305 // configuration. Hence, we must sanitize its environment.
306 char ** clean_env = CopyEnv(envp);
John Criswelldc0de4f2003-09-18 16:22:26 +0000307 if (clean_env == NULL)
John Criswelldc0de4f2003-09-18 16:22:26 +0000308 return 1;
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000309 RemoveEnv("LIBRARY_PATH", clean_env);
310 RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
311 RemoveEnv("GCC_EXEC_PREFIX", clean_env);
312 RemoveEnv("COMPILER_PATH", clean_env);
313 RemoveEnv("COLLECT_GCC", clean_env);
John Criswelldc0de4f2003-09-18 16:22:26 +0000314
John Criswell71478b72003-09-19 20:24:23 +0000315 std::vector<const char *> cmd;
John Criswelldc0de4f2003-09-18 16:22:26 +0000316
John Criswelldc0de4f2003-09-18 16:22:26 +0000317 // Run GCC to assemble and link the program into native code.
318 //
319 // Note:
320 // We can't just assemble and link the file with the system assembler
321 // and linker because we don't know where to put the _start symbol.
322 // GCC mysteriously knows how to do it.
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000323 cmd.push_back(gcc.c_str());
Chris Lattnera1346a22004-04-08 15:18:59 +0000324 cmd.push_back("-fno-strict-aliasing");
Chris Lattner69e8d282004-04-06 16:43:13 +0000325 cmd.push_back("-O3");
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000326 cmd.push_back("-o");
327 cmd.push_back(OutputFilename.c_str());
328 cmd.push_back(InputFilename.c_str());
John Criswelldc0de4f2003-09-18 16:22:26 +0000329
Misha Brukmanb6b28432003-09-30 17:40:12 +0000330 // Adding the library paths creates a problem for native generation. If we
331 // include the search paths from llvmgcc, then we'll be telling normal gcc
332 // to look inside of llvmgcc's library directories for libraries. This is
333 // bad because those libraries hold only bytecode files (not native object
334 // files). In the end, we attempt to link the bytecode libgcc into a native
335 // program.
Chris Lattner238cf3c2003-09-30 17:36:51 +0000336#if 0
John Criswell71478b72003-09-19 20:24:23 +0000337 // Add in the library path options.
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000338 for (unsigned index=0; index < LibPaths.size(); index++) {
339 cmd.push_back("-L");
340 cmd.push_back(LibPaths[index].c_str());
John Criswell71478b72003-09-19 20:24:23 +0000341 }
342#endif
343
John Criswell71478b72003-09-19 20:24:23 +0000344 // Add in the libraries to link.
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000345 std::vector<std::string> Libs(Libraries);
346 for (unsigned index = 0; index < Libs.size(); index++) {
John Criswell6f5592a2004-01-26 23:51:10 +0000347 if (Libs[index] != "crtend") {
348 Libs[index] = "-l" + Libs[index];
349 cmd.push_back(Libs[index].c_str());
350 }
John Criswell71478b72003-09-19 20:24:23 +0000351 }
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000352 cmd.push_back(NULL);
John Criswell71478b72003-09-19 20:24:23 +0000353
John Criswell71478b72003-09-19 20:24:23 +0000354 // Run the compiler to assembly and link together the program.
Misha Brukmanbb5a4d02003-09-30 17:33:12 +0000355 return ExecWait(&(cmd[0]), clean_env);
John Criswelldc0de4f2003-09-18 16:22:26 +0000356}
Chris Lattner0ebee742004-06-02 00:22:24 +0000357