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 "LTOModule.h"
16 #include "LTOCodeGenerator.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Linker.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/Passes.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include "llvm/Bitcode/ReaderWriter.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Target/SubtargetFeature.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Target/TargetSelect.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Config/config.h"
57 static cl::opt<bool> DisableInline("disable-inlining",
58 cl::desc("Do not run the inliner pass"));
61 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;
71 LTOCodeGenerator::LTOCodeGenerator()
72 : _context(getGlobalContext()),
73 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
74 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
75 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
76 _nativeObjectFile(NULL), _assemblerPath(NULL)
78 InitializeAllTargets();
79 InitializeAllAsmPrinters();
82 LTOCodeGenerator::~LTOCodeGenerator()
85 delete _nativeObjectFile;
90 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
92 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
96 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
99 case LTO_DEBUG_MODEL_NONE:
100 _emitDwarfDebugInfo = false;
103 case LTO_DEBUG_MODEL_DWARF:
104 _emitDwarfDebugInfo = true;
107 errMsg = "unknown debug format";
112 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
116 case LTO_CODEGEN_PIC_MODEL_STATIC:
117 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
118 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
122 errMsg = "unknown pic model";
126 void LTOCodeGenerator::setAssemblerPath(const char* path)
128 if ( _assemblerPath )
129 delete _assemblerPath;
130 _assemblerPath = new sys::Path(path);
133 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
135 _mustPreserveSymbols[sym] = 1;
139 bool LTOCodeGenerator::writeMergedModules(const char *path,
140 std::string &errMsg) {
141 if (determineTarget(errMsg))
144 // mark which symbols can not be internalized
145 applyScopeRestrictions();
147 // create output file
149 raw_fd_ostream Out(path, ErrInfo,
150 raw_fd_ostream::F_Force|raw_fd_ostream::F_Binary);
151 if (!ErrInfo.empty()) {
152 errMsg = "could not open bitcode file for writing: ";
157 // write bitcode to it
158 WriteBitcodeToFile(_linker.getModule(), Out);
160 if (Out.has_error()) {
161 errMsg = "could not write bitcode file: ";
170 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
172 // make unique temp .s file to put generated assembly code
173 sys::Path uniqueAsmPath("lto-llvm.s");
174 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
176 sys::RemoveFileOnSignal(uniqueAsmPath);
178 // generate assembly code
179 bool genResult = false;
181 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg,
182 raw_fd_ostream::F_Force);
183 formatted_raw_ostream asmFile(asmFD);
186 genResult = this->generateAssemblyCode(asmFile, errMsg);
189 if ( uniqueAsmPath.exists() )
190 uniqueAsmPath.eraseFromDisk();
194 // make unique temp .o file to put generated object file
195 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
196 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
197 if ( uniqueAsmPath.exists() )
198 uniqueAsmPath.eraseFromDisk();
201 sys::RemoveFileOnSignal(uniqueObjPath);
203 // assemble the assembly code
204 const std::string& uniqueObjStr = uniqueObjPath.toString();
205 bool asmResult = this->assemble(uniqueAsmPath.toString(),
206 uniqueObjStr, errMsg);
208 // remove old buffer if compile() called twice
209 delete _nativeObjectFile;
211 // read .o file into memory buffer
212 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
216 uniqueAsmPath.eraseFromDisk();
217 uniqueObjPath.eraseFromDisk();
219 // return buffer, unless error
220 if ( _nativeObjectFile == NULL )
222 *length = _nativeObjectFile->getBufferSize();
223 return _nativeObjectFile->getBufferStart();
227 bool LTOCodeGenerator::assemble(const std::string& asmPath,
228 const std::string& objPath, std::string& errMsg)
231 bool needsCompilerOptions = true;
232 if ( _assemblerPath ) {
233 tool = *_assemblerPath;
234 needsCompilerOptions = false;
236 // find compiler driver
237 tool = sys::Program::FindProgramByName("gcc");
238 if ( tool.isEmpty() ) {
239 errMsg = "can't locate gcc";
244 // build argument list
245 std::vector<const char*> args;
246 std::string targetTriple = _linker.getModule()->getTargetTriple();
247 args.push_back(tool.c_str());
248 if ( targetTriple.find("darwin") != std::string::npos ) {
249 // darwin specific command line options
250 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
251 args.push_back("-arch");
252 args.push_back("i386");
254 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
255 args.push_back("-arch");
256 args.push_back("x86_64");
258 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
259 args.push_back("-arch");
260 args.push_back("ppc");
262 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
263 args.push_back("-arch");
264 args.push_back("ppc64");
266 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
267 args.push_back("-arch");
268 args.push_back("arm");
270 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
271 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
272 args.push_back("-arch");
273 args.push_back("armv4t");
275 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
276 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
277 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
278 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
279 args.push_back("-arch");
280 args.push_back("armv5");
282 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
283 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
284 args.push_back("-arch");
285 args.push_back("armv6");
287 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
288 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
289 args.push_back("-arch");
290 args.push_back("armv7");
292 // add -static to assembler command line when code model requires
293 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
294 args.push_back("-static");
296 if ( needsCompilerOptions ) {
297 args.push_back("-c");
298 args.push_back("-x");
299 args.push_back("assembler");
301 args.push_back("-o");
302 args.push_back(objPath.c_str());
303 args.push_back(asmPath.c_str());
307 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
308 errMsg = "error in assembly";
311 return false; // success
316 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
318 if ( _target == NULL ) {
319 std::string Triple = _linker.getModule()->getTargetTriple();
321 Triple = sys::getHostTriple();
323 // create target machine from info for merged modules
324 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
328 // The relocation model is actually a static member of TargetMachine
329 // and needs to be set before the TargetMachine is instantiated.
330 switch( _codeModel ) {
331 case LTO_CODEGEN_PIC_MODEL_STATIC:
332 TargetMachine::setRelocationModel(Reloc::Static);
334 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
335 TargetMachine::setRelocationModel(Reloc::PIC_);
337 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
338 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
342 // construct LTModule, hand over ownership of module and target
343 std::string FeatureStr = getFeatureString(Triple.c_str());
344 _target = march->createTargetMachine(Triple, FeatureStr);
349 void LTOCodeGenerator::applyScopeRestrictions()
351 if ( !_scopeRestrictionsDone ) {
352 Module* mergedModule = _linker.getModule();
354 // Start off with a verification pass.
356 passes.add(createVerifierPass());
358 // mark which symbols can not be internalized
359 if ( !_mustPreserveSymbols.empty() ) {
360 Mangler mangler(*mergedModule,
361 _target->getMCAsmInfo()->getGlobalPrefix());
362 std::vector<const char*> mustPreserveList;
363 for (Module::iterator f = mergedModule->begin(),
364 e = mergedModule->end(); f != e; ++f) {
365 if ( !f->isDeclaration()
366 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
367 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
369 for (Module::global_iterator v = mergedModule->global_begin(),
370 e = mergedModule->global_end(); v != e; ++v) {
371 if ( !v->isDeclaration()
372 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
373 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
375 passes.add(createInternalizePass(mustPreserveList));
377 // apply scope restrictions
378 passes.run(*mergedModule);
380 _scopeRestrictionsDone = true;
384 /// Optimize merged modules using various IPO passes
385 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
388 if ( this->determineTarget(errMsg) )
391 // mark which symbols can not be internalized
392 this->applyScopeRestrictions();
394 Module* mergedModule = _linker.getModule();
396 // If target supports exception handling then enable it now.
397 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
398 case ExceptionHandling::Dwarf:
399 llvm::DwarfExceptionHandling = true;
401 case ExceptionHandling::SjLj:
402 llvm::SjLjExceptionHandling = true;
404 case ExceptionHandling::None:
407 assert (0 && "Unknown exception handling model!");
410 // if options were requested, set them
411 if ( !_codegenOptions.empty() )
412 cl::ParseCommandLineOptions(_codegenOptions.size(),
413 (char**)&_codegenOptions[0]);
415 // Instantiate the pass manager to organize the passes.
418 // Start off with a verification pass.
419 passes.add(createVerifierPass());
421 // Add an appropriate TargetData instance for this module...
422 passes.add(new TargetData(*_target->getTargetData()));
424 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
425 /*VerifyEach=*/ false);
427 // Make sure everything is still good.
428 passes.add(createVerifierPass());
430 FunctionPassManager* codeGenPasses =
431 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
433 codeGenPasses->add(new TargetData(*_target->getTargetData()));
435 ObjectCodeEmitter* oce = NULL;
437 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
438 TargetMachine::AssemblyFile,
439 CodeGenOpt::Aggressive)) {
440 case FileModel::MachOFile:
441 oce = AddMachOWriter(*codeGenPasses, out, *_target);
443 case FileModel::ElfFile:
444 oce = AddELFWriter(*codeGenPasses, out, *_target);
446 case FileModel::AsmFile:
448 case FileModel::Error:
449 case FileModel::None:
450 errMsg = "target file type not supported";
454 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
455 CodeGenOpt::Aggressive)) {
456 errMsg = "target does not support generation of this file type";
460 // Run our queue of passes all at once now, efficiently.
461 passes.run(*mergedModule);
463 // Run the code generator, and write assembly file
464 codeGenPasses->doInitialization();
466 for (Module::iterator
467 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
468 if (!it->isDeclaration())
469 codeGenPasses->run(*it);
471 codeGenPasses->doFinalization();
475 return false; // success
479 /// Optimize merged modules using various IPO passes
480 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
482 std::string ops(options);
483 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
484 // ParseCommandLineOptions() expects argv[0] to be program name.
486 if ( _codegenOptions.empty() )
487 _codegenOptions.push_back("libLTO");
488 _codegenOptions.push_back(strdup(o.c_str()));