s/lto_codegen_whole_program_optimization/lto_codegen_set_whole_program_optimization/
[oota-llvm.git] / tools / lto / LTOCodeGenerator.cpp
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 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 "LTOCodeGenerator.h"
16 #include "LTOModule.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Linker.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/system_error.h"
46 #include "llvm/ADT/StringExtras.h"
47 using namespace llvm;
48
49 static cl::opt<bool> EnableInternalizing("enable-internalizing", cl::init(false),
50   cl::desc("Internalize functions during LTO"));
51
52 static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
53   cl::desc("Do not run the inliner pass"));
54
55 static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
56   cl::desc("Do not run the GVN load PRE pass"));
57
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 #else
62   return PACKAGE_NAME " version " PACKAGE_VERSION;
63 #endif
64 }
65
66 LTOCodeGenerator::LTOCodeGenerator()
67   : _context(getGlobalContext()),
68     _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
69     _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
70     _runInternalizePass(false), _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
71     _nativeObjectFile(NULL) {
72   InitializeAllTargets();
73   InitializeAllTargetMCs();
74   InitializeAllAsmPrinters();
75 }
76
77 LTOCodeGenerator::~LTOCodeGenerator() {
78   delete _target;
79   delete _nativeObjectFile;
80
81   for (std::vector<char*>::iterator I = _codegenOptions.begin(),
82          E = _codegenOptions.end(); I != E; ++I)
83     free(*I);
84 }
85
86 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
87   bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
88
89   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
90   for (int i = 0, e = undefs.size(); i != e; ++i)
91     _asmUndefinedRefs[undefs[i]] = 1;
92
93   return ret;
94 }
95
96 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
97                                     std::string& errMsg) {
98   switch (debug) {
99   case LTO_DEBUG_MODEL_NONE:
100     _emitDwarfDebugInfo = false;
101     return false;
102
103   case LTO_DEBUG_MODEL_DWARF:
104     _emitDwarfDebugInfo = true;
105     return false;
106   }
107   llvm_unreachable("Unknown debug format!");
108 }
109
110 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
111                                        std::string& errMsg) {
112   switch (model) {
113   case LTO_CODEGEN_PIC_MODEL_STATIC:
114   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
115   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
116     _codeModel = model;
117     return false;
118   }
119   llvm_unreachable("Unknown PIC model!");
120 }
121
122 bool LTOCodeGenerator::writeMergedModules(const char *path,
123                                           std::string &errMsg) {
124   if (determineTarget(errMsg))
125     return true;
126
127   // mark which symbols can not be internalized
128   applyScopeRestrictions();
129
130   // create output file
131   std::string ErrInfo;
132   tool_output_file Out(path, ErrInfo,
133                        raw_fd_ostream::F_Binary);
134   if (!ErrInfo.empty()) {
135     errMsg = "could not open bitcode file for writing: ";
136     errMsg += path;
137     return true;
138   }
139
140   // write bitcode to it
141   WriteBitcodeToFile(_linker.getModule(), Out.os());
142   Out.os().close();
143
144   if (Out.os().has_error()) {
145     errMsg = "could not write bitcode file: ";
146     errMsg += path;
147     Out.os().clear_error();
148     return true;
149   }
150
151   Out.keep();
152   return false;
153 }
154
155 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
156   // make unique temp .o file to put generated object file
157   sys::PathWithStatus uniqueObjPath("lto-llvm.o");
158   if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
159     uniqueObjPath.eraseFromDisk();
160     return true;
161   }
162   sys::RemoveFileOnSignal(uniqueObjPath);
163
164   // generate object file
165   bool genResult = false;
166   tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
167   if (!errMsg.empty())
168     return true;
169
170   genResult = this->generateObjectFile(objFile.os(), errMsg);
171   objFile.os().close();
172   if (objFile.os().has_error()) {
173     objFile.os().clear_error();
174     return true;
175   }
176
177   objFile.keep();
178   if ( genResult ) {
179     uniqueObjPath.eraseFromDisk();
180     return true;
181   }
182
183   _nativeObjectPath = uniqueObjPath.str();
184   *name = _nativeObjectPath.c_str();
185   return false;
186 }
187
188 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
189   const char *name;
190   if (compile_to_file(&name, errMsg))
191     return NULL;
192
193   // remove old buffer if compile() called twice
194   delete _nativeObjectFile;
195
196   // read .o file into memory buffer
197   OwningPtr<MemoryBuffer> BuffPtr;
198   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
199     errMsg = ec.message();
200     return NULL;
201   }
202   _nativeObjectFile = BuffPtr.take();
203
204   // remove temp files
205   sys::Path(_nativeObjectPath).eraseFromDisk();
206
207   // return buffer, unless error
208   if ( _nativeObjectFile == NULL )
209     return NULL;
210   *length = _nativeObjectFile->getBufferSize();
211   return _nativeObjectFile->getBufferStart();
212 }
213
214 bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
215   if ( _target == NULL ) {
216     std::string Triple = _linker.getModule()->getTargetTriple();
217     if (Triple.empty())
218       Triple = sys::getDefaultTargetTriple();
219
220     // create target machine from info for merged modules
221     const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
222     if ( march == NULL )
223       return true;
224
225     // The relocation model is actually a static member of TargetMachine and
226     // needs to be set before the TargetMachine is instantiated.
227     Reloc::Model RelocModel = Reloc::Default;
228     switch( _codeModel ) {
229     case LTO_CODEGEN_PIC_MODEL_STATIC:
230       RelocModel = Reloc::Static;
231       break;
232     case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
233       RelocModel = Reloc::PIC_;
234       break;
235     case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
236       RelocModel = Reloc::DynamicNoPIC;
237       break;
238     }
239
240     // construct LTOModule, hand over ownership of module and target
241     SubtargetFeatures Features;
242     Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
243     std::string FeatureStr = Features.getString();
244     TargetOptions Options;
245     _target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
246                                          RelocModel);
247   }
248   return false;
249 }
250
251 void LTOCodeGenerator::
252 applyRestriction(GlobalValue &GV,
253                  std::vector<const char*> &mustPreserveList,
254                  SmallPtrSet<GlobalValue*, 8> &asmUsed,
255                  Mangler &mangler) {
256   SmallString<64> Buffer;
257   mangler.getNameWithPrefix(Buffer, &GV, false);
258
259   if (GV.isDeclaration())
260     return;
261   if (_mustPreserveSymbols.count(Buffer))
262     mustPreserveList.push_back(GV.getName().data());
263   if (_asmUndefinedRefs.count(Buffer))
264     asmUsed.insert(&GV);
265 }
266
267 static void findUsedValues(GlobalVariable *LLVMUsed,
268                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
269   if (LLVMUsed == 0) return;
270
271   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
272   if (Inits == 0) return;
273
274   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
275     if (GlobalValue *GV =
276         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
277       UsedValues.insert(GV);
278 }
279
280 void LTOCodeGenerator::applyScopeRestrictions() {
281   // Internalize only if specifically asked for. Otherwise, global symbols which
282   // exist in the final image, but which are used outside of that image
283   // (e.g. bundling) may be removed. This also happens when a function is used
284   // only in inline asm. LLVM doesn't recognize that as a "use", so it could be
285   // stripped.
286   if (!EnableInternalizing)
287     return;
288
289   if (_scopeRestrictionsDone) return;
290   Module *mergedModule = _linker.getModule();
291
292   // Start off with a verification pass.
293   PassManager passes;
294   passes.add(createVerifierPass());
295
296   // mark which symbols can not be internalized
297   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
298   Mangler mangler(Context, *_target->getTargetData());
299   std::vector<const char*> mustPreserveList;
300   SmallPtrSet<GlobalValue*, 8> asmUsed;
301
302   for (Module::iterator f = mergedModule->begin(),
303          e = mergedModule->end(); f != e; ++f)
304     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
305   for (Module::global_iterator v = mergedModule->global_begin(),
306          e = mergedModule->global_end(); v !=  e; ++v)
307     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
308   for (Module::alias_iterator a = mergedModule->alias_begin(),
309          e = mergedModule->alias_end(); a != e; ++a)
310     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
311
312   GlobalVariable *LLVMCompilerUsed =
313     mergedModule->getGlobalVariable("llvm.compiler.used");
314   findUsedValues(LLVMCompilerUsed, asmUsed);
315   if (LLVMCompilerUsed)
316     LLVMCompilerUsed->eraseFromParent();
317
318   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
319   std::vector<Constant*> asmUsed2;
320   for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
321          e = asmUsed.end(); i !=e; ++i) {
322     GlobalValue *GV = *i;
323     Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
324     asmUsed2.push_back(c);
325   }
326
327   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
328   LLVMCompilerUsed =
329     new llvm::GlobalVariable(*mergedModule, ATy, false,
330                              llvm::GlobalValue::AppendingLinkage,
331                              llvm::ConstantArray::get(ATy, asmUsed2),
332                              "llvm.compiler.used");
333
334   LLVMCompilerUsed->setSection("llvm.metadata");
335
336   passes.add(createInternalizePass(mustPreserveList));
337
338   // apply scope restrictions
339   passes.run(*mergedModule);
340
341   _scopeRestrictionsDone = true;
342 }
343
344 /// Optimize merged modules using various IPO passes
345 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
346                                           std::string &errMsg) {
347   if ( this->determineTarget(errMsg) )
348     return true;
349
350   // mark which symbols can not be internalized
351   this->applyScopeRestrictions();
352
353   Module* mergedModule = _linker.getModule();
354
355   // if options were requested, set them
356   if ( !_codegenOptions.empty() )
357     cl::ParseCommandLineOptions(_codegenOptions.size(),
358                                 const_cast<char **>(&_codegenOptions[0]));
359
360   // Instantiate the pass manager to organize the passes.
361   PassManager passes;
362
363   // Start off with a verification pass.
364   passes.add(createVerifierPass());
365
366   // Add an appropriate TargetData instance for this module...
367   passes.add(new TargetData(*_target->getTargetData()));
368
369   PassManagerBuilder().populateLTOPassManager(passes,
370                                               _runInternalizePass,
371                                               !DisableInline,
372                                               DisableGVNLoadPRE);
373
374   // Make sure everything is still good.
375   passes.add(createVerifierPass());
376
377   FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
378
379   codeGenPasses->add(new TargetData(*_target->getTargetData()));
380
381   formatted_raw_ostream Out(out);
382
383   if (_target->addPassesToEmitFile(*codeGenPasses, Out,
384                                    TargetMachine::CGFT_ObjectFile,
385                                    CodeGenOpt::Aggressive)) {
386     errMsg = "target file type not supported";
387     return true;
388   }
389
390   // Run our queue of passes all at once now, efficiently.
391   passes.run(*mergedModule);
392
393   // Run the code generator, and write assembly file
394   codeGenPasses->doInitialization();
395
396   for (Module::iterator
397          it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
398     if (!it->isDeclaration())
399       codeGenPasses->run(*it);
400
401   codeGenPasses->doFinalization();
402   delete codeGenPasses;
403
404   return false; // success
405 }
406
407 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
408 /// LTO problems.
409 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
410   for (std::pair<StringRef, StringRef> o = getToken(options);
411        !o.first.empty(); o = getToken(o.second)) {
412     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
413     // that.
414     if ( _codegenOptions.empty() )
415       _codegenOptions.push_back(strdup("libLTO"));
416     _codegenOptions.push_back(strdup(o.first.str().c_str()));
417   }
418 }