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/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Linker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
40 #include "llvm/Support/system_error.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/ObjCARC.h"
51 DisableOpt("disable-opt", cl::init(false),
52 cl::desc("Do not run any optimization passes"));
55 DisableInline("disable-inlining", cl::init(false),
56 cl::desc("Do not run the inliner pass"));
59 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60 cl::desc("Do not run the GVN load PRE pass"));
62 const char* LTOCodeGenerator::getVersionString() {
63 #ifdef LLVM_VERSION_INFO
64 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 return PACKAGE_NAME " version " PACKAGE_VERSION;
70 LTOCodeGenerator::LTOCodeGenerator()
71 : _context(getGlobalContext()),
72 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
73 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
74 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
75 _nativeObjectFile(NULL) {
76 InitializeAllTargets();
77 InitializeAllTargetMCs();
78 InitializeAllAsmPrinters();
81 LTOCodeGenerator::~LTOCodeGenerator() {
83 delete _nativeObjectFile;
85 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
86 E = _codegenOptions.end(); I != E; ++I)
90 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
91 bool ret = _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
93 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
94 for (int i = 0, e = undefs.size(); i != e; ++i)
95 _asmUndefinedRefs[undefs[i]] = 1;
100 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
101 std::string& errMsg) {
103 case LTO_DEBUG_MODEL_NONE:
104 _emitDwarfDebugInfo = false;
107 case LTO_DEBUG_MODEL_DWARF:
108 _emitDwarfDebugInfo = true;
111 llvm_unreachable("Unknown debug format!");
114 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
115 std::string& errMsg) {
117 case LTO_CODEGEN_PIC_MODEL_STATIC:
118 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
119 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
123 llvm_unreachable("Unknown PIC model!");
126 bool LTOCodeGenerator::writeMergedModules(const char *path,
127 std::string &errMsg) {
128 if (determineTarget(errMsg))
131 // mark which symbols can not be internalized
132 applyScopeRestrictions();
134 // create output file
136 tool_output_file Out(path, ErrInfo,
137 raw_fd_ostream::F_Binary);
138 if (!ErrInfo.empty()) {
139 errMsg = "could not open bitcode file for writing: ";
144 // write bitcode to it
145 WriteBitcodeToFile(_linker.getModule(), Out.os());
148 if (Out.os().has_error()) {
149 errMsg = "could not write bitcode file: ";
151 Out.os().clear_error();
159 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
160 // make unique temp .o file to put generated object file
161 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
162 if (uniqueObjPath.createTemporaryFileOnDisk(false, &errMsg)) {
163 uniqueObjPath.eraseFromDisk();
166 sys::RemoveFileOnSignal(uniqueObjPath);
168 // generate object file
169 bool genResult = false;
170 tool_output_file objFile(uniqueObjPath.c_str(), errMsg);
171 if (!errMsg.empty()) {
172 uniqueObjPath.eraseFromDisk();
176 genResult = this->generateObjectFile(objFile.os(), errMsg);
177 objFile.os().close();
178 if (objFile.os().has_error()) {
179 objFile.os().clear_error();
180 uniqueObjPath.eraseFromDisk();
186 uniqueObjPath.eraseFromDisk();
190 _nativeObjectPath = uniqueObjPath.str();
191 *name = _nativeObjectPath.c_str();
195 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
197 if (compile_to_file(&name, errMsg))
200 // remove old buffer if compile() called twice
201 delete _nativeObjectFile;
203 // read .o file into memory buffer
204 OwningPtr<MemoryBuffer> BuffPtr;
205 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
206 errMsg = ec.message();
207 sys::Path(_nativeObjectPath).eraseFromDisk();
210 _nativeObjectFile = BuffPtr.take();
213 sys::Path(_nativeObjectPath).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) {
226 std::string TripleStr = _linker.getModule()->getTargetTriple();
227 if (TripleStr.empty())
228 TripleStr = sys::getDefaultTargetTriple();
229 llvm::Triple Triple(TripleStr);
231 // create target machine from info for merged modules
232 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
236 // The relocation model is actually a static member of TargetMachine and
237 // needs to be set before the TargetMachine is instantiated.
238 Reloc::Model RelocModel = Reloc::Default;
239 switch (_codeModel) {
240 case LTO_CODEGEN_PIC_MODEL_STATIC:
241 RelocModel = Reloc::Static;
243 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
244 RelocModel = Reloc::PIC_;
246 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
247 RelocModel = Reloc::DynamicNoPIC;
251 // construct LTOModule, hand over ownership of module and target
252 SubtargetFeatures Features;
253 Features.getDefaultSubtargetFeatures(Triple);
254 std::string FeatureStr = Features.getString();
255 // Set a default CPU for Darwin triples.
256 if (_mCpu.empty() && Triple.isOSDarwin()) {
257 if (Triple.getArch() == llvm::Triple::x86_64)
259 else if (Triple.getArch() == llvm::Triple::x86)
262 TargetOptions Options;
263 LTOModule::getTargetOptions(Options);
264 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
265 RelocModel, CodeModel::Default,
266 CodeGenOpt::Aggressive);
270 void LTOCodeGenerator::
271 applyRestriction(GlobalValue &GV,
272 std::vector<const char*> &mustPreserveList,
273 SmallPtrSet<GlobalValue*, 8> &asmUsed,
275 SmallString<64> Buffer;
276 mangler.getNameWithPrefix(Buffer, &GV, false);
278 if (GV.isDeclaration())
280 if (_mustPreserveSymbols.count(Buffer))
281 mustPreserveList.push_back(GV.getName().data());
282 if (_asmUndefinedRefs.count(Buffer))
286 static void findUsedValues(GlobalVariable *LLVMUsed,
287 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
288 if (LLVMUsed == 0) return;
290 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
291 if (Inits == 0) return;
293 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
294 if (GlobalValue *GV =
295 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
296 UsedValues.insert(GV);
299 void LTOCodeGenerator::applyScopeRestrictions() {
300 if (_scopeRestrictionsDone) return;
301 Module *mergedModule = _linker.getModule();
303 // Start off with a verification pass.
305 passes.add(createVerifierPass());
307 // mark which symbols can not be internalized
308 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
309 Mangler mangler(Context, *_target->getDataLayout());
310 std::vector<const char*> mustPreserveList;
311 SmallPtrSet<GlobalValue*, 8> asmUsed;
313 for (Module::iterator f = mergedModule->begin(),
314 e = mergedModule->end(); f != e; ++f)
315 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
316 for (Module::global_iterator v = mergedModule->global_begin(),
317 e = mergedModule->global_end(); v != e; ++v)
318 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
319 for (Module::alias_iterator a = mergedModule->alias_begin(),
320 e = mergedModule->alias_end(); a != e; ++a)
321 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
323 GlobalVariable *LLVMCompilerUsed =
324 mergedModule->getGlobalVariable("llvm.compiler.used");
325 findUsedValues(LLVMCompilerUsed, asmUsed);
326 if (LLVMCompilerUsed)
327 LLVMCompilerUsed->eraseFromParent();
329 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
330 std::vector<Constant*> asmUsed2;
331 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
332 e = asmUsed.end(); i !=e; ++i) {
333 GlobalValue *GV = *i;
334 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
335 asmUsed2.push_back(c);
338 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
340 new llvm::GlobalVariable(*mergedModule, ATy, false,
341 llvm::GlobalValue::AppendingLinkage,
342 llvm::ConstantArray::get(ATy, asmUsed2),
343 "llvm.compiler.used");
345 LLVMCompilerUsed->setSection("llvm.metadata");
347 passes.add(createInternalizePass(mustPreserveList));
349 // apply scope restrictions
350 passes.run(*mergedModule);
352 _scopeRestrictionsDone = true;
355 /// Optimize merged modules using various IPO passes
356 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
357 std::string &errMsg) {
358 if (this->determineTarget(errMsg))
361 Module* mergedModule = _linker.getModule();
363 // if options were requested, set them
364 if (!_codegenOptions.empty())
365 cl::ParseCommandLineOptions(_codegenOptions.size(),
366 const_cast<char **>(&_codegenOptions[0]));
368 // mark which symbols can not be internalized
369 this->applyScopeRestrictions();
371 // Instantiate the pass manager to organize the passes.
374 // Start off with a verification pass.
375 passes.add(createVerifierPass());
377 // Add an appropriate DataLayout instance for this module...
378 passes.add(new DataLayout(*_target->getDataLayout()));
379 _target->addAnalysisPasses(passes);
381 // Enabling internalize here would use its AllButMain variant. It
382 // keeps only main if it exists and does nothing for libraries. Instead
383 // we create the pass ourselves with the symbol list provided by the linker.
385 PassManagerBuilder().populateLTOPassManager(passes,
386 /*Internalize=*/false,
391 // Make sure everything is still good.
392 passes.add(createVerifierPass());
394 PassManager codeGenPasses;
396 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
397 _target->addAnalysisPasses(codeGenPasses);
399 formatted_raw_ostream Out(out);
401 // If the bitcode files contain ARC code and were compiled with optimization,
402 // the ObjCARCContractPass must be run, so do it unconditionally here.
403 codeGenPasses.add(createObjCARCContractPass());
405 if (_target->addPassesToEmitFile(codeGenPasses, Out,
406 TargetMachine::CGFT_ObjectFile)) {
407 errMsg = "target file type not supported";
411 // Run our queue of passes all at once now, efficiently.
412 passes.run(*mergedModule);
414 // Run the code generator, and write assembly file
415 codeGenPasses.run(*mergedModule);
417 return false; // success
420 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
422 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. Lazily add
427 if (_codegenOptions.empty())
428 _codegenOptions.push_back(strdup("libLTO"));
429 _codegenOptions.push_back(strdup(o.first.str().c_str()));