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/SubtargetFeature.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetMachineRegistry.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Transforms/IPO.h"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Config/config.h"
57 const char* LTOCodeGenerator::getVersionString()
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
67 LTOCodeGenerator::LTOCodeGenerator()
68 : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
69 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
70 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
71 _nativeObjectFile(NULL)
76 LTOCodeGenerator::~LTOCodeGenerator()
79 delete _nativeObjectFile;
84 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
86 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
90 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
93 case LTO_DEBUG_MODEL_NONE:
94 _emitDwarfDebugInfo = false;
97 case LTO_DEBUG_MODEL_DWARF:
98 _emitDwarfDebugInfo = true;
101 errMsg = "unknown debug format";
106 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
110 case LTO_CODEGEN_PIC_MODEL_STATIC:
111 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
112 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
116 errMsg = "unknown pic model";
120 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
122 _mustPreserveSymbols[sym] = 1;
126 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
128 if ( this->determineTarget(errMsg) )
131 // mark which symbols can not be internalized
132 this->applyScopeRestrictions();
134 // create output file
135 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
137 errMsg = "could not open bitcode file for writing: ";
142 // write bitcode to it
143 WriteBitcodeToFile(_linker.getModule(), out);
145 errMsg = "could not write bitcode file: ";
154 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
156 // make unique temp .s file to put generated assembly code
157 sys::Path uniqueAsmPath("lto-llvm.s");
158 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
160 sys::RemoveFileOnSignal(uniqueAsmPath);
162 // generate assembly code
163 std::ofstream asmFile(uniqueAsmPath.c_str());
164 bool genResult = this->generateAssemblyCode(asmFile, errMsg);
167 if ( uniqueAsmPath.exists() )
168 uniqueAsmPath.eraseFromDisk();
172 // make unique temp .o file to put generated object file
173 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
174 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
175 if ( uniqueAsmPath.exists() )
176 uniqueAsmPath.eraseFromDisk();
179 sys::RemoveFileOnSignal(uniqueObjPath);
181 // assemble the assembly code
182 const std::string& uniqueObjStr = uniqueObjPath.toString();
183 bool asmResult = this->assemble(uniqueAsmPath.toString(),
184 uniqueObjStr, errMsg);
186 // remove old buffer if compile() called twice
187 delete _nativeObjectFile;
189 // read .o file into memory buffer
190 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
194 uniqueAsmPath.eraseFromDisk();
195 uniqueObjPath.eraseFromDisk();
197 // return buffer, unless error
198 if ( _nativeObjectFile == NULL )
200 *length = _nativeObjectFile->getBufferSize();
201 return _nativeObjectFile->getBufferStart();
205 bool LTOCodeGenerator::assemble(const std::string& asmPath,
206 const std::string& objPath, std::string& errMsg)
208 // find compiler driver
209 const sys::Path gcc = sys::Program::FindProgramByName("gcc");
210 if ( gcc.isEmpty() ) {
211 errMsg = "can't locate gcc";
215 // build argument list
216 std::vector<const char*> args;
217 std::string targetTriple = _linker.getModule()->getTargetTriple();
218 args.push_back(gcc.c_str());
219 if ( targetTriple.find("darwin") != targetTriple.size() ) {
220 if (strncmp(targetTriple.c_str(), "i686-apple-", 11) == 0) {
221 args.push_back("-arch");
222 args.push_back("i386");
224 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
225 args.push_back("-arch");
226 args.push_back("x86_64");
228 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
229 args.push_back("-arch");
230 args.push_back("ppc");
232 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
233 args.push_back("-arch");
234 args.push_back("ppc64");
237 args.push_back("-c");
238 args.push_back("-x");
239 args.push_back("assembler");
240 args.push_back("-o");
241 args.push_back(objPath.c_str());
242 args.push_back(asmPath.c_str());
246 if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
247 errMsg = "error in assembly";
250 return false; // success
255 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
257 if ( _target == NULL ) {
258 // create target machine from info for merged modules
259 Module* mergedModule = _linker.getModule();
260 const TargetMachineRegistry::entry* march =
261 TargetMachineRegistry::getClosestStaticTargetForModule(
262 *mergedModule, errMsg);
266 // construct LTModule, hand over ownership of module and target
267 std::string FeatureStr =
268 getFeatureString(_linker.getModule()->getTargetTriple().c_str());
269 _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
274 void LTOCodeGenerator::applyScopeRestrictions()
276 if ( !_scopeRestrictionsDone ) {
277 Module* mergedModule = _linker.getModule();
279 // Start off with a verification pass.
281 passes.add(createVerifierPass());
283 // mark which symbols can not be internalized
284 if ( !_mustPreserveSymbols.empty() ) {
285 Mangler mangler(*mergedModule,
286 _target->getTargetAsmInfo()->getGlobalPrefix());
287 std::vector<const char*> mustPreserveList;
288 for (Module::iterator f = mergedModule->begin(),
289 e = mergedModule->end(); f != e; ++f) {
290 if ( !f->isDeclaration()
291 && _mustPreserveSymbols.count(mangler.getValueName(f)) )
292 mustPreserveList.push_back(::strdup(f->getName().c_str()));
294 for (Module::global_iterator v = mergedModule->global_begin(),
295 e = mergedModule->global_end(); v != e; ++v) {
296 if ( !v->isDeclaration()
297 && _mustPreserveSymbols.count(mangler.getValueName(v)) )
298 mustPreserveList.push_back(::strdup(v->getName().c_str()));
300 passes.add(createInternalizePass(mustPreserveList));
302 // apply scope restrictions
303 passes.run(*mergedModule);
305 _scopeRestrictionsDone = true;
309 /// Optimize merged modules using various IPO passes
310 bool LTOCodeGenerator::generateAssemblyCode(std::ostream& out, std::string& errMsg)
312 if ( this->determineTarget(errMsg) )
315 // mark which symbols can not be internalized
316 this->applyScopeRestrictions();
318 Module* mergedModule = _linker.getModule();
320 // If target supports exception handling then enable it now.
321 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
322 llvm::ExceptionHandling = true;
325 switch( _codeModel ) {
326 case LTO_CODEGEN_PIC_MODEL_STATIC:
327 _target->setRelocationModel(Reloc::Static);
329 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
330 _target->setRelocationModel(Reloc::PIC_);
332 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
333 _target->setRelocationModel(Reloc::DynamicNoPIC);
337 for (unsigned opt_index = 0, opt_size = _codegenOptions.size();
338 opt_index < opt_size; ++opt_index) {
339 std::vector<const char *> cgOpts;
340 std::string &optString = _codegenOptions[opt_index];
341 for (std::string Opt = getToken(optString);
342 !Opt.empty(); Opt = getToken(optString))
343 cgOpts.push_back(Opt.c_str());
345 int pseudo_argc = cgOpts.size()-1;
346 cl::ParseCommandLineOptions(pseudo_argc, (char**)&cgOpts[0]);
349 // Instantiate the pass manager to organize the passes.
352 // Start off with a verification pass.
353 passes.add(createVerifierPass());
355 // Add an appropriate TargetData instance for this module...
356 passes.add(new TargetData(*_target->getTargetData()));
358 // Propagate constants at call sites into the functions they call. This
359 // opens opportunities for globalopt (and inlining) by substituting function
360 // pointers passed as arguments to direct uses of functions.
361 passes.add(createIPSCCPPass());
363 // Now that we internalized some globals, see if we can hack on them!
364 passes.add(createGlobalOptimizerPass());
366 // Linking modules together can lead to duplicated global constants, only
367 // keep one copy of each constant...
368 passes.add(createConstantMergePass());
370 // Remove unused arguments from functions...
371 passes.add(createDeadArgEliminationPass());
373 // Reduce the code after globalopt and ipsccp. Both can open up significant
374 // simplification opportunities, and both can propagate functions through
375 // function pointers. When this happens, we often have to resolve varargs
376 // calls, etc, so let instcombine do this.
377 passes.add(createInstructionCombiningPass());
378 passes.add(createFunctionInliningPass()); // Inline small functions
379 passes.add(createPruneEHPass()); // Remove dead EH info
380 passes.add(createGlobalDCEPass()); // Remove dead functions
382 // If we didn't decide to inline a function, check to see if we can
383 // transform it to pass arguments by value instead of by reference.
384 passes.add(createArgumentPromotionPass());
386 // The IPO passes may leave cruft around. Clean up after them.
387 passes.add(createInstructionCombiningPass());
388 passes.add(createJumpThreadingPass()); // Thread jumps.
389 passes.add(createScalarReplAggregatesPass()); // Break up allocas
391 // Run a few AA driven optimizations here and now, to cleanup the code.
392 passes.add(createGlobalsModRefPass()); // IP alias analysis
393 passes.add(createLICMPass()); // Hoist loop invariants
394 passes.add(createGVNPass()); // Remove common subexprs
395 passes.add(createMemCpyOptPass()); // Remove dead memcpy's
396 passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
398 // Cleanup and simplify the code after the scalar optimizations.
399 passes.add(createInstructionCombiningPass());
400 passes.add(createJumpThreadingPass()); // Thread jumps.
401 passes.add(createPromoteMemoryToRegisterPass()); // Cleanup after threading.
404 // Delete basic blocks, which optimization passes may have killed...
405 passes.add(createCFGSimplificationPass());
407 // Now that we have optimized the program, discard unreachable functions...
408 passes.add(createGlobalDCEPass());
410 // Make sure everything is still good.
411 passes.add(createVerifierPass());
413 FunctionPassManager* codeGenPasses =
414 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
416 codeGenPasses->add(new TargetData(*_target->getTargetData()));
418 MachineCodeEmitter* mce = NULL;
420 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
421 TargetMachine::AssemblyFile, true)) {
422 case FileModel::MachOFile:
423 mce = AddMachOWriter(*codeGenPasses, out, *_target);
425 case FileModel::ElfFile:
426 mce = AddELFWriter(*codeGenPasses, out, *_target);
428 case FileModel::AsmFile:
430 case FileModel::Error:
431 case FileModel::None:
432 errMsg = "target file type not supported";
436 if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce, true)) {
437 errMsg = "target does not support generation of this file type";
441 // Run our queue of passes all at once now, efficiently.
442 passes.run(*mergedModule);
444 // Run the code generator, and write assembly file
445 codeGenPasses->doInitialization();
447 for (Module::iterator
448 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
449 if (!it->isDeclaration())
450 codeGenPasses->run(*it);
452 codeGenPasses->doFinalization();
453 return false; // success