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/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Target/SubtargetFeature.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Target/TargetSelect.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Config/config.h"
60 static cl::opt
<bool> DisableInline("disable-inlining",
61 cl::desc("Do not run the inliner pass"));
64 const char* LTOCodeGenerator::getVersionString()
66 #ifdef LLVM_VERSION_INFO
67 return PACKAGE_NAME
" version " PACKAGE_VERSION
", " LLVM_VERSION_INFO
;
69 return PACKAGE_NAME
" version " PACKAGE_VERSION
;
74 LTOCodeGenerator::LTOCodeGenerator()
75 : _context(getGlobalContext()),
76 _linker("LinkTimeOptimizer", "ld-temp.o", _context
), _target(NULL
),
77 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
78 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC
),
79 _nativeObjectFile(NULL
), _assemblerPath(NULL
)
81 InitializeAllTargets();
82 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::setAssemblerPath(const char* path
)
131 if ( _assemblerPath
)
132 delete _assemblerPath
;
133 _assemblerPath
= new sys::Path(path
);
136 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym
)
138 _mustPreserveSymbols
[sym
] = 1;
142 bool LTOCodeGenerator::writeMergedModules(const char* path
, std::string
& errMsg
)
144 if ( this->determineTarget(errMsg
) )
147 // mark which symbols can not be internalized
148 this->applyScopeRestrictions();
150 // create output file
151 std::ofstream
out(path
, std::ios_base::out
|std::ios::trunc
|std::ios::binary
);
153 errMsg
= "could not open bitcode file for writing: ";
158 // write bitcode to it
159 WriteBitcodeToFile(_linker
.getModule(), out
);
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(raw_fd_ostream(uniqueAsmPath
.c_str(),
182 /*Binary=*/false, /*Force=*/true,
184 formatted_raw_ostream
asmFile(asmFD
);
187 genResult
= this->generateAssemblyCode(asmFile
, errMsg
);
190 if ( uniqueAsmPath
.exists() )
191 uniqueAsmPath
.eraseFromDisk();
195 // make unique temp .o file to put generated object file
196 sys::PathWithStatus
uniqueObjPath("lto-llvm.o");
197 if ( uniqueObjPath
.createTemporaryFileOnDisk(true, &errMsg
) ) {
198 if ( uniqueAsmPath
.exists() )
199 uniqueAsmPath
.eraseFromDisk();
202 sys::RemoveFileOnSignal(uniqueObjPath
);
204 // assemble the assembly code
205 const std::string
& uniqueObjStr
= uniqueObjPath
.toString();
206 bool asmResult
= this->assemble(uniqueAsmPath
.toString(),
207 uniqueObjStr
, errMsg
);
209 // remove old buffer if compile() called twice
210 delete _nativeObjectFile
;
212 // read .o file into memory buffer
213 _nativeObjectFile
= MemoryBuffer::getFile(uniqueObjStr
.c_str(),&errMsg
);
217 uniqueAsmPath
.eraseFromDisk();
218 uniqueObjPath
.eraseFromDisk();
220 // return buffer, unless error
221 if ( _nativeObjectFile
== NULL
)
223 *length
= _nativeObjectFile
->getBufferSize();
224 return _nativeObjectFile
->getBufferStart();
228 bool LTOCodeGenerator::assemble(const std::string
& asmPath
,
229 const std::string
& objPath
, std::string
& errMsg
)
232 bool needsCompilerOptions
= true;
233 if ( _assemblerPath
) {
234 tool
= *_assemblerPath
;
235 needsCompilerOptions
= false;
237 // find compiler driver
238 tool
= sys::Program::FindProgramByName("gcc");
239 if ( tool
.isEmpty() ) {
240 errMsg
= "can't locate gcc";
245 // build argument list
246 std::vector
<const char*> args
;
247 std::string targetTriple
= _linker
.getModule()->getTargetTriple();
248 args
.push_back(tool
.c_str());
249 if ( targetTriple
.find("darwin") != std::string::npos
) {
250 // darwin specific command line options
251 if (strncmp(targetTriple
.c_str(), "i386-apple-", 11) == 0) {
252 args
.push_back("-arch");
253 args
.push_back("i386");
255 else if (strncmp(targetTriple
.c_str(), "x86_64-apple-", 13) == 0) {
256 args
.push_back("-arch");
257 args
.push_back("x86_64");
259 else if (strncmp(targetTriple
.c_str(), "powerpc-apple-", 14) == 0) {
260 args
.push_back("-arch");
261 args
.push_back("ppc");
263 else if (strncmp(targetTriple
.c_str(), "powerpc64-apple-", 16) == 0) {
264 args
.push_back("-arch");
265 args
.push_back("ppc64");
267 else if (strncmp(targetTriple
.c_str(), "arm-apple-", 10) == 0) {
268 args
.push_back("-arch");
269 args
.push_back("arm");
271 else if ((strncmp(targetTriple
.c_str(), "armv4t-apple-", 13) == 0) ||
272 (strncmp(targetTriple
.c_str(), "thumbv4t-apple-", 15) == 0)) {
273 args
.push_back("-arch");
274 args
.push_back("armv4t");
276 else if ((strncmp(targetTriple
.c_str(), "armv5-apple-", 12) == 0) ||
277 (strncmp(targetTriple
.c_str(), "armv5e-apple-", 13) == 0) ||
278 (strncmp(targetTriple
.c_str(), "thumbv5-apple-", 14) == 0) ||
279 (strncmp(targetTriple
.c_str(), "thumbv5e-apple-", 15) == 0)) {
280 args
.push_back("-arch");
281 args
.push_back("armv5");
283 else if ((strncmp(targetTriple
.c_str(), "armv6-apple-", 12) == 0) ||
284 (strncmp(targetTriple
.c_str(), "thumbv6-apple-", 14) == 0)) {
285 args
.push_back("-arch");
286 args
.push_back("armv6");
288 else if ((strncmp(targetTriple
.c_str(), "armv7-apple-", 12) == 0) ||
289 (strncmp(targetTriple
.c_str(), "thumbv7-apple-", 14) == 0)) {
290 args
.push_back("-arch");
291 args
.push_back("armv7");
293 // add -static to assembler command line when code model requires
294 if ( (_assemblerPath
!= NULL
) && (_codeModel
== LTO_CODEGEN_PIC_MODEL_STATIC
) )
295 args
.push_back("-static");
297 if ( needsCompilerOptions
) {
298 args
.push_back("-c");
299 args
.push_back("-x");
300 args
.push_back("assembler");
302 args
.push_back("-o");
303 args
.push_back(objPath
.c_str());
304 args
.push_back(asmPath
.c_str());
308 if ( sys::Program::ExecuteAndWait(tool
, &args
[0], 0, 0, 0, 0, &errMsg
) ) {
309 errMsg
= "error in assembly";
312 return false; // success
317 bool LTOCodeGenerator::determineTarget(std::string
& errMsg
)
319 if ( _target
== NULL
) {
320 std::string Triple
= _linker
.getModule()->getTargetTriple();
322 Triple
= sys::getHostTriple();
324 // create target machine from info for merged modules
325 const Target
*march
= TargetRegistry::lookupTarget(Triple
, errMsg
);
329 // The relocation model is actually a static member of TargetMachine
330 // and needs to be set before the TargetMachine is instantiated.
331 switch( _codeModel
) {
332 case LTO_CODEGEN_PIC_MODEL_STATIC
:
333 TargetMachine::setRelocationModel(Reloc::Static
);
335 case LTO_CODEGEN_PIC_MODEL_DYNAMIC
:
336 TargetMachine::setRelocationModel(Reloc::PIC_
);
338 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC
:
339 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC
);
343 // construct LTModule, hand over ownership of module and target
344 std::string FeatureStr
= getFeatureString(Triple
.c_str());
345 _target
= march
->createTargetMachine(Triple
, FeatureStr
);
350 void LTOCodeGenerator::applyScopeRestrictions()
352 if ( !_scopeRestrictionsDone
) {
353 Module
* mergedModule
= _linker
.getModule();
355 // Start off with a verification pass.
357 passes
.add(createVerifierPass());
359 // mark which symbols can not be internalized
360 if ( !_mustPreserveSymbols
.empty() ) {
361 Mangler
mangler(*mergedModule
,
362 _target
->getTargetAsmInfo()->getGlobalPrefix());
363 std::vector
<const char*> mustPreserveList
;
364 for (Module::iterator f
= mergedModule
->begin(),
365 e
= mergedModule
->end(); f
!= e
; ++f
) {
366 if ( !f
->isDeclaration()
367 && _mustPreserveSymbols
.count(mangler
.getMangledName(f
)) )
368 mustPreserveList
.push_back(::strdup(f
->getNameStr().c_str()));
370 for (Module::global_iterator v
= mergedModule
->global_begin(),
371 e
= mergedModule
->global_end(); v
!= e
; ++v
) {
372 if ( !v
->isDeclaration()
373 && _mustPreserveSymbols
.count(mangler
.getMangledName(v
)) )
374 mustPreserveList
.push_back(::strdup(v
->getNameStr().c_str()));
376 passes
.add(createInternalizePass(mustPreserveList
));
378 // apply scope restrictions
379 passes
.run(*mergedModule
);
381 _scopeRestrictionsDone
= true;
385 /// Optimize merged modules using various IPO passes
386 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream
& out
,
389 if ( this->determineTarget(errMsg
) )
392 // mark which symbols can not be internalized
393 this->applyScopeRestrictions();
395 Module
* mergedModule
= _linker
.getModule();
397 // If target supports exception handling then enable it now.
398 if ( _target
->getTargetAsmInfo()->doesSupportExceptionHandling() )
399 llvm::ExceptionHandling
= true;
401 // if options were requested, set them
402 if ( !_codegenOptions
.empty() )
403 cl::ParseCommandLineOptions(_codegenOptions
.size(),
404 (char**)&_codegenOptions
[0]);
406 // Instantiate the pass manager to organize the passes.
409 // Start off with a verification pass.
410 passes
.add(createVerifierPass());
412 // Add an appropriate TargetData instance for this module...
413 passes
.add(new TargetData(*_target
->getTargetData()));
415 createStandardLTOPasses(&passes
, /*Internalize=*/ false, !DisableInline
,
416 /*VerifyEach=*/ false);
418 // Make sure everything is still good.
419 passes
.add(createVerifierPass());
421 FunctionPassManager
* codeGenPasses
=
422 new FunctionPassManager(new ExistingModuleProvider(mergedModule
));
424 codeGenPasses
->add(new TargetData(*_target
->getTargetData()));
426 ObjectCodeEmitter
* oce
= NULL
;
428 switch (_target
->addPassesToEmitFile(*codeGenPasses
, out
,
429 TargetMachine::AssemblyFile
,
430 CodeGenOpt::Aggressive
)) {
431 case FileModel::MachOFile
:
432 oce
= AddMachOWriter(*codeGenPasses
, out
, *_target
);
434 case FileModel::ElfFile
:
435 oce
= AddELFWriter(*codeGenPasses
, out
, *_target
);
437 case FileModel::AsmFile
:
439 case FileModel::Error
:
440 case FileModel::None
:
441 errMsg
= "target file type not supported";
445 if (_target
->addPassesToEmitFileFinish(*codeGenPasses
, oce
,
446 CodeGenOpt::Aggressive
)) {
447 errMsg
= "target does not support generation of this file type";
451 // Run our queue of passes all at once now, efficiently.
452 passes
.run(*mergedModule
);
454 // Run the code generator, and write assembly file
455 codeGenPasses
->doInitialization();
457 for (Module::iterator
458 it
= mergedModule
->begin(), e
= mergedModule
->end(); it
!= e
; ++it
)
459 if (!it
->isDeclaration())
460 codeGenPasses
->run(*it
);
462 codeGenPasses
->doFinalization();
466 return false; // success
470 /// Optimize merged modules using various IPO passes
471 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options
)
473 std::string
ops(options
);
474 for (std::string o
= getToken(ops
); !o
.empty(); o
= getToken(ops
)) {
475 // ParseCommandLineOptions() expects argv[0] to be program name.
477 if ( _codegenOptions
.empty() )
478 _codegenOptions
.push_back("libLTO");
479 _codegenOptions
.push_back(strdup(o
.c_str()));