blob: 14cfc8efafa3dffe752acc88c9904f0f0e93fd17 [file] [log] [blame]
Devang Patela89d47f2006-08-03 15:44:57 +00001//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Devang Patel and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implementes link time optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Module.h"
16#include "llvm/PassManager.h"
17#include "llvm/Linker.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/SymbolTable.h"
21#include "llvm/Bytecode/Reader.h"
22#include "llvm/Bytecode/Writer.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FileUtilities.h"
25#include "llvm/Support/SystemUtils.h"
Devang Patel30235da2006-08-14 22:36:16 +000026#include "llvm/Support/Mangler.h"
Devang Patela89d47f2006-08-03 15:44:57 +000027#include "llvm/System/Program.h"
28#include "llvm/System/Signals.h"
29#include "llvm/Analysis/Passes.h"
30#include "llvm/Analysis/Verifier.h"
31#include "llvm/Target/SubtargetFeature.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetMachineRegistry.h"
35#include "llvm/Transforms/IPO.h"
36#include "llvm/Transforms/Scalar.h"
37#include "llvm/Analysis/LoadValueNumbering.h"
38#include "llvm/LinkTimeOptimizer.h"
39#include <fstream>
40#include <iostream>
41
42using namespace llvm;
43
44extern "C"
45llvm::LinkTimeOptimizer *createLLVMOptimizer()
46{
47 llvm::LinkTimeOptimizer *l = new llvm::LinkTimeOptimizer();
48 return l;
49}
50
51
52
53/// If symbol is not used then make it internal and let optimizer takes
54/// care of it.
55void LLVMSymbol::mayBeNotUsed() {
56 gv->setLinkage(GlobalValue::InternalLinkage);
57}
58
59// Helper routine
60// FIXME : Take advantage of GlobalPrefix from AsmPrinter
61static const char *addUnderscore(const char *name) {
62 size_t namelen = strlen(name);
63 char *symName = (char*)malloc(namelen+2);
64 symName[0] = '_';
65 strcpy(&symName[1], name);
66 return symName;
67}
68
69// Map LLVM LinkageType to LTO LinakgeType
70static LTOLinkageTypes
71getLTOLinkageType(GlobalValue *v)
72{
73 LTOLinkageTypes lt;
74 if (v->hasExternalLinkage())
75 lt = LTOExternalLinkage;
76 else if (v->hasLinkOnceLinkage())
77 lt = LTOLinkOnceLinkage;
78 else if (v->hasWeakLinkage())
79 lt = LTOWeakLinkage;
80 else
81 // Otherwise it is internal linkage for link time optimizer
82 lt = LTOInternalLinkage;
83 return lt;
84}
85
86// Find exeternal symbols referenced by VALUE. This is a recursive function.
87static void
Devang Patel30235da2006-08-14 22:36:16 +000088findExternalRefs(Value *value, std::set<std::string> &references,
Devang Patel2198f9c2006-08-14 23:37:18 +000089 Mangler &mangler) {
Devang Patel304d5f22006-08-04 19:10:26 +000090
91 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
Devang Patela89d47f2006-08-03 15:44:57 +000092 LTOLinkageTypes lt = getLTOLinkageType(gv);
93 if (lt != LTOInternalLinkage && strncmp (gv->getName().c_str(), "llvm.", 5))
Devang Patel30235da2006-08-14 22:36:16 +000094 references.insert(mangler.getValueName(gv));
Devang Patela89d47f2006-08-03 15:44:57 +000095 }
Devang Patel304d5f22006-08-04 19:10:26 +000096 else if (Constant *c = dyn_cast<Constant>(value))
97 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
98 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
Devang Patel30235da2006-08-14 22:36:16 +000099 findExternalRefs(c->getOperand(i), references, mangler);
Devang Patela89d47f2006-08-03 15:44:57 +0000100}
101
Devang Patel0701a2f2006-09-06 18:50:26 +0000102/// InputFilename is a LLVM bytecode file. If Module with InputFilename is
103/// available then return it. Otherwise parseInputFilename.
104Module *
105LinkTimeOptimizer::getModule(const std::string &InputFilename)
106{
107 Module *m = NULL;
108
109 NameToModuleMap::iterator pos = allModules.find(InputFilename.c_str());
110 if (pos != allModules.end())
111 m = allModules[InputFilename.c_str()];
112 else {
113 m = ParseBytecodeFile(InputFilename);
114 allModules[InputFilename.c_str()] = m;
115 }
116 return m;
117}
118
Devang Patela291a682006-09-06 20:16:28 +0000119/// InputFilename is a LLVM bytecode file. Reade this bytecode file and
120/// set corresponding target triplet string.
121void
122LinkTimeOptimizer::getTargetTriple(const std::string &InputFilename,
123 std::string &targetTriple)
124{
125 Module *m = getModule(InputFilename);
126 if (m)
127 targetTriple = m->getTargetTriple();
128}
129
Devang Patela89d47f2006-08-03 15:44:57 +0000130/// InputFilename is a LLVM bytecode file. Read it using bytecode reader.
131/// Collect global functions and symbol names in symbols vector.
132/// Collect external references in references vector.
133/// Return LTO_READ_SUCCESS if there is no error.
134enum LTOStatus
135LinkTimeOptimizer::readLLVMObjectFile(const std::string &InputFilename,
Devang Patel2198f9c2006-08-14 23:37:18 +0000136 NameToSymbolMap &symbols,
137 std::set<std::string> &references)
Devang Patela89d47f2006-08-03 15:44:57 +0000138{
Devang Patel0701a2f2006-09-06 18:50:26 +0000139 Module *m = getModule(InputFilename);
Devang Patela89d47f2006-08-03 15:44:57 +0000140 if (!m)
141 return LTO_READ_FAILURE;
Devang Patel30235da2006-08-14 22:36:16 +0000142
143 // Use mangler to add GlobalPrefix to names to match linker names.
144 // FIXME : Instead of hard coding "-" use GlobalPrefix.
145 Mangler mangler(*m, "_");
Devang Patela89d47f2006-08-03 15:44:57 +0000146
147 modules.push_back(m);
148
149 for (Module::iterator f = m->begin(), e = m->end(); f != e; ++f) {
150
151 LTOLinkageTypes lt = getLTOLinkageType(f);
152
153 if (!f->isExternal() && lt != LTOInternalLinkage
Devang Patel2198f9c2006-08-14 23:37:18 +0000154 && strncmp (f->getName().c_str(), "llvm.", 5)) {
Devang Patel30235da2006-08-14 22:36:16 +0000155 LLVMSymbol *newSymbol = new LLVMSymbol(lt, f, f->getName(),
Devang Patel2198f9c2006-08-14 23:37:18 +0000156 mangler.getValueName(f));
Devang Patel30235da2006-08-14 22:36:16 +0000157 symbols[newSymbol->getMangledName()] = newSymbol;
158 allSymbols[newSymbol->getMangledName()] = newSymbol;
Devang Patela89d47f2006-08-03 15:44:57 +0000159 }
Devang Patel30235da2006-08-14 22:36:16 +0000160
Devang Patela89d47f2006-08-03 15:44:57 +0000161 // Collect external symbols referenced by this function.
162 for (Function::iterator b = f->begin(), fe = f->end(); b != fe; ++b)
163 for (BasicBlock::iterator i = b->begin(), be = b->end();
Devang Patel2198f9c2006-08-14 23:37:18 +0000164 i != be; ++i)
165 for (unsigned count = 0, total = i->getNumOperands();
166 count != total; ++count)
167 findExternalRefs(i->getOperand(count), references, mangler);
Devang Patela89d47f2006-08-03 15:44:57 +0000168 }
169
170 for (Module::global_iterator v = m->global_begin(), e = m->global_end();
171 v != e; ++v) {
172 LTOLinkageTypes lt = getLTOLinkageType(v);
173 if (!v->isExternal() && lt != LTOInternalLinkage
Devang Patel2198f9c2006-08-14 23:37:18 +0000174 && strncmp (v->getName().c_str(), "llvm.", 5)) {
Devang Patel30235da2006-08-14 22:36:16 +0000175 LLVMSymbol *newSymbol = new LLVMSymbol(lt, v, v->getName(),
Devang Patel2198f9c2006-08-14 23:37:18 +0000176 mangler.getValueName(v));
Devang Patel30235da2006-08-14 22:36:16 +0000177 symbols[newSymbol->getMangledName()] = newSymbol;
Devang Pateled872862006-09-06 00:45:52 +0000178 allSymbols[newSymbol->getMangledName()] = newSymbol;
Devang Patel304d5f22006-08-04 19:10:26 +0000179
180 for (unsigned count = 0, total = v->getNumOperands();
Devang Patel2198f9c2006-08-14 23:37:18 +0000181 count != total; ++count)
182 findExternalRefs(v->getOperand(count), references, mangler);
Devang Patel304d5f22006-08-04 19:10:26 +0000183
Devang Patela89d47f2006-08-03 15:44:57 +0000184 }
185 }
186
187 return LTO_READ_SUCCESS;
188}
189
190/// Optimize module M using various IPO passes. Use exportList to
191/// internalize selected symbols. Target platform is selected
192/// based on information available to module M. No new target
193/// features are selected.
194static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
Devang Patel2198f9c2006-08-14 23:37:18 +0000195 std::vector<const char *> &exportList)
Devang Patela89d47f2006-08-03 15:44:57 +0000196{
197 // Instantiate the pass manager to organize the passes.
198 PassManager Passes;
199
200 // Collect Target info
201 std::string Err;
202 const TargetMachineRegistry::Entry* March =
203 TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err);
204
205 if (March == 0)
206 return LTO_NO_TARGET;
207
208 // Create target
209 std::string Features;
210 std::auto_ptr<TargetMachine> target(March->CtorFn(*M, Features));
211 if (!target.get())
212 return LTO_NO_TARGET;
213
214 TargetMachine &Target = *target.get();
215
216 // Start off with a verification pass.
217 Passes.add(createVerifierPass());
218
219 // Add an appropriate TargetData instance for this module...
220 Passes.add(new TargetData(*Target.getTargetData()));
221
222 // Often if the programmer does not specify proper prototypes for the
223 // functions they are calling, they end up calling a vararg version of the
224 // function that does not get a body filled in (the real function has typed
225 // arguments). This pass merges the two functions.
226 Passes.add(createFunctionResolvingPass());
227
228 // Internalize symbols if export list is nonemty
229 if (!exportList.empty())
230 Passes.add(createInternalizePass(exportList));
231
232 // Now that we internalized some globals, see if we can hack on them!
233 Passes.add(createGlobalOptimizerPass());
234
235 // Linking modules together can lead to duplicated global constants, only
236 // keep one copy of each constant...
237 Passes.add(createConstantMergePass());
238
239 // If the -s command line option was specified, strip the symbols out of the
240 // resulting program to make it smaller. -s is a GLD option that we are
241 // supporting.
242 Passes.add(createStripSymbolsPass());
243
244 // Propagate constants at call sites into the functions they call.
245 Passes.add(createIPConstantPropagationPass());
246
247 // Remove unused arguments from functions...
248 Passes.add(createDeadArgEliminationPass());
249
250 Passes.add(createFunctionInliningPass()); // Inline small functions
251
252 Passes.add(createPruneEHPass()); // Remove dead EH info
253
254 Passes.add(createGlobalDCEPass()); // Remove dead functions
255
256 // If we didn't decide to inline a function, check to see if we can
257 // transform it to pass arguments by value instead of by reference.
258 Passes.add(createArgumentPromotionPass());
259
260 // The IPO passes may leave cruft around. Clean up after them.
261 Passes.add(createInstructionCombiningPass());
262
263 Passes.add(createScalarReplAggregatesPass()); // Break up allocas
264
265 // Run a few AA driven optimizations here and now, to cleanup the code.
266 Passes.add(createGlobalsModRefPass()); // IP alias analysis
267
268 Passes.add(createLICMPass()); // Hoist loop invariants
269 Passes.add(createLoadValueNumberingPass()); // GVN for load instrs
270 Passes.add(createGCSEPass()); // Remove common subexprs
271 Passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
272
273 // Cleanup and simplify the code after the scalar optimizations.
274 Passes.add(createInstructionCombiningPass());
275
276 // Delete basic blocks, which optimization passes may have killed...
277 Passes.add(createCFGSimplificationPass());
278
279 // Now that we have optimized the program, discard unreachable functions...
280 Passes.add(createGlobalDCEPass());
281
282 // Make sure everything is still good.
283 Passes.add(createVerifierPass());
284
285 Target.addPassesToEmitFile(Passes, Out, TargetMachine::AssemblyFile, true);
286
287 // Run our queue of passes all at once now, efficiently.
288 Passes.run(*M);
289
290 return LTO_OPT_SUCCESS;
291}
292
293///Link all modules together and optimize them using IPO. Generate
294/// native object file using OutputFilename
295/// Return appropriate LTOStatus.
296enum LTOStatus
297LinkTimeOptimizer::optimizeModules(const std::string &OutputFilename,
Devang Patel26810232006-09-06 00:28:22 +0000298 std::vector<const char *> &exportList,
299 std::string &targetTriple)
Devang Patela89d47f2006-08-03 15:44:57 +0000300{
301 if (modules.empty())
302 return LTO_NO_WORK;
303
304 std::ios::openmode io_mode =
305 std::ios::out | std::ios::trunc | std::ios::binary;
306 std::string *errMsg = NULL;
307 Module *bigOne = modules[0];
308 Linker theLinker("LinkTimeOptimizer", bigOne, false);
309 for (unsigned i = 1, e = modules.size(); i != e; ++i)
310 if (theLinker.LinkModules(bigOne, modules[i], errMsg))
311 return LTO_MODULE_MERGE_FAILURE;
312
313#if 0
314 // Enable this when -save-temps is used
315 std::ofstream Out("big.bc", io_mode);
316 WriteBytecodeToFile(bigOne, Out, true);
317#endif
318
319 // Strip leading underscore because it was added to match names
Devang Patel94a0ac92006-08-03 17:25:36 +0000320 // seen by linker.
Devang Patela89d47f2006-08-03 15:44:57 +0000321 for (unsigned i = 0, e = exportList.size(); i != e; ++i) {
322 const char *name = exportList[i];
Devang Pateled872862006-09-06 00:45:52 +0000323 NameToSymbolMap::iterator itr = allSymbols.find(name);
324 if (itr != allSymbols.end())
325 exportList[i] = allSymbols[name]->getName();
Devang Patela89d47f2006-08-03 15:44:57 +0000326 }
327
328 sys::Path tmpAsmFilePath("/tmp/");
Reid Spencere5c9cb52006-08-23 00:39:35 +0000329 std::string ErrMsg;
330 if (tmpAsmFilePath.createTemporaryFileOnDisk(&ErrMsg)) {
331 std::cerr << "lto: " << ErrMsg << "\n";
Devang Patelca640122006-08-23 16:59:25 +0000332 return LTO_WRITE_FAILURE;
Reid Spencere5c9cb52006-08-23 00:39:35 +0000333 }
Devang Patela89d47f2006-08-03 15:44:57 +0000334 sys::RemoveFileOnSignal(tmpAsmFilePath);
335
336 std::ofstream asmFile(tmpAsmFilePath.c_str(), io_mode);
337 if (!asmFile.is_open() || asmFile.bad()) {
338 if (tmpAsmFilePath.exists())
339 tmpAsmFilePath.eraseFromDisk();
340 return LTO_WRITE_FAILURE;
341 }
342
343 enum LTOStatus status = lto_optimize(bigOne, asmFile, exportList);
344 asmFile.close();
345 if (status != LTO_OPT_SUCCESS) {
346 tmpAsmFilePath.eraseFromDisk();
347 return status;
348 }
349
Devang Patel26810232006-09-06 00:28:22 +0000350 targetTriple = bigOne->getTargetTriple();
351
Devang Patela89d47f2006-08-03 15:44:57 +0000352 // Run GCC to assemble and link the program into native code.
353 //
354 // Note:
355 // We can't just assemble and link the file with the system assembler
356 // and linker because we don't know where to put the _start symbol.
357 // GCC mysteriously knows how to do it.
358 const sys::Path gcc = FindExecutable("gcc", "/");
359 if (gcc.isEmpty()) {
360 tmpAsmFilePath.eraseFromDisk();
361 return LTO_ASM_FAILURE;
362 }
363
364 std::vector<const char*> args;
365 args.push_back(gcc.c_str());
366 args.push_back("-c");
367 args.push_back("-x");
368 args.push_back("assembler");
369 args.push_back("-o");
370 args.push_back(OutputFilename.c_str());
371 args.push_back(tmpAsmFilePath.c_str());
372 args.push_back(0);
373
Reid Spencer023fcf92006-08-21 02:04:43 +0000374 sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1);
Devang Patela89d47f2006-08-03 15:44:57 +0000375
376 tmpAsmFilePath.eraseFromDisk();
377
378 return LTO_OPT_SUCCESS;
379}