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"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Linker.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/Passes.h"
26 #include "llvm/Bitcode/ReaderWriter.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetSelect.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/PassManagerBuilder.h"
40 #include "llvm/Support/SystemUtils.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/Program.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/system_error.h"
46 #include "llvm/Config/config.h"
54 static cl::opt
<bool> DisableInline("disable-inlining",
55 cl::desc("Do not run the inliner pass"));
58 const char* LTOCodeGenerator::getVersionString()
60 #ifdef LLVM_VERSION_INFO
61 return PACKAGE_NAME
" version " PACKAGE_VERSION
", " LLVM_VERSION_INFO
;
63 return PACKAGE_NAME
" version " PACKAGE_VERSION
;
68 LTOCodeGenerator::LTOCodeGenerator()
69 : _context(getGlobalContext()),
70 _linker("LinkTimeOptimizer", "ld-temp.o", _context
), _target(NULL
),
71 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
72 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC
),
73 _nativeObjectFile(NULL
)
75 InitializeAllTargets();
76 InitializeAllAsmPrinters();
79 LTOCodeGenerator::~LTOCodeGenerator()
82 delete _nativeObjectFile
;
87 bool LTOCodeGenerator::addModule(LTOModule
* mod
, std::string
& errMsg
)
90 if(mod
->getLLVVMModule()->MaterializeAllPermanently(&errMsg
))
93 bool ret
= _linker
.LinkInModule(mod
->getLLVVMModule(), &errMsg
);
95 const std::vector
<const char*> &undefs
= mod
->getAsmUndefinedRefs();
96 for (int i
= 0, e
= undefs
.size(); i
!= e
; ++i
)
97 _asmUndefinedRefs
[undefs
[i
]] = 1;
103 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug
, std::string
& errMsg
)
106 case LTO_DEBUG_MODEL_NONE
:
107 _emitDwarfDebugInfo
= false;
110 case LTO_DEBUG_MODEL_DWARF
:
111 _emitDwarfDebugInfo
= true;
114 errMsg
= "unknown debug format";
119 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model
,
123 case LTO_CODEGEN_PIC_MODEL_STATIC
:
124 case LTO_CODEGEN_PIC_MODEL_DYNAMIC
:
125 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC
:
129 errMsg
= "unknown pic model";
133 void LTOCodeGenerator::setCpu(const char* mCpu
)
138 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym
)
140 _mustPreserveSymbols
[sym
] = 1;
144 bool LTOCodeGenerator::writeMergedModules(const char *path
,
145 std::string
&errMsg
) {
146 if (determineTarget(errMsg
))
149 // mark which symbols can not be internalized
150 applyScopeRestrictions();
152 // create output file
154 tool_output_file
Out(path
, ErrInfo
,
155 raw_fd_ostream::F_Binary
);
156 if (!ErrInfo
.empty()) {
157 errMsg
= "could not open bitcode file for writing: ";
162 // write bitcode to it
163 WriteBitcodeToFile(_linker
.getModule(), Out
.os());
166 if (Out
.os().has_error()) {
167 errMsg
= "could not write bitcode file: ";
169 Out
.os().clear_error();
178 bool LTOCodeGenerator::compile_to_file(const char** name
, std::string
& errMsg
)
180 // make unique temp .o file to put generated object file
181 sys::PathWithStatus
uniqueObjPath("lto-llvm.o");
182 if ( uniqueObjPath
.createTemporaryFileOnDisk(false, &errMsg
) ) {
183 uniqueObjPath
.eraseFromDisk();
186 sys::RemoveFileOnSignal(uniqueObjPath
);
188 // generate object file
189 bool genResult
= false;
190 tool_output_file
objFile(uniqueObjPath
.c_str(), errMsg
);
193 genResult
= this->generateObjectFile(objFile
.os(), errMsg
);
194 objFile
.os().close();
195 if (objFile
.os().has_error()) {
196 objFile
.os().clear_error();
201 uniqueObjPath
.eraseFromDisk();
205 _nativeObjectPath
= uniqueObjPath
.str();
206 *name
= _nativeObjectPath
.c_str();
210 const void* LTOCodeGenerator::compile(size_t* length
, std::string
& errMsg
)
213 if (compile_to_file(&name
, errMsg
))
216 // remove old buffer if compile() called twice
217 delete _nativeObjectFile
;
219 // read .o file into memory buffer
220 OwningPtr
<MemoryBuffer
> BuffPtr
;
221 if (error_code ec
= MemoryBuffer::getFile(name
, BuffPtr
, -1, false)) {
222 errMsg
= ec
.message();
225 _nativeObjectFile
= BuffPtr
.take();
228 sys::Path(_nativeObjectPath
).eraseFromDisk();
230 // return buffer, unless error
231 if ( _nativeObjectFile
== NULL
)
233 *length
= _nativeObjectFile
->getBufferSize();
234 return _nativeObjectFile
->getBufferStart();
237 bool LTOCodeGenerator::determineTarget(std::string
& errMsg
)
239 if ( _target
== NULL
) {
240 std::string Triple
= _linker
.getModule()->getTargetTriple();
242 Triple
= sys::getHostTriple();
244 // create target machine from info for merged modules
245 const Target
*march
= TargetRegistry::lookupTarget(Triple
, errMsg
);
249 // The relocation model is actually a static member of TargetMachine
250 // and needs to be set before the TargetMachine is instantiated.
251 switch( _codeModel
) {
252 case LTO_CODEGEN_PIC_MODEL_STATIC
:
253 TargetMachine::setRelocationModel(Reloc::Static
);
255 case LTO_CODEGEN_PIC_MODEL_DYNAMIC
:
256 TargetMachine::setRelocationModel(Reloc::PIC_
);
258 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC
:
259 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC
);
263 // construct LTModule, hand over ownership of module and target
264 SubtargetFeatures Features
;
265 Features
.getDefaultSubtargetFeatures(llvm::Triple(Triple
));
266 std::string FeatureStr
= Features
.getString();
267 _target
= march
->createTargetMachine(Triple
, _mCpu
, FeatureStr
);
272 void LTOCodeGenerator::applyRestriction(GlobalValue
&GV
,
273 std::vector
<const char*> &mustPreserveList
,
274 SmallPtrSet
<GlobalValue
*, 8> &asmUsed
,
276 SmallString
<64> Buffer
;
277 mangler
.getNameWithPrefix(Buffer
, &GV
, false);
279 if (GV
.isDeclaration())
281 if (_mustPreserveSymbols
.count(Buffer
))
282 mustPreserveList
.push_back(GV
.getName().data());
283 if (_asmUndefinedRefs
.count(Buffer
))
287 static void findUsedValues(GlobalVariable
*LLVMUsed
,
288 SmallPtrSet
<GlobalValue
*, 8> &UsedValues
) {
289 if (LLVMUsed
== 0) return;
291 ConstantArray
*Inits
= dyn_cast
<ConstantArray
>(LLVMUsed
->getInitializer());
292 if (Inits
== 0) return;
294 for (unsigned i
= 0, e
= Inits
->getNumOperands(); i
!= e
; ++i
)
295 if (GlobalValue
*GV
=
296 dyn_cast
<GlobalValue
>(Inits
->getOperand(i
)->stripPointerCasts()))
297 UsedValues
.insert(GV
);
300 void LTOCodeGenerator::applyScopeRestrictions() {
301 if (_scopeRestrictionsDone
) return;
302 Module
*mergedModule
= _linker
.getModule();
304 // Start off with a verification pass.
306 passes
.add(createVerifierPass());
308 // mark which symbols can not be internalized
309 MCContext
Context(*_target
->getMCAsmInfo(), NULL
);
310 Mangler
mangler(Context
, *_target
->getTargetData());
311 std::vector
<const char*> mustPreserveList
;
312 SmallPtrSet
<GlobalValue
*, 8> asmUsed
;
314 for (Module::iterator f
= mergedModule
->begin(),
315 e
= mergedModule
->end(); f
!= e
; ++f
)
316 applyRestriction(*f
, mustPreserveList
, asmUsed
, mangler
);
317 for (Module::global_iterator v
= mergedModule
->global_begin(),
318 e
= mergedModule
->global_end(); v
!= e
; ++v
)
319 applyRestriction(*v
, mustPreserveList
, asmUsed
, mangler
);
320 for (Module::alias_iterator a
= mergedModule
->alias_begin(),
321 e
= mergedModule
->alias_end(); a
!= e
; ++a
)
322 applyRestriction(*a
, mustPreserveList
, asmUsed
, mangler
);
324 GlobalVariable
*LLVMCompilerUsed
=
325 mergedModule
->getGlobalVariable("llvm.compiler.used");
326 findUsedValues(LLVMCompilerUsed
, asmUsed
);
327 if (LLVMCompilerUsed
)
328 LLVMCompilerUsed
->eraseFromParent();
330 const llvm::Type
*i8PTy
= llvm::Type::getInt8PtrTy(_context
);
331 std::vector
<Constant
*> asmUsed2
;
332 for (SmallPtrSet
<GlobalValue
*, 16>::const_iterator i
= asmUsed
.begin(),
333 e
= asmUsed
.end(); i
!=e
; ++i
) {
334 GlobalValue
*GV
= *i
;
335 Constant
*c
= ConstantExpr::getBitCast(GV
, i8PTy
);
336 asmUsed2
.push_back(c
);
339 llvm::ArrayType
*ATy
= llvm::ArrayType::get(i8PTy
, asmUsed2
.size());
341 new llvm::GlobalVariable(*mergedModule
, ATy
, false,
342 llvm::GlobalValue::AppendingLinkage
,
343 llvm::ConstantArray::get(ATy
, asmUsed2
),
344 "llvm.compiler.used");
346 LLVMCompilerUsed
->setSection("llvm.metadata");
348 passes
.add(createInternalizePass(mustPreserveList
));
350 // apply scope restrictions
351 passes
.run(*mergedModule
);
353 _scopeRestrictionsDone
= true;
356 /// Optimize merged modules using various IPO passes
357 bool LTOCodeGenerator::generateObjectFile(raw_ostream
&out
,
358 std::string
&errMsg
) {
359 if ( this->determineTarget(errMsg
) )
362 // mark which symbols can not be internalized
363 this->applyScopeRestrictions();
365 Module
* mergedModule
= _linker
.getModule();
367 // if options were requested, set them
368 if ( !_codegenOptions
.empty() )
369 cl::ParseCommandLineOptions(_codegenOptions
.size(),
370 const_cast<char **>(&_codegenOptions
[0]));
372 // Instantiate the pass manager to organize the passes.
375 // Start off with a verification pass.
376 passes
.add(createVerifierPass());
378 // Add an appropriate TargetData instance for this module...
379 passes
.add(new TargetData(*_target
->getTargetData()));
381 PassManagerBuilder().populateLTOPassManager(passes
, /*Internalize=*/ false,
384 // Make sure everything is still good.
385 passes
.add(createVerifierPass());
387 FunctionPassManager
*codeGenPasses
= new FunctionPassManager(mergedModule
);
389 codeGenPasses
->add(new TargetData(*_target
->getTargetData()));
391 formatted_raw_ostream
Out(out
);
393 if (_target
->addPassesToEmitFile(*codeGenPasses
, Out
,
394 TargetMachine::CGFT_ObjectFile
,
395 CodeGenOpt::Aggressive
)) {
396 errMsg
= "target file type not supported";
400 // Run our queue of passes all at once now, efficiently.
401 passes
.run(*mergedModule
);
403 // Run the code generator, and write assembly file
404 codeGenPasses
->doInitialization();
406 for (Module::iterator
407 it
= mergedModule
->begin(), e
= mergedModule
->end(); it
!= e
; ++it
)
408 if (!it
->isDeclaration())
409 codeGenPasses
->run(*it
);
411 codeGenPasses
->doFinalization();
412 delete codeGenPasses
;
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()));