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"
50 DisableInline("disable-inlining", cl::init(false),
51 cl::desc("Do not run the inliner pass"));
54 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
55 cl::desc("Do not run the GVN load PRE pass"));
57 const char* LTOCodeGenerator::getVersionString() {
58 #ifdef LLVM_VERSION_INFO
59 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 return PACKAGE_NAME " version " PACKAGE_VERSION;
65 LTOCodeGenerator::LTOCodeGenerator()
66 : _context(getGlobalContext()),
67 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
68 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
69 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
70 _nativeObjectFile(NULL) {
71 InitializeAllTargets();
72 InitializeAllTargetMCs();
73 InitializeAllAsmPrinters();
76 LTOCodeGenerator::~LTOCodeGenerator() {
78 delete _nativeObjectFile;
80 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
81 E = _codegenOptions.end(); I != E; ++I)
85 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
86 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
88 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
89 for (int i = 0, e = undefs.size(); i != e; ++i)
90 _asmUndefinedRefs[undefs[i]] = 1;
95 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
96 std::string& errMsg) {
98 case LTO_DEBUG_MODEL_NONE:
99 _emitDwarfDebugInfo = false;
102 case LTO_DEBUG_MODEL_DWARF:
103 _emitDwarfDebugInfo = true;
106 llvm_unreachable("Unknown debug format!");
109 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
110 std::string& errMsg) {
112 case LTO_CODEGEN_PIC_MODEL_STATIC:
113 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
114 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
118 llvm_unreachable("Unknown PIC model!");
121 bool LTOCodeGenerator::writeMergedModules(const char *path,
122 std::string &errMsg) {
123 if (determineTarget(errMsg))
126 // mark which symbols can not be internalized
127 applyScopeRestrictions();
129 // create output file
131 tool_output_file Out(path, ErrInfo,
132 raw_fd_ostream::F_Binary);
133 if (!ErrInfo.empty()) {
134 errMsg = "could not open bitcode file for writing: ";
139 // write bitcode to it
140 WriteBitcodeToFile(_linker.getModule(), Out.os());
143 if (Out.os().has_error()) {
144 errMsg = "could not write bitcode file: ";
146 Out.os().clear_error();
154 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
155 // make unique temp .o file to put generated object file
156 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
157 if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
158 uniqueObjPath.eraseFromDisk();
161 sys::RemoveFileOnSignal(uniqueObjPath);
163 // generate object file
164 bool genResult = false;
165 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
166 if (!errMsg.empty()) {
167 uniqueObjPath.eraseFromDisk();
171 genResult = this->generateObjectFile(objFile.os(), errMsg);
172 objFile.os().close();
173 if (objFile.os().has_error()) {
174 objFile.os().clear_error();
175 uniqueObjPath.eraseFromDisk();
181 uniqueObjPath.eraseFromDisk();
185 _nativeObjectPath = uniqueObjPath.str();
186 *name = _nativeObjectPath.c_str();
190 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
192 if (compile_to_file(&name, errMsg))
195 // remove old buffer if compile() called twice
196 delete _nativeObjectFile;
198 // read .o file into memory buffer
199 OwningPtr<MemoryBuffer> BuffPtr;
200 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
201 errMsg = ec.message();
202 sys::Path(_nativeObjectPath).eraseFromDisk();
205 _nativeObjectFile = BuffPtr.take();
208 sys::Path(_nativeObjectPath).eraseFromDisk();
210 // return buffer, unless error
211 if (_nativeObjectFile == NULL)
213 *length = _nativeObjectFile->getBufferSize();
214 return _nativeObjectFile->getBufferStart();
217 bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
221 std::string Triple = _linker.getModule()->getTargetTriple();
223 Triple = sys::getDefaultTargetTriple();
225 // create target machine from info for merged modules
226 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
230 // The relocation model is actually a static member of TargetMachine and
231 // needs to be set before the TargetMachine is instantiated.
232 Reloc::Model RelocModel = Reloc::Default;
233 switch (_codeModel) {
234 case LTO_CODEGEN_PIC_MODEL_STATIC:
235 RelocModel = Reloc::Static;
237 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
238 RelocModel = Reloc::PIC_;
240 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
241 RelocModel = Reloc::DynamicNoPIC;
245 // construct LTOModule, hand over ownership of module and target
246 SubtargetFeatures Features;
247 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
248 std::string FeatureStr = Features.getString();
249 TargetOptions Options;
250 LTOModule::getTargetOptions(Options);
251 _target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
252 RelocModel, CodeModel::Default,
253 CodeGenOpt::Aggressive);
257 void LTOCodeGenerator::
258 applyRestriction(GlobalValue &GV,
259 std::vector<const char*> &mustPreserveList,
260 SmallPtrSet<GlobalValue*, 8> &asmUsed,
262 SmallString<64> Buffer;
263 mangler.getNameWithPrefix(Buffer, &GV, false);
265 if (GV.isDeclaration())
267 if (_mustPreserveSymbols.count(Buffer))
268 mustPreserveList.push_back(GV.getName().data());
269 if (_asmUndefinedRefs.count(Buffer))
273 static void findUsedValues(GlobalVariable *LLVMUsed,
274 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
275 if (LLVMUsed == 0) return;
277 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
278 if (Inits == 0) return;
280 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
281 if (GlobalValue *GV =
282 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
283 UsedValues.insert(GV);
286 void LTOCodeGenerator::applyScopeRestrictions() {
287 if (_scopeRestrictionsDone) return;
288 Module *mergedModule = _linker.getModule();
290 // Start off with a verification pass.
292 passes.add(createVerifierPass());
294 // mark which symbols can not be internalized
295 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
296 Mangler mangler(Context, *_target->getTargetData());
297 std::vector<const char*> mustPreserveList;
298 SmallPtrSet<GlobalValue*, 8> asmUsed;
300 for (Module::iterator f = mergedModule->begin(),
301 e = mergedModule->end(); f != e; ++f)
302 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
303 for (Module::global_iterator v = mergedModule->global_begin(),
304 e = mergedModule->global_end(); v != e; ++v)
305 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
306 for (Module::alias_iterator a = mergedModule->alias_begin(),
307 e = mergedModule->alias_end(); a != e; ++a)
308 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
310 GlobalVariable *LLVMCompilerUsed =
311 mergedModule->getGlobalVariable("llvm.compiler.used");
312 findUsedValues(LLVMCompilerUsed, asmUsed);
313 if (LLVMCompilerUsed)
314 LLVMCompilerUsed->eraseFromParent();
316 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
317 std::vector<Constant*> asmUsed2;
318 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
319 e = asmUsed.end(); i !=e; ++i) {
320 GlobalValue *GV = *i;
321 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
322 asmUsed2.push_back(c);
325 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
327 new llvm::GlobalVariable(*mergedModule, ATy, false,
328 llvm::GlobalValue::AppendingLinkage,
329 llvm::ConstantArray::get(ATy, asmUsed2),
330 "llvm.compiler.used");
332 LLVMCompilerUsed->setSection("llvm.metadata");
334 passes.add(createInternalizePass(mustPreserveList));
336 // apply scope restrictions
337 passes.run(*mergedModule);
339 _scopeRestrictionsDone = true;
342 /// Optimize merged modules using various IPO passes
343 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
344 std::string &errMsg) {
345 if (this->determineTarget(errMsg))
348 Module* mergedModule = _linker.getModule();
350 // if options were requested, set them
351 if (!_codegenOptions.empty())
352 cl::ParseCommandLineOptions(_codegenOptions.size(),
353 const_cast<char **>(&_codegenOptions[0]));
355 // mark which symbols can not be internalized
356 this->applyScopeRestrictions();
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 // Enabling internalize here would use its AllButMain variant. It
368 // keeps only main if it exists and does nothing for libraries. Instead
369 // we create the pass ourselves with the symbol list provided by the linker.
370 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/false,
374 // Make sure everything is still good.
375 passes.add(createVerifierPass());
377 FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);
379 codeGenPasses->add(new TargetData(*_target->getTargetData()));
381 formatted_raw_ostream Out(out);
383 if (_target->addPassesToEmitFile(*codeGenPasses, Out,
384 TargetMachine::CGFT_ObjectFile)) {
385 errMsg = "target file type not supported";
389 // Run our queue of passes all at once now, efficiently.
390 passes.run(*mergedModule);
392 // Run the code generator, and write assembly file
393 codeGenPasses->doInitialization();
395 for (Module::iterator
396 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
397 if (!it->isDeclaration())
398 codeGenPasses->run(*it);
400 codeGenPasses->doFinalization();
401 delete codeGenPasses;
403 return false; // success
406 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
408 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
409 for (std::pair<StringRef, StringRef> o = getToken(options);
410 !o.first.empty(); o = getToken(o.second)) {
411 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
413 if (_codegenOptions.empty())
414 _codegenOptions.push_back(strdup("libLTO"));
415 _codegenOptions.push_back(strdup(o.first.str().c_str()));