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/FileSystem.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/Mangler.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/ObjCARC.h"
52 DisableOpt("disable-opt", cl::init(false),
53 cl::desc("Do not run any optimization passes"));
56 DisableInline("disable-inlining", cl::init(false),
57 cl::desc("Do not run the inliner pass"));
60 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
61 cl::desc("Do not run the GVN load PRE pass"));
63 const char* LTOCodeGenerator::getVersionString() {
64 #ifdef LLVM_VERSION_INFO
65 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 return PACKAGE_NAME " version " PACKAGE_VERSION;
71 LTOCodeGenerator::LTOCodeGenerator()
72 : _context(getGlobalContext()),
73 _linker(new Module("ld-temp.o", _context)), _target(NULL),
74 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
75 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
76 _nativeObjectFile(NULL) {
77 InitializeAllTargets();
78 InitializeAllTargetMCs();
79 InitializeAllAsmPrinters();
82 LTOCodeGenerator::~LTOCodeGenerator() {
84 delete _nativeObjectFile;
85 delete _linker.getModule();
87 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
88 E = _codegenOptions.end(); I != E; ++I)
92 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
93 bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
95 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
96 for (int i = 0, e = undefs.size(); i != e; ++i)
97 _asmUndefinedRefs[undefs[i]] = 1;
102 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
103 std::string& errMsg) {
105 case LTO_DEBUG_MODEL_NONE:
106 _emitDwarfDebugInfo = false;
109 case LTO_DEBUG_MODEL_DWARF:
110 _emitDwarfDebugInfo = true;
113 llvm_unreachable("Unknown debug format!");
116 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
117 std::string& errMsg) {
119 case LTO_CODEGEN_PIC_MODEL_STATIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
125 llvm_unreachable("Unknown PIC model!");
128 bool LTOCodeGenerator::writeMergedModules(const char *path,
129 std::string &errMsg) {
130 if (determineTarget(errMsg))
133 // Run the verifier on the merged modules.
135 passes.add(createVerifierPass());
136 passes.run(*_linker.getModule());
138 // create output file
140 tool_output_file Out(path, ErrInfo,
141 raw_fd_ostream::F_Binary);
142 if (!ErrInfo.empty()) {
143 errMsg = "could not open bitcode file for writing: ";
148 // write bitcode to it
149 WriteBitcodeToFile(_linker.getModule(), Out.os());
152 if (Out.os().has_error()) {
153 errMsg = "could not write bitcode file: ";
155 Out.os().clear_error();
163 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
164 // make unique temp .o file to put generated object file
165 SmallString<128> Filename;
167 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
169 errMsg = EC.message();
173 // generate object file
174 tool_output_file objFile(Filename.c_str(), FD);
176 bool genResult = generateObjectFile(objFile.os(), errMsg);
177 objFile.os().close();
178 if (objFile.os().has_error()) {
179 objFile.os().clear_error();
180 sys::fs::remove(Twine(Filename));
186 sys::fs::remove(Twine(Filename));
190 _nativeObjectPath = Filename.c_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::fs::remove(_nativeObjectPath);
210 _nativeObjectFile = BuffPtr.take();
213 sys::fs::remove(_nativeObjectPath);
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 // if options were requested, set them
227 if (!_codegenOptions.empty())
228 cl::ParseCommandLineOptions(_codegenOptions.size(),
229 const_cast<char **>(&_codegenOptions[0]));
231 std::string TripleStr = _linker.getModule()->getTargetTriple();
232 if (TripleStr.empty())
233 TripleStr = sys::getDefaultTargetTriple();
234 llvm::Triple Triple(TripleStr);
236 // create target machine from info for merged modules
237 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
241 // The relocation model is actually a static member of TargetMachine and
242 // needs to be set before the TargetMachine is instantiated.
243 Reloc::Model RelocModel = Reloc::Default;
244 switch (_codeModel) {
245 case LTO_CODEGEN_PIC_MODEL_STATIC:
246 RelocModel = Reloc::Static;
248 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
249 RelocModel = Reloc::PIC_;
251 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
252 RelocModel = Reloc::DynamicNoPIC;
256 // construct LTOModule, hand over ownership of module and target
257 SubtargetFeatures Features;
258 Features.getDefaultSubtargetFeatures(Triple);
259 std::string FeatureStr = Features.getString();
260 // Set a default CPU for Darwin triples.
261 if (_mCpu.empty() && Triple.isOSDarwin()) {
262 if (Triple.getArch() == llvm::Triple::x86_64)
264 else if (Triple.getArch() == llvm::Triple::x86)
267 TargetOptions Options;
268 LTOModule::getTargetOptions(Options);
269 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
270 RelocModel, CodeModel::Default,
271 CodeGenOpt::Aggressive);
275 void LTOCodeGenerator::
276 applyRestriction(GlobalValue &GV,
277 std::vector<const char*> &mustPreserveList,
278 SmallPtrSet<GlobalValue*, 8> &asmUsed,
280 SmallString<64> Buffer;
281 mangler.getNameWithPrefix(Buffer, &GV, false);
283 if (GV.isDeclaration())
285 if (_mustPreserveSymbols.count(Buffer))
286 mustPreserveList.push_back(GV.getName().data());
287 if (_asmUndefinedRefs.count(Buffer))
291 static void findUsedValues(GlobalVariable *LLVMUsed,
292 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
293 if (LLVMUsed == 0) return;
295 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
296 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
297 if (GlobalValue *GV =
298 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
299 UsedValues.insert(GV);
302 void LTOCodeGenerator::applyScopeRestrictions() {
303 if (_scopeRestrictionsDone) return;
304 Module *mergedModule = _linker.getModule();
306 // Start off with a verification pass.
308 passes.add(createVerifierPass());
310 // mark which symbols can not be internalized
311 MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
312 Mangler mangler(Context, _target);
313 std::vector<const char*> mustPreserveList;
314 SmallPtrSet<GlobalValue*, 8> asmUsed;
316 for (Module::iterator f = mergedModule->begin(),
317 e = mergedModule->end(); f != e; ++f)
318 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
319 for (Module::global_iterator v = mergedModule->global_begin(),
320 e = mergedModule->global_end(); v != e; ++v)
321 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
322 for (Module::alias_iterator a = mergedModule->alias_begin(),
323 e = mergedModule->alias_end(); a != e; ++a)
324 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
326 GlobalVariable *LLVMCompilerUsed =
327 mergedModule->getGlobalVariable("llvm.compiler.used");
328 findUsedValues(LLVMCompilerUsed, asmUsed);
329 if (LLVMCompilerUsed)
330 LLVMCompilerUsed->eraseFromParent();
332 if (!asmUsed.empty()) {
333 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
334 std::vector<Constant*> asmUsed2;
335 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
336 e = asmUsed.end(); i !=e; ++i) {
337 GlobalValue *GV = *i;
338 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
339 asmUsed2.push_back(c);
342 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
344 new llvm::GlobalVariable(*mergedModule, ATy, false,
345 llvm::GlobalValue::AppendingLinkage,
346 llvm::ConstantArray::get(ATy, asmUsed2),
347 "llvm.compiler.used");
349 LLVMCompilerUsed->setSection("llvm.metadata");
352 passes.add(createInternalizePass(mustPreserveList));
354 // apply scope restrictions
355 passes.run(*mergedModule);
357 _scopeRestrictionsDone = true;
360 /// Optimize merged modules using various IPO passes
361 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
362 std::string &errMsg) {
363 if (this->determineTarget(errMsg))
366 Module* mergedModule = _linker.getModule();
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,
390 // Make sure everything is still good.
391 passes.add(createVerifierPass());
393 PassManager codeGenPasses;
395 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
396 _target->addAnalysisPasses(codeGenPasses);
398 formatted_raw_ostream Out(out);
400 // If the bitcode files contain ARC code and were compiled with optimization,
401 // the ObjCARCContractPass must be run, so do it unconditionally here.
402 codeGenPasses.add(createObjCARCContractPass());
404 if (_target->addPassesToEmitFile(codeGenPasses, Out,
405 TargetMachine::CGFT_ObjectFile)) {
406 errMsg = "target file type not supported";
410 // Run our queue of passes all at once now, efficiently.
411 passes.run(*mergedModule);
413 // Run the code generator, and write assembly file
414 codeGenPasses.run(*mergedModule);
416 return false; // success
419 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
421 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
422 for (std::pair<StringRef, StringRef> o = getToken(options);
423 !o.first.empty(); o = getToken(o.second)) {
424 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
426 if (_codegenOptions.empty())
427 _codegenOptions.push_back(strdup("libLTO"));
428 _codegenOptions.push_back(strdup(o.first.str().c_str()));