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 "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/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/system_error.h"
46 #include "llvm/ADT/StringExtras.h"
49 static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
50 cl::desc("Do not run the inliner pass"));
52 static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
53 cl::desc("Do not run the GVN load PRE pass"));
55 const char* LTOCodeGenerator::getVersionString() {
56 #ifdef LLVM_VERSION_INFO
57 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
59 return PACKAGE_NAME " version " PACKAGE_VERSION;
63 LTOCodeGenerator::LTOCodeGenerator()
64 : _context(getGlobalContext()),
65 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
66 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
67 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
68 _nativeObjectFile(NULL) {
69 InitializeAllTargets();
70 InitializeAllTargetMCs();
71 InitializeAllAsmPrinters();
74 LTOCodeGenerator::~LTOCodeGenerator() {
76 delete _nativeObjectFile;
78 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
79 E = _codegenOptions.end(); I != E; ++I)
83 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
84 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
86 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
87 for (int i = 0, e = undefs.size(); i != e; ++i)
88 _asmUndefinedRefs[undefs[i]] = 1;
93 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
94 std::string& errMsg) {
96 case LTO_DEBUG_MODEL_NONE:
97 _emitDwarfDebugInfo = false;
100 case LTO_DEBUG_MODEL_DWARF:
101 _emitDwarfDebugInfo = true;
104 llvm_unreachable("Unknown debug format!");
107 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
108 std::string& errMsg) {
110 case LTO_CODEGEN_PIC_MODEL_STATIC:
111 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
112 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
116 llvm_unreachable("Unknown PIC model!");
119 bool LTOCodeGenerator::writeMergedModules(const char *path,
120 std::string &errMsg) {
121 if (determineTarget(errMsg))
124 // mark which symbols can not be internalized
125 applyScopeRestrictions();
127 // create output file
129 tool_output_file Out(path, ErrInfo,
130 raw_fd_ostream::F_Binary);
131 if (!ErrInfo.empty()) {
132 errMsg = "could not open bitcode file for writing: ";
137 // write bitcode to it
138 WriteBitcodeToFile(_linker.getModule(), Out.os());
141 if (Out.os().has_error()) {
142 errMsg = "could not write bitcode file: ";
144 Out.os().clear_error();
152 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
153 // make unique temp .o file to put generated object file
154 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
155 if ( uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg) ) {
156 uniqueObjPath.eraseFromDisk();
159 sys::RemoveFileOnSignal(uniqueObjPath);
161 // generate object file
162 bool genResult = false;
163 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
167 genResult = this->generateObjectFile(objFile.os(), errMsg);
168 objFile.os().close();
169 if (objFile.os().has_error()) {
170 objFile.os().clear_error();
176 uniqueObjPath.eraseFromDisk();
180 _nativeObjectPath = uniqueObjPath.str();
181 *name = _nativeObjectPath.c_str();
185 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
187 if (compile_to_file(&name, errMsg))
190 // remove old buffer if compile() called twice
191 delete _nativeObjectFile;
193 // read .o file into memory buffer
194 OwningPtr<MemoryBuffer> BuffPtr;
195 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
196 errMsg = ec.message();
199 _nativeObjectFile = BuffPtr.take();
202 sys::Path(_nativeObjectPath).eraseFromDisk();
204 // return buffer, unless error
205 if ( _nativeObjectFile == NULL )
207 *length = _nativeObjectFile->getBufferSize();
208 return _nativeObjectFile->getBufferStart();
211 bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
212 if ( _target == NULL ) {
213 std::string Triple = _linker.getModule()->getTargetTriple();
215 Triple = sys::getDefaultTargetTriple();
217 // create target machine from info for merged modules
218 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
222 // The relocation model is actually a static member of TargetMachine and
223 // needs to be set before the TargetMachine is instantiated.
224 Reloc::Model RelocModel = Reloc::Default;
225 switch( _codeModel ) {
226 case LTO_CODEGEN_PIC_MODEL_STATIC:
227 RelocModel = Reloc::Static;
229 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
230 RelocModel = Reloc::PIC_;
232 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
233 RelocModel = Reloc::DynamicNoPIC;
237 // construct LTOModule, hand over ownership of module and target
238 SubtargetFeatures Features;
239 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
240 std::string FeatureStr = Features.getString();
241 TargetOptions Options;
242 _target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
243 RelocModel, CodeModel::Default,
244 CodeGenOpt::Aggressive);
249 void LTOCodeGenerator::
250 applyRestriction(GlobalValue &GV,
251 std::vector<const char*> &mustPreserveList,
252 SmallPtrSet<GlobalValue*, 8> &asmUsed,
254 SmallString<64> Buffer;
255 mangler.getNameWithPrefix(Buffer, &GV, false);
257 if (GV.isDeclaration())
259 if (_mustPreserveSymbols.count(Buffer))
260 mustPreserveList.push_back(GV.getName().data());
261 if (_asmUndefinedRefs.count(Buffer))
265 static void findUsedValues(GlobalVariable *LLVMUsed,
266 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
267 if (LLVMUsed == 0) return;
269 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
270 if (Inits == 0) return;
272 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
273 if (GlobalValue *GV =
274 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
275 UsedValues.insert(GV);
278 void LTOCodeGenerator::applyScopeRestrictions() {
279 if (_scopeRestrictionsDone) return;
280 Module *mergedModule = _linker.getModule();
282 // Start off with a verification pass.
284 passes.add(createVerifierPass());
286 // mark which symbols can not be internalized
287 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
288 Mangler mangler(Context, *_target->getTargetData());
289 std::vector<const char*> mustPreserveList;
290 SmallPtrSet<GlobalValue*, 8> asmUsed;
292 for (Module::iterator f = mergedModule->begin(),
293 e = mergedModule->end(); f != e; ++f)
294 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
295 for (Module::global_iterator v = mergedModule->global_begin(),
296 e = mergedModule->global_end(); v != e; ++v)
297 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
298 for (Module::alias_iterator a = mergedModule->alias_begin(),
299 e = mergedModule->alias_end(); a != e; ++a)
300 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
302 GlobalVariable *LLVMCompilerUsed =
303 mergedModule->getGlobalVariable("llvm.compiler.used");
304 findUsedValues(LLVMCompilerUsed, asmUsed);
305 if (LLVMCompilerUsed)
306 LLVMCompilerUsed->eraseFromParent();
308 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
309 std::vector<Constant*> asmUsed2;
310 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
311 e = asmUsed.end(); i !=e; ++i) {
312 GlobalValue *GV = *i;
313 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
314 asmUsed2.push_back(c);
317 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
319 new llvm::GlobalVariable(*mergedModule, ATy, false,
320 llvm::GlobalValue::AppendingLinkage,
321 llvm::ConstantArray::get(ATy, asmUsed2),
322 "llvm.compiler.used");
324 LLVMCompilerUsed->setSection("llvm.metadata");
326 passes.add(createInternalizePass(mustPreserveList));
328 // apply scope restrictions
329 passes.run(*mergedModule);
331 _scopeRestrictionsDone = true;
334 /// Optimize merged modules using various IPO passes
335 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
336 std::string &errMsg) {
337 if ( this->determineTarget(errMsg) )
340 Module* mergedModule = _linker.getModule();
342 // if options were requested, set them
343 if ( !_codegenOptions.empty() )
344 cl::ParseCommandLineOptions(_codegenOptions.size(),
345 const_cast<char **>(&_codegenOptions[0]));
347 // mark which symbols can not be internalized
348 this->applyScopeRestrictions();
350 // Instantiate the pass manager to organize the passes.
353 // Start off with a verification pass.
354 passes.add(createVerifierPass());
356 // Add an appropriate TargetData instance for this module...
357 passes.add(new TargetData(*_target->getTargetData()));
359 // Enabling internalize here would use its AllButMain variant. It
360 // keeps only main if it exists and does nothing for libraries. Instead
361 // we create the pass ourselves with the symbol list provided by the linker.
362 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/false,
366 // Make sure everything is still good.
367 passes.add(createVerifierPass());
369 FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
371 codeGenPasses->add(new TargetData(*_target->getTargetData()));
373 formatted_raw_ostream Out(out);
375 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
376 TargetMachine::CGFT_ObjectFile)) {
377 errMsg = "target file type not supported";
381 // Run our queue of passes all at once now, efficiently.
382 passes.run(*mergedModule);
384 // Run the code generator, and write assembly file
385 codeGenPasses->doInitialization();
387 for (Module::iterator
388 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
389 if (!it->isDeclaration())
390 codeGenPasses->run(*it);
392 codeGenPasses->doFinalization();
393 delete codeGenPasses;
395 return false; // success
398 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
400 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
401 for (std::pair<StringRef, StringRef> o = getToken(options);
402 !o.first.empty(); o = getToken(o.second)) {
403 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
405 if ( _codegenOptions.empty() )
406 _codegenOptions.push_back(strdup("libLTO"));
407 _codegenOptions.push_back(strdup(o.first.str().c_str()));