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"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Linker.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/Passes.h"
27 #include "llvm/Bitcode/ReaderWriter.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/StandardPasses.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/system_error.h"
47 #include "llvm/Config/config.h"
55 static cl::opt<bool> DisableInline("disable-inlining",
56 cl::desc("Do not run the inliner pass"));
59 const char* LTOCodeGenerator::getVersionString()
61 #ifdef LLVM_VERSION_INFO
62 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
64 return PACKAGE_NAME " version " PACKAGE_VERSION;
69 LTOCodeGenerator::LTOCodeGenerator()
70 : _context(getGlobalContext()),
71 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
72 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
73 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
74 _nativeObjectFile(NULL)
76 InitializeAllTargets();
77 InitializeAllAsmPrinters();
80 LTOCodeGenerator::~LTOCodeGenerator()
83 delete _nativeObjectFile;
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 errMsg = "unknown debug format";
116 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
120 case LTO_CODEGEN_PIC_MODEL_STATIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
122 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
126 errMsg = "unknown pic model";
130 void LTOCodeGenerator::setCpu(const char* mCpu)
135 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
137 _mustPreserveSymbols[sym] = 1;
141 bool LTOCodeGenerator::writeMergedModules(const char *path,
142 std::string &errMsg) {
143 if (determineTarget(errMsg))
146 // mark which symbols can not be internalized
147 applyScopeRestrictions();
149 // create output file
151 tool_output_file Out(path, ErrInfo,
152 raw_fd_ostream::F_Binary);
153 if (!ErrInfo.empty()) {
154 errMsg = "could not open bitcode file for writing: ";
159 // write bitcode to it
160 WriteBitcodeToFile(_linker.getModule(), Out.os());
163 if (Out.os().has_error()) {
164 errMsg = "could not write bitcode file: ";
166 Out.os().clear_error();
175 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
177 // make unique temp .o file to put generated object file
178 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
179 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
180 uniqueObjPath.eraseFromDisk();
183 sys::RemoveFileOnSignal(uniqueObjPath);
185 // generate object file
186 bool genResult = false;
187 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
190 genResult = this->generateObjectFile(objFile.os(), errMsg);
191 objFile.os().close();
192 if (objFile.os().has_error()) {
193 objFile.os().clear_error();
198 uniqueObjPath.eraseFromDisk();
202 const std::string& uniqueObjStr = uniqueObjPath.str();
203 // remove old buffer if compile() called twice
204 delete _nativeObjectFile;
206 // read .o file into memory buffer
207 OwningPtr<MemoryBuffer> BuffPtr;
208 if (error_code ec = MemoryBuffer::getFile(uniqueObjStr.c_str(),BuffPtr))
209 errMsg = ec.message();
210 _nativeObjectFile = BuffPtr.take();
213 uniqueObjPath.eraseFromDisk();
215 // return buffer, unless error
216 if ( _nativeObjectFile == NULL )
218 *length = _nativeObjectFile->getBufferSize();
219 return _nativeObjectFile->getBufferStart();
222 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
224 if ( _target == NULL ) {
225 std::string Triple = _linker.getModule()->getTargetTriple();
227 Triple = sys::getHostTriple();
229 // create target machine from info for merged modules
230 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
234 // The relocation model is actually a static member of TargetMachine
235 // and needs to be set before the TargetMachine is instantiated.
236 switch( _codeModel ) {
237 case LTO_CODEGEN_PIC_MODEL_STATIC:
238 TargetMachine::setRelocationModel(Reloc::Static);
240 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
241 TargetMachine::setRelocationModel(Reloc::PIC_);
243 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
244 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
248 // construct LTModule, hand over ownership of module and target
249 SubtargetFeatures Features;
250 Features.getDefaultSubtargetFeatures(_mCpu, llvm::Triple(Triple));
251 std::string FeatureStr = Features.getString();
252 _target = march->createTargetMachine(Triple, FeatureStr);
257 void LTOCodeGenerator::applyRestriction(GlobalValue &GV,
258 std::vector<const char*> &mustPreserveList,
259 SmallPtrSet<GlobalValue*, 8> &asmUsed,
261 SmallString<64> Buffer;
262 mangler.getNameWithPrefix(Buffer, &GV, false);
264 if (GV.isDeclaration())
266 if (_mustPreserveSymbols.count(Buffer))
267 mustPreserveList.push_back(GV.getName().data());
268 if (_asmUndefinedRefs.count(Buffer))
272 static void findUsedValues(GlobalVariable *LLVMUsed,
273 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
274 if (LLVMUsed == 0) return;
276 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
277 if (Inits == 0) return;
279 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
280 if (GlobalValue *GV =
281 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
282 UsedValues.insert(GV);
285 void LTOCodeGenerator::applyScopeRestrictions() {
286 if (_scopeRestrictionsDone) return;
287 Module *mergedModule = _linker.getModule();
289 // Start off with a verification pass.
291 passes.add(createVerifierPass());
293 // mark which symbols can not be internalized
294 MCContext Context(*_target->getMCAsmInfo(), NULL);
295 Mangler mangler(Context, *_target->getTargetData());
296 std::vector<const char*> mustPreserveList;
297 SmallPtrSet<GlobalValue*, 8> asmUsed;
299 for (Module::iterator f = mergedModule->begin(),
300 e = mergedModule->end(); f != e; ++f)
301 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
302 for (Module::global_iterator v = mergedModule->global_begin(),
303 e = mergedModule->global_end(); v != e; ++v)
304 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
305 for (Module::alias_iterator a = mergedModule->alias_begin(),
306 e = mergedModule->alias_end(); a != e; ++a)
307 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
309 GlobalVariable *LLVMCompilerUsed =
310 mergedModule->getGlobalVariable("llvm.compiler.used");
311 findUsedValues(LLVMCompilerUsed, asmUsed);
312 if (LLVMCompilerUsed)
313 LLVMCompilerUsed->eraseFromParent();
315 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
316 std::vector<Constant*> asmUsed2;
317 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
318 e = asmUsed.end(); i !=e; ++i) {
319 GlobalValue *GV = *i;
320 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
321 asmUsed2.push_back(c);
324 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
326 new llvm::GlobalVariable(*mergedModule, ATy, false,
327 llvm::GlobalValue::AppendingLinkage,
328 llvm::ConstantArray::get(ATy, asmUsed2),
329 "llvm.compiler.used");
331 LLVMCompilerUsed->setSection("llvm.metadata");
333 passes.add(createInternalizePass(mustPreserveList));
335 // apply scope restrictions
336 passes.run(*mergedModule);
338 _scopeRestrictionsDone = true;
341 /// Optimize merged modules using various IPO passes
342 bool LTOCodeGenerator::generateObjectFile(raw_ostream& out,
345 if ( this->determineTarget(errMsg) )
348 // mark which symbols can not be internalized
349 this->applyScopeRestrictions();
351 Module* mergedModule = _linker.getModule();
353 // if options were requested, set them
354 if ( !_codegenOptions.empty() )
355 cl::ParseCommandLineOptions(_codegenOptions.size(),
356 const_cast<char **>(&_codegenOptions[0]));
358 // Instantiate the pass manager to organize the passes.
361 // Start off with a verification pass.
362 passes.add(createVerifierPass());
364 // Add an appropriate TargetData instance for this module...
365 passes.add(new TargetData(*_target->getTargetData()));
367 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
368 /*VerifyEach=*/ false);
370 // Make sure everything is still good.
371 passes.add(createVerifierPass());
373 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
375 codeGenPasses->add(new TargetData(*_target->getTargetData()));
377 formatted_raw_ostream Out(out);
379 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
380 TargetMachine::CGFT_ObjectFile,
381 CodeGenOpt::Aggressive)) {
382 errMsg = "target file type not supported";
386 // Run our queue of passes all at once now, efficiently.
387 passes.run(*mergedModule);
389 // Run the code generator, and write assembly file
390 codeGenPasses->doInitialization();
392 for (Module::iterator
393 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
394 if (!it->isDeclaration())
395 codeGenPasses->run(*it);
397 codeGenPasses->doFinalization();
398 delete codeGenPasses;
400 return false; // success
404 /// Optimize merged modules using various IPO passes
405 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
407 for (std::pair<StringRef, StringRef> o = getToken(options);
408 !o.first.empty(); o = getToken(o.second)) {
409 // ParseCommandLineOptions() expects argv[0] to be program name.
411 if ( _codegenOptions.empty() )
412 _codegenOptions.push_back("libLTO");
413 _codegenOptions.push_back(strdup(o.first.str().c_str()));