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"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Linker.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/Passes.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/Verifier.h"
29 #include "llvm/Bitcode/ReaderWriter.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/Target/Mangler.h"
33 #include "llvm/Target/SubtargetFeature.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.h"
39 #include "llvm/Transforms/IPO.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/StandardPasses.h"
45 #include "llvm/Support/SystemUtils.h"
46 #include "llvm/System/Host.h"
47 #include "llvm/System/Program.h"
48 #include "llvm/System/Signals.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_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 formatted_raw_ostream asmFile(asmFD);
185 genResult = this->generateAssemblyCode(asmFile, errMsg);
188 if ( uniqueAsmPath.exists() )
189 uniqueAsmPath.eraseFromDisk();
193 // make unique temp .o file to put generated object file
194 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
195 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
196 if ( uniqueAsmPath.exists() )
197 uniqueAsmPath.eraseFromDisk();
200 sys::RemoveFileOnSignal(uniqueObjPath);
202 // assemble the assembly code
203 const std::string& uniqueObjStr = uniqueObjPath.str();
204 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
206 // remove old buffer if compile() called twice
207 delete _nativeObjectFile;
209 // read .o file into memory buffer
210 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
214 uniqueAsmPath.eraseFromDisk();
215 uniqueObjPath.eraseFromDisk();
217 // return buffer, unless error
218 if ( _nativeObjectFile == NULL )
220 *length = _nativeObjectFile->getBufferSize();
221 return _nativeObjectFile->getBufferStart();
225 bool LTOCodeGenerator::assemble(const std::string& asmPath,
226 const std::string& objPath, std::string& errMsg)
229 bool needsCompilerOptions = true;
230 if ( _assemblerPath ) {
231 tool = *_assemblerPath;
232 needsCompilerOptions = false;
234 // find compiler driver
235 tool = sys::Program::FindProgramByName("gcc");
236 if ( tool.isEmpty() ) {
237 errMsg = "can't locate gcc";
242 // build argument list
243 std::vector<const char*> args;
244 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
245 const char *arch = targetTriple.getArchNameForAssembler();
247 args.push_back(tool.c_str());
249 if (targetTriple.getOS() == Triple::Darwin) {
250 // darwin specific command line options
252 args.push_back("-arch");
253 args.push_back(arch);
255 // add -static to assembler command line when code model requires
256 if ( (_assemblerPath != NULL) &&
257 (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
258 args.push_back("-static");
260 if ( needsCompilerOptions ) {
261 args.push_back("-c");
262 args.push_back("-x");
263 args.push_back("assembler");
265 args.push_back("-o");
266 args.push_back(objPath.c_str());
267 args.push_back(asmPath.c_str());
271 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
272 errMsg = "error in assembly";
275 return false; // success
280 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
282 if ( _target == NULL ) {
283 std::string Triple = _linker.getModule()->getTargetTriple();
285 Triple = sys::getHostTriple();
287 // create target machine from info for merged modules
288 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
292 // The relocation model is actually a static member of TargetMachine
293 // and needs to be set before the TargetMachine is instantiated.
294 switch( _codeModel ) {
295 case LTO_CODEGEN_PIC_MODEL_STATIC:
296 TargetMachine::setRelocationModel(Reloc::Static);
298 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
299 TargetMachine::setRelocationModel(Reloc::PIC_);
301 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
302 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
306 // construct LTModule, hand over ownership of module and target
307 const std::string FeatureStr =
308 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
309 _target = march->createTargetMachine(Triple, FeatureStr);
314 void LTOCodeGenerator::applyScopeRestrictions() {
315 if (_scopeRestrictionsDone) return;
316 Module *mergedModule = _linker.getModule();
318 // Start off with a verification pass.
320 passes.add(createVerifierPass());
322 // mark which symbols can not be internalized
323 if (!_mustPreserveSymbols.empty()) {
324 MCContext Context(*_target->getMCAsmInfo());
325 Mangler mangler(Context, *_target->getTargetData());
326 std::vector<const char*> mustPreserveList;
327 for (Module::iterator f = mergedModule->begin(),
328 e = mergedModule->end(); f != e; ++f) {
329 if (!f->isDeclaration() &&
330 _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
331 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
333 for (Module::global_iterator v = mergedModule->global_begin(),
334 e = mergedModule->global_end(); v != e; ++v) {
335 if (v->isDeclaration() &&
336 _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
337 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
339 passes.add(createInternalizePass(mustPreserveList));
342 // apply scope restrictions
343 passes.run(*mergedModule);
345 _scopeRestrictionsDone = true;
348 /// Optimize merged modules using various IPO passes
349 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
352 if ( this->determineTarget(errMsg) )
355 // mark which symbols can not be internalized
356 this->applyScopeRestrictions();
358 Module* mergedModule = _linker.getModule();
360 // If target supports exception handling then enable it now.
361 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
362 case ExceptionHandling::Dwarf:
363 llvm::DwarfExceptionHandling = true;
365 case ExceptionHandling::SjLj:
366 llvm::SjLjExceptionHandling = true;
368 case ExceptionHandling::None:
371 assert (0 && "Unknown exception handling model!");
374 // if options were requested, set them
375 if ( !_codegenOptions.empty() )
376 cl::ParseCommandLineOptions(_codegenOptions.size(),
377 (char**)&_codegenOptions[0]);
379 // Instantiate the pass manager to organize the passes.
382 // Start off with a verification pass.
383 passes.add(createVerifierPass());
385 // Add an appropriate TargetData instance for this module...
386 passes.add(new TargetData(*_target->getTargetData()));
388 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
389 /*VerifyEach=*/ false);
391 // Make sure everything is still good.
392 passes.add(createVerifierPass());
394 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
396 codeGenPasses->add(new TargetData(*_target->getTargetData()));
398 if (_target->addPassesToEmitFile(*codeGenPasses, out,
399 TargetMachine::CGFT_AssemblyFile,
400 CodeGenOpt::Aggressive)) {
401 errMsg = "target file type not supported";
405 // Run our queue of passes all at once now, efficiently.
406 passes.run(*mergedModule);
408 // Run the code generator, and write assembly file
409 codeGenPasses->doInitialization();
411 for (Module::iterator
412 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
413 if (!it->isDeclaration())
414 codeGenPasses->run(*it);
416 codeGenPasses->doFinalization();
418 return false; // success
422 /// Optimize merged modules using various IPO passes
423 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
425 for (std::pair<StringRef, StringRef> o = getToken(options);
426 !o.first.empty(); o = getToken(o.second)) {
427 // ParseCommandLineOptions() expects argv[0] to be program name.
429 if ( _codegenOptions.empty() )
430 _codegenOptions.push_back("libLTO");
431 _codegenOptions.push_back(strdup(o.first.str().c_str()));