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/Bitcode/ReaderWriter.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/StandardPasses.h"
41 #include "llvm/Support/SystemUtils.h"
42 #include "llvm/System/Host.h"
43 #include "llvm/System/Program.h"
44 #include "llvm/System/Signals.h"
45 #include "llvm/Config/config.h"
53 static cl::opt<bool> DisableInline("disable-inlining",
54 cl::desc("Do not run the inliner pass"));
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 : _context(getGlobalContext()),
69 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
70 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
71 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
72 _nativeObjectFile(NULL), _assemblerPath(NULL)
74 InitializeAllTargets();
75 InitializeAllAsmPrinters();
78 LTOCodeGenerator::~LTOCodeGenerator()
81 delete _nativeObjectFile;
86 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
88 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
92 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
95 case LTO_DEBUG_MODEL_NONE:
96 _emitDwarfDebugInfo = false;
99 case LTO_DEBUG_MODEL_DWARF:
100 _emitDwarfDebugInfo = true;
103 errMsg = "unknown debug format";
108 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
112 case LTO_CODEGEN_PIC_MODEL_STATIC:
113 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
114 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
118 errMsg = "unknown pic model";
122 void LTOCodeGenerator::setAssemblerPath(const char* path)
124 if ( _assemblerPath )
125 delete _assemblerPath;
126 _assemblerPath = new sys::Path(path);
129 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
131 _mustPreserveSymbols[sym] = 1;
135 bool LTOCodeGenerator::writeMergedModules(const char *path,
136 std::string &errMsg) {
137 if (determineTarget(errMsg))
140 // mark which symbols can not be internalized
141 applyScopeRestrictions();
143 // create output file
145 raw_fd_ostream Out(path, ErrInfo,
146 raw_fd_ostream::F_Binary);
147 if (!ErrInfo.empty()) {
148 errMsg = "could not open bitcode file for writing: ";
153 // write bitcode to it
154 WriteBitcodeToFile(_linker.getModule(), Out);
156 if (Out.has_error()) {
157 errMsg = "could not write bitcode file: ";
166 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
168 // make unique temp .s file to put generated assembly code
169 sys::Path uniqueAsmPath("lto-llvm.s");
170 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
172 sys::RemoveFileOnSignal(uniqueAsmPath);
174 // generate assembly code
175 bool genResult = false;
177 raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
178 formatted_raw_ostream asmFile(asmFD);
181 genResult = this->generateAssemblyCode(asmFile, errMsg);
184 if ( uniqueAsmPath.exists() )
185 uniqueAsmPath.eraseFromDisk();
189 // make unique temp .o file to put generated object file
190 sys::PathWithStatus uniqueObjPath("lto-llvm.o");
191 if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
192 if ( uniqueAsmPath.exists() )
193 uniqueAsmPath.eraseFromDisk();
196 sys::RemoveFileOnSignal(uniqueObjPath);
198 // assemble the assembly code
199 const std::string& uniqueObjStr = uniqueObjPath.str();
200 bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
202 // remove old buffer if compile() called twice
203 delete _nativeObjectFile;
205 // read .o file into memory buffer
206 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
210 uniqueAsmPath.eraseFromDisk();
211 uniqueObjPath.eraseFromDisk();
213 // return buffer, unless error
214 if ( _nativeObjectFile == NULL )
216 *length = _nativeObjectFile->getBufferSize();
217 return _nativeObjectFile->getBufferStart();
221 bool LTOCodeGenerator::assemble(const std::string& asmPath,
222 const std::string& objPath, std::string& errMsg)
225 bool needsCompilerOptions = true;
226 if ( _assemblerPath ) {
227 tool = *_assemblerPath;
228 needsCompilerOptions = false;
230 // find compiler driver
231 tool = sys::Program::FindProgramByName("gcc");
232 if ( tool.isEmpty() ) {
233 errMsg = "can't locate gcc";
238 // build argument list
239 std::vector<const char*> args;
240 llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
241 const char *arch = targetTriple.getArchNameForAssembler();
243 args.push_back(tool.c_str());
245 if (targetTriple.getOS() == Triple::Darwin) {
246 // darwin specific command line options
248 args.push_back("-arch");
249 args.push_back(arch);
251 // add -static to assembler command line when code model requires
252 if ( (_assemblerPath != NULL) &&
253 (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
254 args.push_back("-static");
256 if ( needsCompilerOptions ) {
257 args.push_back("-c");
258 args.push_back("-x");
259 args.push_back("assembler");
261 args.push_back("-o");
262 args.push_back(objPath.c_str());
263 args.push_back(asmPath.c_str());
267 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
268 errMsg = "error in assembly";
271 return false; // success
276 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
278 if ( _target == NULL ) {
279 std::string Triple = _linker.getModule()->getTargetTriple();
281 Triple = sys::getHostTriple();
283 // create target machine from info for merged modules
284 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
288 // The relocation model is actually a static member of TargetMachine
289 // and needs to be set before the TargetMachine is instantiated.
290 switch( _codeModel ) {
291 case LTO_CODEGEN_PIC_MODEL_STATIC:
292 TargetMachine::setRelocationModel(Reloc::Static);
294 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
295 TargetMachine::setRelocationModel(Reloc::PIC_);
297 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
298 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
302 // construct LTModule, hand over ownership of module and target
303 const std::string FeatureStr =
304 SubtargetFeatures::getDefaultSubtargetFeatures(llvm::Triple(Triple));
305 _target = march->createTargetMachine(Triple, FeatureStr);
310 void LTOCodeGenerator::applyScopeRestrictions() {
311 if (_scopeRestrictionsDone) return;
312 Module *mergedModule = _linker.getModule();
314 // Start off with a verification pass.
316 passes.add(createVerifierPass());
318 // mark which symbols can not be internalized
319 if (!_mustPreserveSymbols.empty()) {
320 MCContext Context(*_target->getMCAsmInfo());
321 Mangler mangler(Context, *_target->getTargetData());
322 std::vector<const char*> mustPreserveList;
323 for (Module::iterator f = mergedModule->begin(),
324 e = mergedModule->end(); f != e; ++f) {
325 if (!f->isDeclaration() &&
326 _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
327 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
329 for (Module::global_iterator v = mergedModule->global_begin(),
330 e = mergedModule->global_end(); v != e; ++v) {
331 if (v->isDeclaration() &&
332 _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
333 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
335 passes.add(createInternalizePass(mustPreserveList));
338 // apply scope restrictions
339 passes.run(*mergedModule);
341 _scopeRestrictionsDone = true;
344 /// Optimize merged modules using various IPO passes
345 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
348 if ( this->determineTarget(errMsg) )
351 // mark which symbols can not be internalized
352 this->applyScopeRestrictions();
354 Module* mergedModule = _linker.getModule();
356 // If target supports exception handling then enable it now.
357 switch (_target->getMCAsmInfo()->getExceptionHandlingType()) {
358 case ExceptionHandling::Dwarf:
359 llvm::DwarfExceptionHandling = true;
361 case ExceptionHandling::SjLj:
362 llvm::SjLjExceptionHandling = true;
364 case ExceptionHandling::None:
367 assert (0 && "Unknown exception handling model!");
370 // if options were requested, set them
371 if ( !_codegenOptions.empty() )
372 cl::ParseCommandLineOptions(_codegenOptions.size(),
373 (char**)&_codegenOptions[0]);
375 // Instantiate the pass manager to organize the passes.
378 // Start off with a verification pass.
379 passes.add(createVerifierPass());
381 // Add an appropriate TargetData instance for this module...
382 passes.add(new TargetData(*_target->getTargetData()));
384 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
385 /*VerifyEach=*/ false);
387 // Make sure everything is still good.
388 passes.add(createVerifierPass());
390 FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
392 codeGenPasses->add(new TargetData(*_target->getTargetData()));
394 if (_target->addPassesToEmitFile(*codeGenPasses, out,
395 TargetMachine::CGFT_AssemblyFile,
396 CodeGenOpt::Aggressive)) {
397 errMsg = "target file type not supported";
401 // Run our queue of passes all at once now, efficiently.
402 passes.run(*mergedModule);
404 // Run the code generator, and write assembly file
405 codeGenPasses->doInitialization();
407 for (Module::iterator
408 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
409 if (!it->isDeclaration())
410 codeGenPasses->run(*it);
412 codeGenPasses->doFinalization();
414 return false; // success
418 /// Optimize merged modules using various IPO passes
419 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
421 for (std::pair<StringRef, StringRef> o = getToken(options);
422 !o.first.empty(); o = getToken(o.second)) {
423 // ParseCommandLineOptions() expects argv[0] to be program name.
425 if ( _codegenOptions.empty() )
426 _codegenOptions.push_back("libLTO");
427 _codegenOptions.push_back(strdup(o.first.str().c_str()));