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