blob: c4bee714c6c8b1faa1d238ae60c214a391bc7498 [file] [log] [blame]
Nick Kledzik77595fc2008-02-26 20:26:43 +00001//===-LTOModule.cpp - LLVM Link Time Optimizer ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOModule.h"
16
Nick Kledzik77595fc2008-02-26 20:26:43 +000017#include "llvm/Module.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000018#include "llvm/ModuleProvider.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000019#include "llvm/ADT/OwningPtr.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000021#include "llvm/Support/SystemUtils.h"
22#include "llvm/Support/Mangler.h"
23#include "llvm/Support/MemoryBuffer.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000024#include "llvm/Support/MathExtras.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000025#include "llvm/System/Path.h"
Nick Kledzik90dcff72008-05-09 01:09:59 +000026#include "llvm/System/Process.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000027#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetMachineRegistry.h"
29#include "llvm/Target/TargetAsmInfo.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000030
Nick Kledzik77595fc2008-02-26 20:26:43 +000031
32#include <fstream>
33
34using namespace llvm;
35
36bool LTOModule::isBitcodeFile(const void* mem, size_t length)
37{
38 return ( llvm::sys::IdentifyFileType((char*)mem, length)
39 == llvm::sys::Bitcode_FileType );
40}
41
42bool LTOModule::isBitcodeFile(const char* path)
43{
44 return llvm::sys::Path(path).isBitcodeFile();
45}
46
Chris Lattner038112a2008-04-01 18:04:03 +000047bool LTOModule::isBitcodeFileForTarget(const void* mem, size_t length,
48 const char* triplePrefix)
Nick Kledzik77595fc2008-02-26 20:26:43 +000049{
Nick Kledzik90dcff72008-05-09 01:09:59 +000050 MemoryBuffer* buffer = makeBuffer(mem, length);
Nick Kledzikef194ed2008-02-27 22:25:36 +000051 if ( buffer == NULL )
52 return false;
53 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik77595fc2008-02-26 20:26:43 +000054}
55
Nick Kledzikef194ed2008-02-27 22:25:36 +000056
Nick Kledzik77595fc2008-02-26 20:26:43 +000057bool LTOModule::isBitcodeFileForTarget(const char* path,
Chris Lattner038112a2008-04-01 18:04:03 +000058 const char* triplePrefix)
Nick Kledzik77595fc2008-02-26 20:26:43 +000059{
Chris Lattner038112a2008-04-01 18:04:03 +000060 MemoryBuffer *buffer = MemoryBuffer::getFile(path);
61 if (buffer == NULL)
Nick Kledzikef194ed2008-02-27 22:25:36 +000062 return false;
63 return isTargetMatch(buffer, triplePrefix);
64}
65
66// takes ownership of buffer
67bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
68{
69 OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer));
70 // on success, mp owns buffer and both are deleted at end of this method
71 if ( !mp ) {
72 delete buffer;
73 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +000074 }
Nick Kledzikef194ed2008-02-27 22:25:36 +000075 std::string actualTarget = mp->getModule()->getTargetTriple();
76 return ( strncmp(actualTarget.c_str(), triplePrefix,
77 strlen(triplePrefix)) == 0);
Nick Kledzik77595fc2008-02-26 20:26:43 +000078}
79
80
81LTOModule::LTOModule(Module* m, TargetMachine* t)
82 : _module(m), _target(t), _symbolsParsed(false)
83{
84}
85
Nick Kledzik77595fc2008-02-26 20:26:43 +000086LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
87{
Chris Lattner038112a2008-04-01 18:04:03 +000088 OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
Nick Kledzikef194ed2008-02-27 22:25:36 +000089 if ( !buffer )
90 return NULL;
91 return makeLTOModule(buffer.get(), errMsg);
Nick Kledzik77595fc2008-02-26 20:26:43 +000092}
93
Nick Kledzik6b89d922008-05-09 18:44:41 +000094/// 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.
Nick Kledzik90dcff72008-05-09 01:09:59 +000098MemoryBuffer* LTOModule::makeBuffer(const void* mem, size_t length)
99{
Nick Kledzik90dcff72008-05-09 01:09:59 +0000100 const char* startPtr = (char*)mem;
101 const char* endPtr = startPtr+length;
102 if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0)
103 || (*endPtr != 0) )
104 return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
105 else
106 return MemoryBuffer::getMemBuffer(startPtr, endPtr);
107}
108
109
Nick Kledzik77595fc2008-02-26 20:26:43 +0000110LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length,
111 std::string& errMsg)
112{
Nick Kledzik90dcff72008-05-09 01:09:59 +0000113 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
Nick Kledzikef194ed2008-02-27 22:25:36 +0000114 if ( !buffer )
115 return NULL;
116 return makeLTOModule(buffer.get(), errMsg);
117}
118
119LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
120{
121 // parse bitcode buffer
122 OwningPtr<Module> m(ParseBitcodeFile(buffer, &errMsg));
123 if ( !m )
124 return NULL;
125 // find machine architecture for this module
126 const TargetMachineRegistry::entry* march =
127 TargetMachineRegistry::getClosestStaticTargetForModule(*m, errMsg);
128 if ( march == NULL )
129 return NULL;
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);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000134}
135
136
137const char* LTOModule::getTargetTriple()
138{
139 return _module->getTargetTriple().c_str();
140}
141
Nick Kledzikef194ed2008-02-27 22:25:36 +0000142void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
143{
144 // add to list of defined symbols
145 addDefinedSymbol(f, mangler, true);
146
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);
153 }
154 }
155 }
156}
157
158void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler &mangler)
159{
160 // add to list of defined symbols
161 addDefinedSymbol(v, mangler, false);
162
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);
167 }
168}
169
170
Nick Kledzik77595fc2008-02-26 20:26:43 +0000171void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler,
172 bool isFunction)
173{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000174 // string is owned by _defines
Nick Kledzik77595fc2008-02-26 20:26:43 +0000175 const char* symbolName = ::strdup(mangler.getValueName(def).c_str());
176
177 // set alignment part log2() can have rounding errors
178 uint32_t align = def->getAlignment();
Nick Kledzikef194ed2008-02-27 22:25:36 +0000179 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000180
181 // set permissions part
182 if ( isFunction )
183 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
184 else {
185 GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
186 if ( (gv != NULL) && gv->isConstant() )
187 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
188 else
189 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
190 }
191
192 // set definition part
193 if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
Dale Johannesened1ec3a2008-05-23 00:15:10 +0000194 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000195 }
Dale Johannesen6a6f2dd2008-05-16 22:46:40 +0000196 else if ( def->hasCommonLinkage()) {
197 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
198 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000199 else {
200 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
201 }
202
203 // set scope part
204 if ( def->hasHiddenVisibility() )
205 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
206 else if ( def->hasExternalLinkage() || def->hasWeakLinkage() )
207 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
208 else
209 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
210
211 // add to table of symbols
212 NameAndAttributes info;
213 info.name = symbolName;
214 info.attributes = (lto_symbol_attributes)attr;
215 _symbols.push_back(info);
216 _defines[info.name] = 1;
217}
218
219
Nick Kledzikef194ed2008-02-27 22:25:36 +0000220void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
221{
222 const char* name = mangler.getValueName(decl).c_str();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000223 // ignore all llvm.* symbols
224 if ( strncmp(name, "llvm.", 5) != 0 ) {
225 _undefines[name] = 1;
226 }
227}
228
229
230
231// Find exeternal symbols referenced by VALUE. This is a recursive function.
232void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
233
234 if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
235 if ( !gv->hasExternalLinkage() )
Nick Kledzikef194ed2008-02-27 22:25:36 +0000236 addPotentialUndefinedSymbol(gv, mangler);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000237 }
238
239 // GlobalValue, even with InternalLinkage type, may have operands with
240 // ExternalLinkage type. Do not ignore these operands.
241 if (Constant* c = dyn_cast<Constant>(value)) {
242 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
243 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
244 findExternalRefs(c->getOperand(i), mangler);
245 }
246}
247
Nick Kledzikef194ed2008-02-27 22:25:36 +0000248void LTOModule::lazyParseSymbols()
Nick Kledzik77595fc2008-02-26 20:26:43 +0000249{
250 if ( !_symbolsParsed ) {
251 _symbolsParsed = true;
252
253 // Use mangler to add GlobalPrefix to names to match linker names.
254 Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
255
256 // add functions
257 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000258 if ( f->isDeclaration() )
259 addPotentialUndefinedSymbol(f, mangler);
260 else
261 addDefinedFunctionSymbol(f, mangler);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000262 }
263
264 // add data
265 for (Module::global_iterator v = _module->global_begin(),
266 e = _module->global_end(); v != e; ++v) {
Nick Kledzikef194ed2008-02-27 22:25:36 +0000267 if ( v->isDeclaration() )
268 addPotentialUndefinedSymbol(v, mangler);
269 else
270 addDefinedDataSymbol(v, mangler);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000271 }
272
273 // make symbols for all undefines
274 for (StringSet::iterator it=_undefines.begin();
275 it != _undefines.end(); ++it) {
276 // if this symbol also has a definition, then don't make an undefine
277 // because it is a tentative definition
Nick Kledzikef194ed2008-02-27 22:25:36 +0000278 if ( _defines.count(it->getKeyData(), it->getKeyData()+
279 it->getKeyLength()) == 0 ) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000280 NameAndAttributes info;
281 info.name = it->getKeyData();
282 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
283 _symbols.push_back(info);
284 }
285 }
Nick Kledzikef194ed2008-02-27 22:25:36 +0000286 }
287}
288
289
290uint32_t LTOModule::getSymbolCount()
291{
292 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000293 return _symbols.size();
294}
295
296
297lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
298{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000299 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000300 if ( index < _symbols.size() )
301 return _symbols[index].attributes;
302 else
303 return lto_symbol_attributes(0);
304}
305
306const char* LTOModule::getSymbolName(uint32_t index)
307{
Nick Kledzikef194ed2008-02-27 22:25:36 +0000308 lazyParseSymbols();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000309 if ( index < _symbols.size() )
310 return _symbols[index].name;
311 else
312 return NULL;
313}
314