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/Bitcode/ReaderWriter.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/TargetRegistry.h"
35 #include "llvm/Target/TargetSelect.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PassManagerBuilder.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/system_error.h"
46 #include "llvm/Config/config.h"
54 static cl::opt<bool> DisableInline("disable-inlining",
55 cl::desc("Do not run the inliner pass"));
58 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;
68 LTOCodeGenerator::LTOCodeGenerator()
69 : _context(getGlobalContext()),
70 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
71 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
72 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
73 _nativeObjectFile(NULL)
75 InitializeAllTargets();
76 InitializeAllMCAsmInfos();
77 InitializeAllMCSubtargetInfos();
78 InitializeAllAsmPrinters();
81 LTOCodeGenerator::~LTOCodeGenerator()
84 delete _nativeObjectFile;
89 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
92 if(mod->getLLVVMModule()->MaterializeAllPermanently(&errMsg))
95 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
97 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
98 for (int i = 0, e = undefs.size(); i != e; ++i)
99 _asmUndefinedRefs[undefs[i]] = 1;
105 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
108 case LTO_DEBUG_MODEL_NONE:
109 _emitDwarfDebugInfo = false;
112 case LTO_DEBUG_MODEL_DWARF:
113 _emitDwarfDebugInfo = true;
116 errMsg = "unknown debug format";
121 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
125 case LTO_CODEGEN_PIC_MODEL_STATIC:
126 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
127 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
131 errMsg = "unknown pic model";
135 void LTOCodeGenerator::setCpu(const char* mCpu)
140 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
142 _mustPreserveSymbols[sym] = 1;
146 bool LTOCodeGenerator::writeMergedModules(const char *path,
147 std::string &errMsg) {
148 if (determineTarget(errMsg))
151 // mark which symbols can not be internalized
152 applyScopeRestrictions();
154 // create output file
156 tool_output_file Out(path, ErrInfo,
157 raw_fd_ostream::F_Binary);
158 if (!ErrInfo.empty()) {
159 errMsg = "could not open bitcode file for writing: ";
164 // write bitcode to it
165 WriteBitcodeToFile(_linker.getModule(), Out.os());
168 if (Out.os().has_error()) {
169 errMsg = "could not write bitcode file: ";
171 Out.os().clear_error();
180 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg)
182 // make unique temp .o file to put generated object file
183 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
184 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
185 uniqueObjPath.eraseFromDisk();
188 sys::RemoveFileOnSignal(uniqueObjPath);
190 // generate object file
191 bool genResult = false;
192 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
195 genResult = this->generateObjectFile(objFile.os(), errMsg);
196 objFile.os().close();
197 if (objFile.os().has_error()) {
198 objFile.os().clear_error();
203 uniqueObjPath.eraseFromDisk();
207 _nativeObjectPath = uniqueObjPath.str();
208 *name = _nativeObjectPath.c_str();
212 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
215 if (compile_to_file(&name, errMsg))
218 // remove old buffer if compile() called twice
219 delete _nativeObjectFile;
221 // read .o file into memory buffer
222 OwningPtr<MemoryBuffer> BuffPtr;
223 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
224 errMsg = ec.message();
227 _nativeObjectFile = BuffPtr.take();
230 sys::Path(_nativeObjectPath).eraseFromDisk();
232 // return buffer, unless error
233 if ( _nativeObjectFile == NULL )
235 *length = _nativeObjectFile->getBufferSize();
236 return _nativeObjectFile->getBufferStart();
239 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
241 if ( _target == NULL ) {
242 std::string Triple = _linker.getModule()->getTargetTriple();
244 Triple = sys::getHostTriple();
246 // create target machine from info for merged modules
247 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
251 // The relocation model is actually a static member of TargetMachine
252 // and needs to be set before the TargetMachine is instantiated.
253 switch( _codeModel ) {
254 case LTO_CODEGEN_PIC_MODEL_STATIC:
255 TargetMachine::setRelocationModel(Reloc::Static);
257 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
258 TargetMachine::setRelocationModel(Reloc::PIC_);
260 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
261 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
265 // construct LTModule, hand over ownership of module and target
266 SubtargetFeatures Features;
267 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
268 std::string FeatureStr = Features.getString();
269 _target = march->createTargetMachine(Triple, _mCpu, FeatureStr);
274 void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
275 std::vector<const char*> &mustPreserveList,
276 SmallPtrSet<GlobalValue*, 8> &asmUsed,
278 SmallString<64> Buffer;
279 mangler.getNameWithPrefix(Buffer, &GV, false);
281 if (GV.isDeclaration())
283 if (_mustPreserveSymbols.count(Buffer))
284 mustPreserveList.push_back(GV.getName().data());
285 if (_asmUndefinedRefs.count(Buffer))
289 static void findUsedValues(GlobalVariable *LLVMUsed,
290 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
291 if (LLVMUsed == 0) return;
293 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
294 if (Inits == 0) return;
296 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
297 if (GlobalValue *GV =
298 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
299 UsedValues.insert(GV);
302 void LTOCodeGenerator::applyScopeRestrictions() {
303 if (_scopeRestrictionsDone) return;
304 Module *mergedModule = _linker.getModule();
306 // Start off with a verification pass.
308 passes.add(createVerifierPass());
310 // mark which symbols can not be internalized
311 MCContext Context(*_target->getMCAsmInfo(), NULL);
312 Mangler mangler(Context, *_target->getTargetData());
313 std::vector<const char*> mustPreserveList;
314 SmallPtrSet<GlobalValue*, 8> asmUsed;
316 for (Module::iterator f = mergedModule->begin(),
317 e = mergedModule->end(); f != e; ++f)
318 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
319 for (Module::global_iterator v = mergedModule->global_begin(),
320 e = mergedModule->global_end(); v != e; ++v)
321 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
322 for (Module::alias_iterator a = mergedModule->alias_begin(),
323 e = mergedModule->alias_end(); a != e; ++a)
324 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
326 GlobalVariable *LLVMCompilerUsed =
327 mergedModule->getGlobalVariable("llvm.compiler.used");
328 findUsedValues(LLVMCompilerUsed, asmUsed);
329 if (LLVMCompilerUsed)
330 LLVMCompilerUsed->eraseFromParent();
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);
341 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
343 new llvm::GlobalVariable(*mergedModule, ATy, false,
344 llvm::GlobalValue::AppendingLinkage,
345 llvm::ConstantArray::get(ATy, asmUsed2),
346 "llvm.compiler.used");
348 LLVMCompilerUsed->setSection("llvm.metadata");
350 passes.add(createInternalizePass(mustPreserveList));
352 // apply scope restrictions
353 passes.run(*mergedModule);
355 _scopeRestrictionsDone = true;
358 /// Optimize merged modules using various IPO passes
359 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
360 std::string &errMsg) {
361 if ( this->determineTarget(errMsg) )
364 // mark which symbols can not be internalized
365 this->applyScopeRestrictions();
367 Module* mergedModule = _linker.getModule();
369 // if options were requested, set them
370 if ( !_codegenOptions.empty() )
371 cl::ParseCommandLineOptions(_codegenOptions.size(),
372 const_cast<char **>(&_codegenOptions[0]));
374 // Instantiate the pass manager to organize the passes.
377 // Start off with a verification pass.
378 passes.add(createVerifierPass());
380 // Add an appropriate TargetData instance for this module...
381 passes.add(new TargetData(*_target->getTargetData()));
383 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false,
386 // Make sure everything is still good.
387 passes.add(createVerifierPass());
389 FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
391 codeGenPasses->add(new TargetData(*_target->getTargetData()));
393 formatted_raw_ostream Out(out);
395 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
396 TargetMachine::CGFT_ObjectFile,
397 CodeGenOpt::Aggressive)) {
398 errMsg = "target file type not supported";
402 // Run our queue of passes all at once now, efficiently.
403 passes.run(*mergedModule);
405 // Run the code generator, and write assembly file
406 codeGenPasses->doInitialization();
408 for (Module::iterator
409 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
410 if (!it->isDeclaration())
411 codeGenPasses->run(*it);
413 codeGenPasses->doFinalization();
414 delete codeGenPasses;
416 return false; // success
420 /// Optimize merged modules using various IPO passes
421 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
423 for (std::pair<StringRef, StringRef> o = getToken(options);
424 !o.first.empty(); o = getToken(o.second)) {
425 // ParseCommandLineOptions() expects argv[0] to be program name.
427 if ( _codegenOptions.empty() )
428 _codegenOptions.push_back("libLTO");
429 _codegenOptions.push_back(strdup(o.first.str().c_str()));