lto.cpp revision 3f0e5e205772af1529d980cb1fb2c910ef38417c
1//===-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"
26#include "llvm/Support/Mangler.h"
27#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::LTO *l = new llvm::LTO();
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
88findExternalRefs(Value *value, std::set<std::string> &references,
89                 Mangler &mangler) {
90
91  if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
92    LTOLinkageTypes lt = getLTOLinkageType(gv);
93    if (lt != LTOInternalLinkage && strncmp (gv->getName().c_str(), "llvm.", 5))
94      references.insert(mangler.getValueName(gv));
95  }
96
97  // GlobalValue, even with InternalLinkage type, may have operands with
98  // ExternalLinkage type. Do not ignore these operands.
99  if (Constant *c = dyn_cast<Constant>(value))
100    // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
101    for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
102      findExternalRefs(c->getOperand(i), references, mangler);
103}
104
105/// InputFilename is a LLVM bytecode file. If Module with InputFilename is
106/// available then return it. Otherwise parseInputFilename.
107Module *
108LTO::getModule(const std::string &InputFilename)
109{
110  Module *m = NULL;
111
112  NameToModuleMap::iterator pos = allModules.find(InputFilename.c_str());
113  if (pos != allModules.end())
114    m = allModules[InputFilename.c_str()];
115  else {
116    m = ParseBytecodeFile(InputFilename);
117    allModules[InputFilename.c_str()] = m;
118  }
119  return m;
120}
121
122/// InputFilename is a LLVM bytecode file. Reade this bytecode file and
123/// set corresponding target triplet string.
124void
125LTO::getTargetTriple(const std::string &InputFilename,
126				   std::string &targetTriple)
127{
128  Module *m = getModule(InputFilename);
129  if (m)
130    targetTriple = m->getTargetTriple();
131}
132
133/// InputFilename is a LLVM bytecode file. Read it using bytecode reader.
134/// Collect global functions and symbol names in symbols vector.
135/// Collect external references in references vector.
136/// Return LTO_READ_SUCCESS if there is no error.
137enum LTOStatus
138LTO::readLLVMObjectFile(const std::string &InputFilename,
139                                      NameToSymbolMap &symbols,
140                                      std::set<std::string> &references)
141{
142  Module *m = getModule(InputFilename);
143  if (!m)
144    return LTO_READ_FAILURE;
145
146  // Use mangler to add GlobalPrefix to names to match linker names.
147  // FIXME : Instead of hard coding "-" use GlobalPrefix.
148  Mangler mangler(*m, "_");
149
150  modules.push_back(m);
151
152  for (Module::iterator f = m->begin(), e = m->end(); f != e; ++f) {
153
154    LTOLinkageTypes lt = getLTOLinkageType(f);
155
156    if (!f->isExternal() && lt != LTOInternalLinkage
157        && strncmp (f->getName().c_str(), "llvm.", 5)) {
158      LLVMSymbol *newSymbol = new LLVMSymbol(lt, f, f->getName(),
159                                             mangler.getValueName(f));
160      symbols[newSymbol->getMangledName()] = newSymbol;
161      allSymbols[newSymbol->getMangledName()] = newSymbol;
162    }
163
164    // Collect external symbols referenced by this function.
165    for (Function::iterator b = f->begin(), fe = f->end(); b != fe; ++b)
166      for (BasicBlock::iterator i = b->begin(), be = b->end();
167           i != be; ++i)
168        for (unsigned count = 0, total = i->getNumOperands();
169             count != total; ++count)
170          findExternalRefs(i->getOperand(count), references, mangler);
171  }
172
173  for (Module::global_iterator v = m->global_begin(), e = m->global_end();
174       v !=  e; ++v) {
175    LTOLinkageTypes lt = getLTOLinkageType(v);
176    if (!v->isExternal() && lt != LTOInternalLinkage
177        && strncmp (v->getName().c_str(), "llvm.", 5)) {
178      LLVMSymbol *newSymbol = new LLVMSymbol(lt, v, v->getName(),
179                                             mangler.getValueName(v));
180      symbols[newSymbol->getMangledName()] = newSymbol;
181      allSymbols[newSymbol->getMangledName()] = newSymbol;
182
183      for (unsigned count = 0, total = v->getNumOperands();
184           count != total; ++count)
185        findExternalRefs(v->getOperand(count), references, mangler);
186
187    }
188  }
189
190  return LTO_READ_SUCCESS;
191}
192
193/// Optimize module M using various IPO passes. Use exportList to
194/// internalize selected symbols. Target platform is selected
195/// based on information available to module M. No new target
196/// features are selected.
197static enum LTOStatus lto_optimize(Module *M, std::ostream &Out,
198                                   std::vector<const char *> &exportList)
199{
200  // Instantiate the pass manager to organize the passes.
201  PassManager Passes;
202
203  // Collect Target info
204  std::string Err;
205  const TargetMachineRegistry::Entry* March =
206    TargetMachineRegistry::getClosestStaticTargetForModule(*M, Err);
207
208  if (March == 0)
209    return LTO_NO_TARGET;
210
211  // Create target
212  std::string Features;
213  std::auto_ptr<TargetMachine> target(March->CtorFn(*M, Features));
214  if (!target.get())
215    return LTO_NO_TARGET;
216
217  TargetMachine &Target = *target.get();
218
219  // Start off with a verification pass.
220  Passes.add(createVerifierPass());
221
222  // Add an appropriate TargetData instance for this module...
223  Passes.add(new TargetData(*Target.getTargetData()));
224
225  // Often if the programmer does not specify proper prototypes for the
226  // functions they are calling, they end up calling a vararg version of the
227  // function that does not get a body filled in (the real function has typed
228  // arguments).  This pass merges the two functions.
229  Passes.add(createFunctionResolvingPass());
230
231  // Internalize symbols if export list is nonemty
232  if (!exportList.empty())
233    Passes.add(createInternalizePass(exportList));
234
235  // Now that we internalized some globals, see if we can hack on them!
236  Passes.add(createGlobalOptimizerPass());
237
238  // Linking modules together can lead to duplicated global constants, only
239  // keep one copy of each constant...
240  Passes.add(createConstantMergePass());
241
242  // If the -s command line option was specified, strip the symbols out of the
243  // resulting program to make it smaller.  -s is a GLD option that we are
244  // supporting.
245  Passes.add(createStripSymbolsPass());
246
247  // Propagate constants at call sites into the functions they call.
248  Passes.add(createIPConstantPropagationPass());
249
250  // Remove unused arguments from functions...
251  Passes.add(createDeadArgEliminationPass());
252
253  Passes.add(createFunctionInliningPass()); // Inline small functions
254
255  Passes.add(createPruneEHPass());            // Remove dead EH info
256
257  Passes.add(createGlobalDCEPass());          // Remove dead functions
258
259  // If we didn't decide to inline a function, check to see if we can
260  // transform it to pass arguments by value instead of by reference.
261  Passes.add(createArgumentPromotionPass());
262
263  // The IPO passes may leave cruft around.  Clean up after them.
264  Passes.add(createInstructionCombiningPass());
265
266  Passes.add(createScalarReplAggregatesPass()); // Break up allocas
267
268  // Run a few AA driven optimizations here and now, to cleanup the code.
269  Passes.add(createGlobalsModRefPass());      // IP alias analysis
270
271  Passes.add(createLICMPass());               // Hoist loop invariants
272  Passes.add(createLoadValueNumberingPass()); // GVN for load instrs
273  Passes.add(createGCSEPass());               // Remove common subexprs
274  Passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
275
276  // Cleanup and simplify the code after the scalar optimizations.
277  Passes.add(createInstructionCombiningPass());
278
279  // Delete basic blocks, which optimization passes may have killed...
280  Passes.add(createCFGSimplificationPass());
281
282  // Now that we have optimized the program, discard unreachable functions...
283  Passes.add(createGlobalDCEPass());
284
285  // Make sure everything is still good.
286  Passes.add(createVerifierPass());
287
288  FunctionPassManager *CodeGenPasses =
289    new FunctionPassManager(new ExistingModuleProvider(M));
290
291  CodeGenPasses->add(new TargetData(*Target.getTargetData()));
292  Target.addPassesToEmitFile(*CodeGenPasses, Out, TargetMachine::AssemblyFile,
293			     true);
294
295  // Run our queue of passes all at once now, efficiently.
296  Passes.run(*M);
297
298  // Run the code generator, if present.
299  CodeGenPasses->doInitialization();
300  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
301    if (!I->isExternal())
302      CodeGenPasses->run(*I);
303  }
304  CodeGenPasses->doFinalization();
305
306  return LTO_OPT_SUCCESS;
307}
308
309///Link all modules together and optimize them using IPO. Generate
310/// native object file using OutputFilename
311/// Return appropriate LTOStatus.
312enum LTOStatus
313LTO::optimizeModules(const std::string &OutputFilename,
314                                   std::vector<const char *> &exportList,
315                                   std::string &targetTriple)
316{
317  if (modules.empty())
318    return LTO_NO_WORK;
319
320  std::ios::openmode io_mode =
321    std::ios::out | std::ios::trunc | std::ios::binary;
322  std::string *errMsg = NULL;
323  Module *bigOne = modules[0];
324  Linker theLinker("LinkTimeOptimizer", bigOne, false);
325  for (unsigned i = 1, e = modules.size(); i != e; ++i)
326    if (theLinker.LinkModules(bigOne, modules[i], errMsg))
327      return LTO_MODULE_MERGE_FAILURE;
328
329#if 0
330  // Enable this when -save-temps is used
331  std::ofstream Out("big.bc", io_mode);
332  WriteBytecodeToFile(bigOne, Out, true);
333#endif
334
335  // Strip leading underscore because it was added to match names
336  // seen by linker.
337  for (unsigned i = 0, e = exportList.size(); i != e; ++i) {
338    const char *name = exportList[i];
339    NameToSymbolMap::iterator itr = allSymbols.find(name);
340    if (itr != allSymbols.end())
341      exportList[i] = allSymbols[name]->getName();
342  }
343
344
345  std::string ErrMsg;
346  sys::Path TempDir = sys::Path::GetTemporaryDirectory(&ErrMsg);
347  sys::Path tmpAsmFilePath(TempDir);
348  if (!tmpAsmFilePath.appendComponent("lto")) {
349    std::cerr << "lto: " << ErrMsg << "\n";
350    TempDir.eraseFromDisk(true);
351    return LTO_WRITE_FAILURE;
352  }
353  if (tmpAsmFilePath.createTemporaryFileOnDisk(&ErrMsg)) {
354    std::cerr << "lto: " << ErrMsg << "\n";
355    TempDir.eraseFromDisk(true);
356    return LTO_WRITE_FAILURE;
357  }
358  sys::RemoveFileOnSignal(tmpAsmFilePath);
359
360  std::ofstream asmFile(tmpAsmFilePath.c_str(), io_mode);
361  if (!asmFile.is_open() || asmFile.bad()) {
362    if (tmpAsmFilePath.exists()) {
363      tmpAsmFilePath.eraseFromDisk();
364      TempDir.eraseFromDisk(true);
365    }
366    return LTO_WRITE_FAILURE;
367  }
368
369  enum LTOStatus status = lto_optimize(bigOne, asmFile, exportList);
370  asmFile.close();
371  if (status != LTO_OPT_SUCCESS) {
372    tmpAsmFilePath.eraseFromDisk();
373    TempDir.eraseFromDisk(true);
374    return status;
375  }
376
377  targetTriple = bigOne->getTargetTriple();
378
379  // Run GCC to assemble and link the program into native code.
380  //
381  // Note:
382  //  We can't just assemble and link the file with the system assembler
383  //  and linker because we don't know where to put the _start symbol.
384  //  GCC mysteriously knows how to do it.
385  const sys::Path gcc = FindExecutable("gcc", "/");
386  if (gcc.isEmpty()) {
387    tmpAsmFilePath.eraseFromDisk();
388    TempDir.eraseFromDisk(true);
389    return LTO_ASM_FAILURE;
390  }
391
392  std::vector<const char*> args;
393  args.push_back(gcc.c_str());
394  args.push_back("-c");
395  args.push_back("-x");
396  args.push_back("assembler");
397  args.push_back("-o");
398  args.push_back(OutputFilename.c_str());
399  args.push_back(tmpAsmFilePath.c_str());
400  args.push_back(0);
401
402  sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 1);
403
404  tmpAsmFilePath.eraseFromDisk();
405  TempDir.eraseFromDisk(true);
406
407  return LTO_OPT_SUCCESS;
408}
409