1 //===-LTOModule.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"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Support/SystemUtils.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/System/Path.h"
26 #include "llvm/System/Process.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetMachineRegistry.h"
29 #include "llvm/Target/TargetAsmInfo.h"
36 bool LTOModule::isBitcodeFile(const void* mem, size_t length)
38 return ( llvm::sys::IdentifyFileType((char*)mem, length)
39 == llvm::sys::Bitcode_FileType );
42 bool LTOModule::isBitcodeFile(const char* path)
44 return llvm::sys::Path(path).isBitcodeFile();
47 bool LTOModule::isBitcodeFileForTarget(const void* mem, size_t length,
48 const char* triplePrefix)
50 MemoryBuffer* buffer = makeBuffer(mem, length);
53 return isTargetMatch(buffer, triplePrefix);
57 bool LTOModule::isBitcodeFileForTarget(const char* path,
58 const char* triplePrefix)
60 MemoryBuffer *buffer = MemoryBuffer::getFile(path);
63 return isTargetMatch(buffer, triplePrefix);
66 // takes ownership of buffer
67 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
69 OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer));
70 // on success, mp owns buffer and both are deleted at end of this method
75 std::string actualTarget = mp->getModule()->getTargetTriple();
76 return ( strncmp(actualTarget.c_str(), triplePrefix,
77 strlen(triplePrefix)) == 0);
81 LTOModule::LTOModule(Module* m, TargetMachine* t)
82 : _module(m), _target(t), _symbolsParsed(false)
86 LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
88 OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
91 return makeLTOModule(buffer.get(), errMsg);
94 /// makeBuffer - create a MemoryBuffer from a memory range.
95 /// MemoryBuffer requires the byte past end of the buffer to be a zero.
96 /// We might get lucky and already be that way, otherwise make a copy.
97 /// Also if next byte is on a different page, don't assume it is readable.
98 MemoryBuffer* LTOModule::makeBuffer(const void* mem, size_t length)
100 const char* startPtr = (char*)mem;
101 const char* endPtr = startPtr+length;
102 if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0)
104 return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
106 return MemoryBuffer::getMemBuffer(startPtr, endPtr);
110 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length,
113 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
116 return makeLTOModule(buffer.get(), errMsg);
119 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
121 // parse bitcode buffer
122 OwningPtr<Module> m(ParseBitcodeFile(buffer, &errMsg));
125 // find machine architecture for this module
126 const TargetMachineRegistry::entry* march =
127 TargetMachineRegistry::getClosestStaticTargetForModule(*m, errMsg);
130 // construct LTModule, hand over ownership of module and target
131 std::string features;
132 TargetMachine* target = march->CtorFn(*m, features);
133 return new LTOModule(m.take(), target);
137 const char* LTOModule::getTargetTriple()
139 return _module->getTargetTriple().c_str();
142 void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
144 // add to list of defined symbols
145 addDefinedSymbol(f, mangler, true);
147 // add external symbols referenced by this function.
148 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
149 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
150 for (unsigned count = 0, total = i->getNumOperands();
151 count != total; ++count) {
152 findExternalRefs(i->getOperand(count), mangler);
158 void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler &mangler)
160 // add to list of defined symbols
161 addDefinedSymbol(v, mangler, false);
163 // add external symbols referenced by this data.
164 for (unsigned count = 0, total = v->getNumOperands();\
165 count != total; ++count) {
166 findExternalRefs(v->getOperand(count), mangler);
171 void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler,
174 // string is owned by _defines
175 const char* symbolName = ::strdup(mangler.getValueName(def).c_str());
177 // set alignment part log2() can have rounding errors
178 uint32_t align = def->getAlignment();
179 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
181 // set permissions part
183 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
185 GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
186 if ( (gv != NULL) && gv->isConstant() )
187 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
189 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
192 // set definition part
193 if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
194 // lvm bitcode does not differenciate between weak def data
195 // and tentative definitions!
197 // C++ does not use tentative definitions, but does use weak symbols
198 // so guess that anything that looks like a C++ symbol is weak and others
199 // are tentative definitions
200 if ( (strncmp(symbolName, "__Z", 3) == 0) )
201 attr |= LTO_SYMBOL_DEFINITION_WEAK;
203 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
206 else if ( def->hasCommonLinkage()) {
207 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
210 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
214 if ( def->hasHiddenVisibility() )
215 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
216 else if ( def->hasExternalLinkage() || def->hasWeakLinkage() )
217 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
219 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
221 // add to table of symbols
222 NameAndAttributes info;
223 info.name = symbolName;
224 info.attributes = (lto_symbol_attributes)attr;
225 _symbols.push_back(info);
226 _defines[info.name] = 1;
230 void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
232 const char* name = mangler.getValueName(decl).c_str();
233 // ignore all llvm.* symbols
234 if ( strncmp(name, "llvm.", 5) != 0 ) {
235 _undefines[name] = 1;
241 // Find exeternal symbols referenced by VALUE. This is a recursive function.
242 void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
244 if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
245 if ( !gv->hasExternalLinkage() )
246 addPotentialUndefinedSymbol(gv, mangler);
249 // GlobalValue, even with InternalLinkage type, may have operands with
250 // ExternalLinkage type. Do not ignore these operands.
251 if (Constant* c = dyn_cast<Constant>(value)) {
252 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
253 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
254 findExternalRefs(c->getOperand(i), mangler);
258 void LTOModule::lazyParseSymbols()
260 if ( !_symbolsParsed ) {
261 _symbolsParsed = true;
263 // Use mangler to add GlobalPrefix to names to match linker names.
264 Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
267 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
268 if ( f->isDeclaration() )
269 addPotentialUndefinedSymbol(f, mangler);
271 addDefinedFunctionSymbol(f, mangler);
275 for (Module::global_iterator v = _module->global_begin(),
276 e = _module->global_end(); v != e; ++v) {
277 if ( v->isDeclaration() )
278 addPotentialUndefinedSymbol(v, mangler);
280 addDefinedDataSymbol(v, mangler);
283 // make symbols for all undefines
284 for (StringSet::iterator it=_undefines.begin();
285 it != _undefines.end(); ++it) {
286 // if this symbol also has a definition, then don't make an undefine
287 // because it is a tentative definition
288 if ( _defines.count(it->getKeyData(), it->getKeyData()+
289 it->getKeyLength()) == 0 ) {
290 NameAndAttributes info;
291 info.name = it->getKeyData();
292 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
293 _symbols.push_back(info);
300 uint32_t LTOModule::getSymbolCount()
303 return _symbols.size();
307 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
310 if ( index < _symbols.size() )
311 return _symbols[index].attributes;
313 return lto_symbol_attributes(0);
316 const char* LTOModule::getSymbolName(uint32_t index)
319 if ( index < _symbols.size() )
320 return _symbols[index].name;