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