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();
85 LTOCodeGenerator::~LTOCodeGenerator()
88 delete _nativeObjectFile;
93 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
95 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
99 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
102 case LTO_DEBUG_MODEL_NONE:
103 _emitDwarfDebugInfo = false;
106 case LTO_DEBUG_MODEL_DWARF:
107 _emitDwarfDebugInfo = true;
110 errMsg = "unknown debug format";
115 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
119 case LTO_CODEGEN_PIC_MODEL_STATIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
125 errMsg = "unknown pic model";
129 void LTOCodeGenerator::setGccPath(const char* path)
133 _gccPath = new sys::Path(path);
136 void LTOCodeGenerator::setAssemblerPath(const char* path)
138 if ( _assemblerPath )
139 delete _assemblerPath;
140 _assemblerPath = new sys::Path(path);
143 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
145 _mustPreserveSymbols[sym] = 1;
149 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
151 if ( this->determineTarget(errMsg) )
154 // mark which symbols can not be internalized
155 this->applyScopeRestrictions();
157 // create output file
158 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
160 errMsg = "could not open bitcode file for writing: ";
165 // write bitcode to it
166 WriteBitcodeToFile(_linker.getModule(), out);
168 errMsg = "could not write bitcode file: ";
177 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
179 // make unique temp .s file to put generated assembly code
180 sys::Path uniqueAsmPath("lto-llvm.s");
181 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
183 sys::RemoveFileOnSignal(uniqueAsmPath);
185 // generate assembly code
186 bool genResult = false;
188 raw_fd_ostream asmFD(raw_fd_ostream(uniqueAsmPath.c_str(),
189 /*Binary=*/false, /*Force=*/true,
191 formatted_raw_ostream asmFile(asmFD);
194 genResult = this->generateAssemblyCode(asmFile, errMsg);
197 if ( uniqueAsmPath.exists() )
198 uniqueAsmPath.eraseFromDisk();
202 // make unique temp .o file to put generated object file
203 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
204 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
205 if ( uniqueAsmPath.exists() )
206 uniqueAsmPath.eraseFromDisk();
209 sys::RemoveFileOnSignal(uniqueObjPath);
211 // assemble the assembly code
212 const std::string& uniqueObjStr = uniqueObjPath.toString();
213 bool asmResult = this->assemble(uniqueAsmPath.toString(),
214 uniqueObjStr, errMsg);
216 // remove old buffer if compile() called twice
217 delete _nativeObjectFile;
219 // read .o file into memory buffer
220 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
224 uniqueAsmPath.eraseFromDisk();
225 uniqueObjPath.eraseFromDisk();
227 // return buffer, unless error
228 if ( _nativeObjectFile == NULL )
230 *length = _nativeObjectFile->getBufferSize();
231 return _nativeObjectFile->getBufferStart();
235 bool LTOCodeGenerator::assemble(const std::string& asmPath,
236 const std::string& objPath, std::string& errMsg)
239 bool needsCompilerOptions = true;
240 if ( _assemblerPath ) {
241 tool = *_assemblerPath;
242 needsCompilerOptions = false;
244 else if ( _gccPath ) {
247 // find compiler driver
248 tool = sys::Program::FindProgramByName("gcc");
249 if ( tool.isEmpty() ) {
250 errMsg = "can't locate gcc";
255 // build argument list
256 std::vector<const char*> args;
257 std::string targetTriple = _linker.getModule()->getTargetTriple();
258 args.push_back(tool.c_str());
259 if ( targetTriple.find("darwin") != std::string::npos ) {
260 // darwin specific command line options
261 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
262 args.push_back("-arch");
263 args.push_back("i386");
265 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
266 args.push_back("-arch");
267 args.push_back("x86_64");
269 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
270 args.push_back("-arch");
271 args.push_back("ppc");
273 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
274 args.push_back("-arch");
275 args.push_back("ppc64");
277 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
278 args.push_back("-arch");
279 args.push_back("arm");
281 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
282 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
283 args.push_back("-arch");
284 args.push_back("armv4t");
286 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
287 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
288 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
289 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
290 args.push_back("-arch");
291 args.push_back("armv5");
293 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
294 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
295 args.push_back("-arch");
296 args.push_back("armv6");
298 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
299 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
300 args.push_back("-arch");
301 args.push_back("armv7");
303 // add -static to assembler command line when code model requires
304 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
305 args.push_back("-static");
307 if ( needsCompilerOptions ) {
308 args.push_back("-c");
309 args.push_back("-x");
310 args.push_back("assembler");
312 args.push_back("-o");
313 args.push_back(objPath.c_str());
314 args.push_back(asmPath.c_str());
318 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
319 errMsg = "error in assembly";
322 return false; // success
327 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
329 if ( _target == NULL ) {
330 // create target machine from info for merged modules
331 Module* mergedModule = _linker.getModule();
332 const Target *march =
333 TargetRegistry::getClosestStaticTargetForModule(*mergedModule,
338 // The relocation model is actually a static member of TargetMachine
339 // and needs to be set before the TargetMachine is instantiated.
340 switch( _codeModel ) {
341 case LTO_CODEGEN_PIC_MODEL_STATIC:
342 TargetMachine::setRelocationModel(Reloc::Static);
344 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
345 TargetMachine::setRelocationModel(Reloc::PIC_);
347 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
348 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
352 // construct LTModule, hand over ownership of module and target
353 std::string FeatureStr =
354 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
355 _target = march->createTargetMachine(*mergedModule, FeatureStr.c_str());
360 void LTOCodeGenerator::applyScopeRestrictions()
362 if ( !_scopeRestrictionsDone ) {
363 Module* mergedModule = _linker.getModule();
365 // Start off with a verification pass.
367 passes.add(createVerifierPass());
369 // mark which symbols can not be internalized
370 if ( !_mustPreserveSymbols.empty() ) {
371 Mangler mangler(*mergedModule,
372 _target->getTargetAsmInfo()->getGlobalPrefix());
373 std::vector<const char*> mustPreserveList;
374 for (Module::iterator f = mergedModule->begin(),
375 e = mergedModule->end(); f != e; ++f) {
376 if ( !f->isDeclaration()
377 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
378 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
380 for (Module::global_iterator v = mergedModule->global_begin(),
381 e = mergedModule->global_end(); v != e; ++v) {
382 if ( !v->isDeclaration()
383 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
384 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
386 passes.add(createInternalizePass(mustPreserveList));
388 // apply scope restrictions
389 passes.run(*mergedModule);
391 _scopeRestrictionsDone = true;
395 /// Optimize merged modules using various IPO passes
396 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
399 if ( this->determineTarget(errMsg) )
402 // mark which symbols can not be internalized
403 this->applyScopeRestrictions();
405 Module* mergedModule = _linker.getModule();
407 // If target supports exception handling then enable it now.
408 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
409 llvm::ExceptionHandling = true;
411 // if options were requested, set them
412 if ( !_codegenOptions.empty() )
413 cl::ParseCommandLineOptions(_codegenOptions.size(),
414 (char**)&_codegenOptions[0]);
416 // Instantiate the pass manager to organize the passes.
419 // Start off with a verification pass.
420 passes.add(createVerifierPass());
422 // Add an appropriate TargetData instance for this module...
423 passes.add(new TargetData(*_target->getTargetData()));
425 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
426 /*VerifyEach=*/ false);
428 // Make sure everything is still good.
429 passes.add(createVerifierPass());
431 FunctionPassManager* codeGenPasses =
432 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
434 codeGenPasses->add(new TargetData(*_target->getTargetData()));
436 ObjectCodeEmitter* oce = NULL;
438 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
439 TargetMachine::AssemblyFile,
440 CodeGenOpt::Aggressive)) {
441 case FileModel::MachOFile:
442 oce = AddMachOWriter(*codeGenPasses, out, *_target);
444 case FileModel::ElfFile:
445 oce = AddELFWriter(*codeGenPasses, out, *_target);
447 case FileModel::AsmFile:
449 case FileModel::Error:
450 case FileModel::None:
451 errMsg = "target file type not supported";
455 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
456 CodeGenOpt::Aggressive)) {
457 errMsg = "target does not support generation of this file type";
461 // Run our queue of passes all at once now, efficiently.
462 passes.run(*mergedModule);
464 // Run the code generator, and write assembly file
465 codeGenPasses->doInitialization();
467 for (Module::iterator
468 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
469 if (!it->isDeclaration())
470 codeGenPasses->run(*it);
472 codeGenPasses->doFinalization();
473 return false; // success
477 /// Optimize merged modules using various IPO passes
478 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
480 std::string ops(options);
481 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
482 // ParseCommandLineOptions() expects argv[0] to be program name.
484 if ( _codegenOptions.empty() )
485 _codegenOptions.push_back("libLTO");
486 _codegenOptions.push_back(strdup(o.c_str()));