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