1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.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"
56 static cl::opt<bool> DisableInline("disable-inlining",
57 cl::desc("Do not run the inliner pass"));
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63 return PACKAGE_NAME " version " PACKAGE_VERSION;
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)
74 InitializeAllTargets();
75 InitializeAllTargetMCs();
76 InitializeAllAsmPrinters();
79 LTOCodeGenerator::~LTOCodeGenerator() {
81 delete _nativeObjectFile;
83 for (std::vector<const char*>::iterator I = _codegenOptions.begin(),
84 E = _codegenOptions.end(); I != E; ++I)
88 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
90 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
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;
100 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
103 case LTO_DEBUG_MODEL_NONE:
104 _emitDwarfDebugInfo = false;
107 case LTO_DEBUG_MODEL_DWARF:
108 _emitDwarfDebugInfo = true;
111 llvm_unreachable("Unknown debug format!");
115 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
119 case LTO_CODEGEN_PIC_MODEL_STATIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
125 llvm_unreachable("Unknown PIC model!");
128 void LTOCodeGenerator::setCpu(const char* mCpu)
133 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
135 _mustPreserveSymbols[sym] = 1;
139 bool LTOCodeGenerator::writeMergedModules(const char *path,
140 std::string &errMsg) {
141 if (determineTarget(errMsg))
144 // mark which symbols can not be internalized
145 applyScopeRestrictions();
147 // create output file
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: ";
157 // write bitcode to it
158 WriteBitcodeToFile(_linker.getModule(), Out.os());
161 if (Out.os().has_error()) {
162 errMsg = "could not write bitcode file: ";
164 Out.os().clear_error();
173 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg)
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();
181 sys::RemoveFileOnSignal(uniqueObjPath);
183 // generate object file
184 bool genResult = false;
185 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
188 genResult = this->generateObjectFile(objFile.os(), errMsg);
189 objFile.os().close();
190 if (objFile.os().has_error()) {
191 objFile.os().clear_error();
196 uniqueObjPath.eraseFromDisk();
200 _nativeObjectPath = uniqueObjPath.str();
201 *name = _nativeObjectPath.c_str();
205 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
208 if (compile_to_file(&name, errMsg))
211 // remove old buffer if compile() called twice
212 delete _nativeObjectFile;
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();
220 _nativeObjectFile = BuffPtr.take();
223 sys::Path(_nativeObjectPath).eraseFromDisk();
225 // return buffer, unless error
226 if ( _nativeObjectFile == NULL )
228 *length = _nativeObjectFile->getBufferSize();
229 return _nativeObjectFile->getBufferStart();
232 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
234 if ( _target == NULL ) {
235 std::string Triple = _linker.getModule()->getTargetTriple();
237 Triple = sys::getDefaultTargetTriple();
239 // create target machine from info for merged modules
240 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
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;
251 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
252 RelocModel = Reloc::PIC_;
254 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
255 RelocModel = Reloc::DynamicNoPIC;
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,
270 void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
271 std::vector<const char*> &mustPreserveList,
272 SmallPtrSet<GlobalValue*, 8> &asmUsed,
274 SmallString<64> Buffer;
275 mangler.getNameWithPrefix(Buffer, &GV, false);
277 if (GV.isDeclaration())
279 if (_mustPreserveSymbols.count(Buffer))
280 mustPreserveList.push_back(GV.getName().data());
281 if (_asmUndefinedRefs.count(Buffer))
285 static void findUsedValues(GlobalVariable *LLVMUsed,
286 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
287 if (LLVMUsed == 0) return;
289 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
290 if (Inits == 0) return;
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);
298 void LTOCodeGenerator::applyScopeRestrictions() {
299 if (_scopeRestrictionsDone) return;
300 Module *mergedModule = _linker.getModule();
302 // Start off with a verification pass.
304 passes.add(createVerifierPass());
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;
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);
322 GlobalVariable *LLVMCompilerUsed =
323 mergedModule->getGlobalVariable("llvm.compiler.used");
324 findUsedValues(LLVMCompilerUsed, asmUsed);
325 if (LLVMCompilerUsed)
326 LLVMCompilerUsed->eraseFromParent();
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);
337 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
339 new llvm::GlobalVariable(*mergedModule, ATy, false,
340 llvm::GlobalValue::AppendingLinkage,
341 llvm::ConstantArray::get(ATy, asmUsed2),
342 "llvm.compiler.used");
344 LLVMCompilerUsed->setSection("llvm.metadata");
346 passes.add(createInternalizePass(mustPreserveList));
348 // apply scope restrictions
349 passes.run(*mergedModule);
351 _scopeRestrictionsDone = true;
354 /// Optimize merged modules using various IPO passes
355 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
356 std::string &errMsg) {
357 if ( this->determineTarget(errMsg) )
360 // mark which symbols can not be internalized
361 this->applyScopeRestrictions();
363 Module* mergedModule = _linker.getModule();
365 // if options were requested, set them
366 if ( !_codegenOptions.empty() )
367 cl::ParseCommandLineOptions(_codegenOptions.size(),
368 const_cast<char **>(&_codegenOptions[0]));
370 // Instantiate the pass manager to organize the passes.
373 // Start off with a verification pass.
374 passes.add(createVerifierPass());
376 // Add an appropriate TargetData instance for this module...
377 passes.add(new TargetData(*_target->getTargetData()));
379 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false,
382 // Make sure everything is still good.
383 passes.add(createVerifierPass());
385 FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
387 codeGenPasses->add(new TargetData(*_target->getTargetData()));
389 formatted_raw_ostream Out(out);
391 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
392 TargetMachine::CGFT_ObjectFile,
393 CodeGenOpt::Aggressive)) {
394 errMsg = "target file type not supported";
398 // Run our queue of passes all at once now, efficiently.
399 passes.run(*mergedModule);
401 // Run the code generator, and write assembly file
402 codeGenPasses->doInitialization();
404 for (Module::iterator
405 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
406 if (!it->isDeclaration())
407 codeGenPasses->run(*it);
409 codeGenPasses->doFinalization();
410 delete codeGenPasses;
412 return false; // success
415 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
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
422 if ( _codegenOptions.empty() )
423 _codegenOptions.push_back(strdup("libLTO"));
424 _codegenOptions.push_back(strdup(o.first.str().c_str()));