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);
169 genResult = this->generateObjectFile(objFile.os(), errMsg);
170 objFile.os().close();
171 if (objFile.os().has_error()) {
172 objFile.os().clear_error();
178 uniqueObjPath.eraseFromDisk();
182 _nativeObjectPath = uniqueObjPath.str();
183 *name = _nativeObjectPath.c_str();
187 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
189 if (compile_to_file(&name, errMsg))
192 // remove old buffer if compile() called twice
193 delete _nativeObjectFile;
195 // read .o file into memory buffer
196 OwningPtr<MemoryBuffer> BuffPtr;
197 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
198 errMsg = ec.message();
201 _nativeObjectFile = BuffPtr.take();
204 sys::Path(_nativeObjectPath).eraseFromDisk();
206 // return buffer, unless error
207 if (_nativeObjectFile == NULL)
209 *length = _nativeObjectFile->getBufferSize();
210 return _nativeObjectFile->getBufferStart();
213 bool LTOCodeGenerator::determineTarget(std::string& errMsg) {
217 std::string Triple = _linker.getModule()->getTargetTriple();
219 Triple = sys::getDefaultTargetTriple();
221 // create target machine from info for merged modules
222 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
226 // The relocation model is actually a static member of TargetMachine and
227 // needs to be set before the TargetMachine is instantiated.
228 Reloc::Model RelocModel = Reloc::Default;
229 switch (_codeModel) {
230 case LTO_CODEGEN_PIC_MODEL_STATIC:
231 RelocModel = Reloc::Static;
233 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
234 RelocModel = Reloc::PIC_;
236 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
237 RelocModel = Reloc::DynamicNoPIC;
241 // construct LTOModule, hand over ownership of module and target
242 SubtargetFeatures Features;
243 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
244 std::string FeatureStr = Features.getString();
245 TargetOptions Options;
246 LTOModule::getTargetOptions(Options);
247 _target = march->createTargetMachine(Triple, _mCpu, FeatureStr, Options,
248 RelocModel, CodeModel::Default,
249 CodeGenOpt::Aggressive);
253 void LTOCodeGenerator::
254 applyRestriction(GlobalValue &GV,
255 std::vector<const char*> &mustPreserveList,
256 SmallPtrSet<GlobalValue*, 8> &asmUsed,
258 SmallString<64> Buffer;
259 mangler.getNameWithPrefix(Buffer, &GV, false);
261 if (GV.isDeclaration())
263 if (_mustPreserveSymbols.count(Buffer))
264 mustPreserveList.push_back(GV.getName().data());
265 if (_asmUndefinedRefs.count(Buffer))
269 static void findUsedValues(GlobalVariable *LLVMUsed,
270 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
271 if (LLVMUsed == 0) return;
273 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
274 if (Inits == 0) return;
276 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
277 if (GlobalValue *GV =
278 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
279 UsedValues.insert(GV);
282 void LTOCodeGenerator::applyScopeRestrictions() {
283 if (_scopeRestrictionsDone) return;
284 Module *mergedModule = _linker.getModule();
286 // Start off with a verification pass.
288 passes.add(createVerifierPass());
290 // mark which symbols can not be internalized
291 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
292 Mangler mangler(Context, *_target->getTargetData());
293 std::vector<const char*> mustPreserveList;
294 SmallPtrSet<GlobalValue*, 8> asmUsed;
296 for (Module::iterator f = mergedModule->begin(),
297 e = mergedModule->end(); f != e; ++f)
298 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
299 for (Module::global_iterator v = mergedModule->global_begin(),
300 e = mergedModule->global_end(); v != e; ++v)
301 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
302 for (Module::alias_iterator a = mergedModule->alias_begin(),
303 e = mergedModule->alias_end(); a != e; ++a)
304 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
306 GlobalVariable *LLVMCompilerUsed =
307 mergedModule->getGlobalVariable("llvm.compiler.used");
308 findUsedValues(LLVMCompilerUsed, asmUsed);
309 if (LLVMCompilerUsed)
310 LLVMCompilerUsed->eraseFromParent();
312 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
313 std::vector<Constant*> asmUsed2;
314 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
315 e = asmUsed.end(); i !=e; ++i) {
316 GlobalValue *GV = *i;
317 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
318 asmUsed2.push_back(c);
321 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
323 new llvm::GlobalVariable(*mergedModule, ATy, false,
324 llvm::GlobalValue::AppendingLinkage,
325 llvm::ConstantArray::get(ATy, asmUsed2),
326 "llvm.compiler.used");
328 LLVMCompilerUsed->setSection("llvm.metadata");
330 passes.add(createInternalizePass(mustPreserveList));
332 // apply scope restrictions
333 passes.run(*mergedModule);
335 _scopeRestrictionsDone = true;
338 /// Optimize merged modules using various IPO passes
339 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
340 std::string &errMsg) {
341 if (this->determineTarget(errMsg))
344 Module* mergedModule = _linker.getModule();
346 // if options were requested, set them
347 if (!_codegenOptions.empty())
348 cl::ParseCommandLineOptions(_codegenOptions.size(),
349 const_cast<char **>(&_codegenOptions[0]));
351 // mark which symbols can not be internalized
352 this->applyScopeRestrictions();
354 // Instantiate the pass manager to organize the passes.
357 // Start off with a verification pass.
358 passes.add(createVerifierPass());
360 // Add an appropriate TargetData instance for this module...
361 passes.add(new TargetData(*_target->getTargetData()));
363 // Enabling internalize here would use its AllButMain variant. It
364 // keeps only main if it exists and does nothing for libraries. Instead
365 // we create the pass ourselves with the symbol list provided by the linker.
366 PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/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 errMsg = "target file type not supported";
385 // Run our queue of passes all at once now, efficiently.
386 passes.run(*mergedModule);
388 // Run the code generator, and write assembly file
389 codeGenPasses->doInitialization();
391 for (Module::iterator
392 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
393 if (!it->isDeclaration())
394 codeGenPasses->run(*it);
396 codeGenPasses->doFinalization();
397 delete codeGenPasses;
399 return false; // success
402 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
404 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
405 for (std::pair<StringRef, StringRef> o = getToken(options);
406 !o.first.empty(); o = getToken(o.second)) {
407 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
409 if (_codegenOptions.empty())
410 _codegenOptions.push_back(strdup("libLTO"));
411 _codegenOptions.push_back(strdup(o.first.str().c_str()));