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/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/Support/SystemUtils.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/System/Signals.h"
30 #include "llvm/Analysis/Passes.h"
31 #include "llvm/Analysis/LoopPass.h"
32 #include "llvm/Analysis/Verifier.h"
33 #include "llvm/Analysis/LoadValueNumbering.h"
34 #include "llvm/CodeGen/FileWriters.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetMachineRegistry.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Config/config.h"
55 const char* LTOCodeGenerator::getVersionString()
57 #ifdef LLVM_VERSION_INFO
58 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
60 return PACKAGE_NAME " version " PACKAGE_VERSION;
65 LTOCodeGenerator::LTOCodeGenerator()
66 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
67 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
68 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
69 _nativeObjectFile(NULL)
74 LTOCodeGenerator::~LTOCodeGenerator()
77 delete _nativeObjectFile;
82 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
84 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
88 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
91 case LTO_DEBUG_MODEL_NONE:
92 _emitDwarfDebugInfo = false;
95 case LTO_DEBUG_MODEL_DWARF:
96 _emitDwarfDebugInfo = true;
99 errMsg = "unknown debug format";
104 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
108 case LTO_CODEGEN_PIC_MODEL_STATIC:
109 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
110 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
114 errMsg = "unknown pic model";
119 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
121 _mustPreserveSymbols[sym] = 1;
125 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
127 if ( this->determineTarget(errMsg) )
130 // mark which symbols can not be internalized
131 this->applyScopeRestrictions();
133 // create output file
134 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
136 errMsg = "could not open bitcode file for writing: ";
141 // write bitcode to it
142 WriteBitcodeToFile(_linker.getModule(), out);
144 errMsg = "could not write bitcode file: ";
153 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
155 // make unique temp .s file to put generated assembly code
156 sys::Path uniqueAsmPath("lto-llvm.s");
157 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
159 sys::RemoveFileOnSignal(uniqueAsmPath);
161 // generate assembly code
162 std::ofstream asmFile(uniqueAsmPath.c_str());
163 bool genResult = this->generateAssemblyCode(asmFile, errMsg);
166 if ( uniqueAsmPath.exists() )
167 uniqueAsmPath.eraseFromDisk();
171 // make unique temp .o file to put generated object file
172 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
173 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
174 if ( uniqueAsmPath.exists() )
175 uniqueAsmPath.eraseFromDisk();
178 sys::RemoveFileOnSignal(uniqueObjPath);
180 // assemble the assembly code
181 const std::string& uniqueObjStr = uniqueObjPath.toString();
182 bool asmResult = this->assemble(uniqueAsmPath.toString(),
183 uniqueObjStr, errMsg);
185 // remove old buffer if compile() called twice
186 delete _nativeObjectFile;
188 // read .o file into memory buffer
189 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
193 uniqueAsmPath.eraseFromDisk();
194 uniqueObjPath.eraseFromDisk();
196 // return buffer, unless error
197 if ( _nativeObjectFile == NULL )
199 *length = _nativeObjectFile->getBufferSize();
200 return _nativeObjectFile->getBufferStart();
204 bool LTOCodeGenerator::assemble(const std::string& asmPath,
205 const std::string& objPath, std::string& errMsg)
207 // find compiler driver
208 const sys::Path gcc = sys::Program::FindProgramByName("gcc");
209 if ( gcc.isEmpty() ) {
210 errMsg = "can't locate gcc";
214 // build argument list
215 std::vector<const char*> args;
216 std::string targetTriple = _linker.getModule()->getTargetTriple();
217 args.push_back(gcc.c_str());
218 if ( targetTriple.find("darwin") != targetTriple.size() ) {
219 if (strncmp(targetTriple.c_str(), "i686-apple-", 11) == 0) {
220 args.push_back("-arch");
221 args.push_back("i386");
223 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
224 args.push_back("-arch");
225 args.push_back("x86_64");
227 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
228 args.push_back("-arch");
229 args.push_back("ppc");
231 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
232 args.push_back("-arch");
233 args.push_back("ppc64");
236 args.push_back("-c");
237 args.push_back("-x");
238 args.push_back("assembler");
239 args.push_back("-o");
240 args.push_back(objPath.c_str());
241 args.push_back(asmPath.c_str());
245 if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
246 errMsg = "error in assembly";
249 return false; // success
254 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
256 if ( _target == NULL ) {
257 // create target machine from info for merged modules
258 Module* mergedModule = _linker.getModule();
259 const TargetMachineRegistry::entry* march =
260 TargetMachineRegistry::getClosestStaticTargetForModule(
261 *mergedModule, errMsg);
264 std::string features;
265 _target = march->CtorFn(*mergedModule, features);
270 void LTOCodeGenerator::applyScopeRestrictions()
272 if ( !_scopeRestrictionsDone ) {
273 Module* mergedModule = _linker.getModule();
275 // Start off with a verification pass.
277 passes.add(createVerifierPass());
279 // mark which symbols can not be internalized
280 if ( !_mustPreserveSymbols.empty() ) {
281 Mangler mangler(*mergedModule,
282 _target->getTargetAsmInfo()->getGlobalPrefix());
283 std::vector<const char*> mustPreserveList;
284 for (Module::iterator f = mergedModule->begin(),
285 e = mergedModule->end(); f != e; ++f) {
286 if ( !f->isDeclaration()
287 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
288 mustPreserveList.push_back(::strdup(f->getName().c_str()));
290 for (Module::global_iterator v = mergedModule->global_begin(),
291 e = mergedModule->global_end(); v != e; ++v) {
292 if ( !v->isDeclaration()
293 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
294 mustPreserveList.push_back(::strdup(v->getName().c_str()));
296 passes.add(createInternalizePass(mustPreserveList));
298 // apply scope restrictions
299 passes.run(*mergedModule);
301 _scopeRestrictionsDone = true;
306 /// Optimize merged modules using various IPO passes
307 bool LTOCodeGenerator::generateAssemblyCode(std::ostream& out, std::string& errMsg)
309 if ( this->determineTarget(errMsg) )
312 // mark which symbols can not be internalized
313 this->applyScopeRestrictions();
315 Module* mergedModule = _linker.getModule();
317 // If target supports exception handling then enable it now.
318 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
319 llvm::ExceptionHandling = true;
322 switch( _codeModel ) {
323 case LTO_CODEGEN_PIC_MODEL_STATIC:
324 _target->setRelocationModel(Reloc::Static);
326 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
327 _target->setRelocationModel(Reloc::PIC_);
329 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
330 _target->setRelocationModel(Reloc::DynamicNoPIC);
334 // Instantiate the pass manager to organize the passes.
337 // Start off with a verification pass.
338 passes.add(createVerifierPass());
340 // Add an appropriate TargetData instance for this module...
341 passes.add(new TargetData(*_target->getTargetData()));
343 // Propagate constants at call sites into the functions they call. This
344 // opens opportunities for globalopt (and inlining) by substituting function
345 // pointers passed as arguments to direct uses of functions.
346 passes.add(createIPSCCPPass());
348 // Now that we internalized some globals, see if we can hack on them!
349 passes.add(createGlobalOptimizerPass());
351 // Linking modules together can lead to duplicated global constants, only
352 // keep one copy of each constant...
353 passes.add(createConstantMergePass());
355 // Remove unused arguments from functions...
356 passes.add(createDeadArgEliminationPass());
358 // Reduce the code after globalopt and ipsccp. Both can open up significant
359 // simplification opportunities, and both can propagate functions through
360 // function pointers. When this happens, we often have to resolve varargs
361 // calls, etc, so let instcombine do this.
362 passes.add(createInstructionCombiningPass());
364 passes.add(createFunctionInliningPass()); // Inline small functions
366 passes.add(createPruneEHPass()); // Remove dead EH info
368 passes.add(createGlobalDCEPass()); // Remove dead functions
370 // If we didn't decide to inline a function, check to see if we can
371 // transform it to pass arguments by value instead of by reference.
372 passes.add(createArgumentPromotionPass());
374 // The IPO passes may leave cruft around. Clean up after them.
375 passes.add(createInstructionCombiningPass());
376 passes.add(createJumpThreadingPass()); // Thread jumps.
377 passes.add(createScalarReplAggregatesPass()); // Break up allocas
379 // Run a few AA driven optimizations here and now, to cleanup the code.
380 passes.add(createGlobalsModRefPass()); // IP alias analysis
382 passes.add(createLICMPass()); // Hoist loop invariants
383 passes.add(createGVNPass()); // Remove common subexprs
384 passes.add(createMemCpyOptPass()); // Remove dead memcpy's
385 passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
387 // Cleanup and simplify the code after the scalar optimizations.
388 passes.add(createInstructionCombiningPass());
390 passes.add(createJumpThreadingPass()); // Thread jumps.
392 // Delete basic blocks, which optimization passes may have killed...
393 passes.add(createCFGSimplificationPass());
395 // Now that we have optimized the program, discard unreachable functions...
396 passes.add(createGlobalDCEPass());
398 // Make sure everything is still good.
399 passes.add(createVerifierPass());
401 FunctionPassManager* codeGenPasses =
402 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
404 codeGenPasses->add(new TargetData(*_target->getTargetData()));
406 MachineCodeEmitter* mce = NULL;
408 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
409 TargetMachine::AssemblyFile, true)) {
410 case FileModel::MachOFile:
411 mce = AddMachOWriter(*codeGenPasses, out, *_target);
413 case FileModel::ElfFile:
414 mce = AddELFWriter(*codeGenPasses, out, *_target);
416 case FileModel::AsmFile:
418 case FileModel::Error:
419 case FileModel::None:
420 errMsg = "target file type not supported";
424 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
425 errMsg = "target does not support generation of this file type";
429 // Run our queue of passes all at once now, efficiently.
430 passes.run(*mergedModule);
432 // Run the code generator, and write assembly file
433 codeGenPasses->doInitialization();
434 for (Module::iterator it = mergedModule->begin(),
435 e = mergedModule->end(); it != e; ++it) {
436 if (!it->isDeclaration())
437 codeGenPasses->run(*it);
439 codeGenPasses->doFinalization();
441 return false; // success