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/Signals.h"
39 #include "llvm/Target/SubtargetFeature.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Config/config.h"
59 static cl::opt<bool> DisableInline("disable-inlining",
60 cl::desc("Do not run the inliner pass"));
63 const char* LTOCodeGenerator::getVersionString()
65 #ifdef LLVM_VERSION_INFO
66 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 return PACKAGE_NAME " version " PACKAGE_VERSION;
73 LTOCodeGenerator::LTOCodeGenerator()
74 : _context(getGlobalContext()),
75 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
76 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
77 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
78 _nativeObjectFile(NULL), _gccPath(NULL), _assemblerPath(NULL)
80 InitializeAllTargets();
81 InitializeAllAsmPrinters();
84 LTOCodeGenerator::~LTOCodeGenerator()
87 delete _nativeObjectFile;
92 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
94 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
98 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
101 case LTO_DEBUG_MODEL_NONE:
102 _emitDwarfDebugInfo = false;
105 case LTO_DEBUG_MODEL_DWARF:
106 _emitDwarfDebugInfo = true;
109 errMsg = "unknown debug format";
114 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
118 case LTO_CODEGEN_PIC_MODEL_STATIC:
119 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
124 errMsg = "unknown pic model";
128 void LTOCodeGenerator::setGccPath(const char* path)
132 _gccPath = new sys::Path(path);
135 void LTOCodeGenerator::setAssemblerPath(const char* path)
137 if ( _assemblerPath )
138 delete _assemblerPath;
139 _assemblerPath = new sys::Path(path);
142 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
144 _mustPreserveSymbols[sym] = 1;
148 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
150 if ( this->determineTarget(errMsg) )
153 // mark which symbols can not be internalized
154 this->applyScopeRestrictions();
156 // create output file
157 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
159 errMsg = "could not open bitcode file for writing: ";
164 // write bitcode to it
165 WriteBitcodeToFile(_linker.getModule(), out);
167 errMsg = "could not write bitcode file: ";
176 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
178 // make unique temp .s file to put generated assembly code
179 sys::Path uniqueAsmPath("lto-llvm.s");
180 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
182 sys::RemoveFileOnSignal(uniqueAsmPath);
184 // generate assembly code
185 bool genResult = false;
187 raw_fd_ostream asmFD(raw_fd_ostream(uniqueAsmPath.c_str(),
188 /*Binary=*/false, /*Force=*/true,
190 formatted_raw_ostream asmFile(asmFD);
193 genResult = this->generateAssemblyCode(asmFile, errMsg);
196 if ( uniqueAsmPath.exists() )
197 uniqueAsmPath.eraseFromDisk();
201 // make unique temp .o file to put generated object file
202 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
203 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
204 if ( uniqueAsmPath.exists() )
205 uniqueAsmPath.eraseFromDisk();
208 sys::RemoveFileOnSignal(uniqueObjPath);
210 // assemble the assembly code
211 const std::string& uniqueObjStr = uniqueObjPath.toString();
212 bool asmResult = this->assemble(uniqueAsmPath.toString(),
213 uniqueObjStr, errMsg);
215 // remove old buffer if compile() called twice
216 delete _nativeObjectFile;
218 // read .o file into memory buffer
219 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
223 uniqueAsmPath.eraseFromDisk();
224 uniqueObjPath.eraseFromDisk();
226 // return buffer, unless error
227 if ( _nativeObjectFile == NULL )
229 *length = _nativeObjectFile->getBufferSize();
230 return _nativeObjectFile->getBufferStart();
234 bool LTOCodeGenerator::assemble(const std::string& asmPath,
235 const std::string& objPath, std::string& errMsg)
238 bool needsCompilerOptions = true;
239 if ( _assemblerPath ) {
240 tool = *_assemblerPath;
241 needsCompilerOptions = false;
243 else if ( _gccPath ) {
246 // find compiler driver
247 tool = sys::Program::FindProgramByName("gcc");
248 if ( tool.isEmpty() ) {
249 errMsg = "can't locate gcc";
254 // build argument list
255 std::vector<const char*> args;
256 std::string targetTriple = _linker.getModule()->getTargetTriple();
257 args.push_back(tool.c_str());
258 if ( targetTriple.find("darwin") != std::string::npos ) {
259 // darwin specific command line options
260 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
261 args.push_back("-arch");
262 args.push_back("i386");
264 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
265 args.push_back("-arch");
266 args.push_back("x86_64");
268 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
269 args.push_back("-arch");
270 args.push_back("ppc");
272 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
273 args.push_back("-arch");
274 args.push_back("ppc64");
276 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
277 args.push_back("-arch");
278 args.push_back("arm");
280 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
281 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
282 args.push_back("-arch");
283 args.push_back("armv4t");
285 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
286 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
287 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
288 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
289 args.push_back("-arch");
290 args.push_back("armv5");
292 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
293 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
294 args.push_back("-arch");
295 args.push_back("armv6");
297 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
298 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
299 args.push_back("-arch");
300 args.push_back("armv7");
302 // add -static to assembler command line when code model requires
303 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
304 args.push_back("-static");
306 if ( needsCompilerOptions ) {
307 args.push_back("-c");
308 args.push_back("-x");
309 args.push_back("assembler");
311 args.push_back("-o");
312 args.push_back(objPath.c_str());
313 args.push_back(asmPath.c_str());
317 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
318 errMsg = "error in assembly";
321 return false; // success
326 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
328 if ( _target == NULL ) {
329 // create target machine from info for merged modules
330 Module* mergedModule = _linker.getModule();
331 const Target *march =
332 TargetRegistry::lookupTarget(mergedModule->getTargetTriple(),
333 /*FallbackToHost=*/true,
334 /*RequireJIT=*/false,
339 // The relocation model is actually a static member of TargetMachine
340 // and needs to be set before the TargetMachine is instantiated.
341 switch( _codeModel ) {
342 case LTO_CODEGEN_PIC_MODEL_STATIC:
343 TargetMachine::setRelocationModel(Reloc::Static);
345 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
346 TargetMachine::setRelocationModel(Reloc::PIC_);
348 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
349 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
353 // construct LTModule, hand over ownership of module and target
354 std::string FeatureStr =
355 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
356 _target = march->createTargetMachine(*mergedModule, FeatureStr.c_str());
361 void LTOCodeGenerator::applyScopeRestrictions()
363 if ( !_scopeRestrictionsDone ) {
364 Module* mergedModule = _linker.getModule();
366 // Start off with a verification pass.
368 passes.add(createVerifierPass());
370 // mark which symbols can not be internalized
371 if ( !_mustPreserveSymbols.empty() ) {
372 Mangler mangler(*mergedModule,
373 _target->getTargetAsmInfo()->getGlobalPrefix());
374 std::vector<const char*> mustPreserveList;
375 for (Module::iterator f = mergedModule->begin(),
376 e = mergedModule->end(); f != e; ++f) {
377 if ( !f->isDeclaration()
378 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
379 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
381 for (Module::global_iterator v = mergedModule->global_begin(),
382 e = mergedModule->global_end(); v != e; ++v) {
383 if ( !v->isDeclaration()
384 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
385 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
387 passes.add(createInternalizePass(mustPreserveList));
389 // apply scope restrictions
390 passes.run(*mergedModule);
392 _scopeRestrictionsDone = true;
396 /// Optimize merged modules using various IPO passes
397 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
400 if ( this->determineTarget(errMsg) )
403 // mark which symbols can not be internalized
404 this->applyScopeRestrictions();
406 Module* mergedModule = _linker.getModule();
408 // If target supports exception handling then enable it now.
409 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
410 llvm::ExceptionHandling = true;
412 // if options were requested, set them
413 if ( !_codegenOptions.empty() )
414 cl::ParseCommandLineOptions(_codegenOptions.size(),
415 (char**)&_codegenOptions[0]);
417 // Instantiate the pass manager to organize the passes.
420 // Start off with a verification pass.
421 passes.add(createVerifierPass());
423 // Add an appropriate TargetData instance for this module...
424 passes.add(new TargetData(*_target->getTargetData()));
426 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
427 /*VerifyEach=*/ false);
429 // Make sure everything is still good.
430 passes.add(createVerifierPass());
432 FunctionPassManager* codeGenPasses =
433 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
435 codeGenPasses->add(new TargetData(*_target->getTargetData()));
437 ObjectCodeEmitter* oce = NULL;
439 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
440 TargetMachine::AssemblyFile,
441 CodeGenOpt::Aggressive)) {
442 case FileModel::MachOFile:
443 oce = AddMachOWriter(*codeGenPasses, out, *_target);
445 case FileModel::ElfFile:
446 oce = AddELFWriter(*codeGenPasses, out, *_target);
448 case FileModel::AsmFile:
450 case FileModel::Error:
451 case FileModel::None:
452 errMsg = "target file type not supported";
456 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
457 CodeGenOpt::Aggressive)) {
458 errMsg = "target does not support generation of this file type";
462 // Run our queue of passes all at once now, efficiently.
463 passes.run(*mergedModule);
465 // Run the code generator, and write assembly file
466 codeGenPasses->doInitialization();
468 for (Module::iterator
469 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
470 if (!it->isDeclaration())
471 codeGenPasses->run(*it);
473 codeGenPasses->doFinalization();
477 return false; // success
481 /// Optimize merged modules using various IPO passes
482 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
484 std::string ops(options);
485 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
486 // ParseCommandLineOptions() expects argv[0] to be program name.
488 if ( _codegenOptions.empty() )
489 _codegenOptions.push_back("libLTO");
490 _codegenOptions.push_back(strdup(o.c_str()));