blob: 9de3d5ffceeda59455510406c7d4ae3009782ab1 [file] [log] [blame]
Chris Lattner5ef31a02010-03-12 18:44:54 +00001//===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
Nick Kledzik77595fc2008-02-26 20:26:43 +00002//
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.
Daniel Dunbarb06913d2010-08-10 23:46:39 +00007//
Nick Kledzik77595fc2008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Daniel Dunbarb06913d2010-08-10 23:46:39 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik77595fc2008-02-26 20:26:43 +000011// 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 Kledzik3eb445f2009-06-01 20:33:09 +000017#include "llvm/Constants.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000018#include "llvm/LLVMContext.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000019#include "llvm/Module.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000020#include "llvm/ADT/OwningPtr.h"
Viktor Kutuzove823db82009-11-18 20:20:05 +000021#include "llvm/ADT/Triple.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000022#include "llvm/Bitcode/ReaderWriter.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000023#include "llvm/Support/SystemUtils.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000024#include "llvm/Support/MemoryBuffer.h"
Nick Kledzikef194ed2008-02-27 22:25:36 +000025#include "llvm/Support/MathExtras.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000026#include "llvm/Support/Host.h"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/Process.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000029#include "llvm/Support/SourceMgr.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000030#include "llvm/Support/system_error.h"
Chris Lattner45111d12010-01-16 21:57:06 +000031#include "llvm/Target/Mangler.h"
Bill Wendling604a8182008-06-18 06:35:30 +000032#include "llvm/Target/SubtargetFeature.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000033#include "llvm/MC/MCAsmInfo.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000034#include "llvm/MC/MCContext.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000035#include "llvm/MC/MCExpr.h"
36#include "llvm/MC/MCInst.h"
37#include "llvm/MC/MCParser/MCAsmParser.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
40#include "llvm/Target/TargetAsmParser.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000041#include "llvm/Target/TargetMachine.h"
42#include "llvm/Target/TargetRegistry.h"
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000043#include "llvm/Target/TargetSelect.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000044
Nick Kledzik77595fc2008-02-26 20:26:43 +000045using namespace llvm;
46
Daniel Dunbarb06913d2010-08-10 23:46:39 +000047bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
48 return llvm::sys::IdentifyFileType((char*)mem, length)
49 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000050}
51
Daniel Dunbarb06913d2010-08-10 23:46:39 +000052bool LTOModule::isBitcodeFile(const char *path) {
53 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000054}
55
Daniel Dunbarb06913d2010-08-10 23:46:39 +000056bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
57 const char *triplePrefix) {
58 MemoryBuffer *buffer = makeBuffer(mem, length);
59 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000060 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000061 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000062}
63
Daniel Dunbarb06913d2010-08-10 23:46:39 +000064
65bool LTOModule::isBitcodeFileForTarget(const char *path,
66 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000067 OwningPtr<MemoryBuffer> buffer;
68 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000069 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000070 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000071}
72
73// Takes ownership of buffer.
74bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000075 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
76 delete buffer;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000077 return (strncmp(Triple.c_str(), triplePrefix,
Bill Wendling34711742010-10-06 01:22:42 +000078 strlen(triplePrefix)) == 0);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000079}
80
81
82LTOModule::LTOModule(Module *m, TargetMachine *t)
Rafael Espindola38c4e532011-03-02 04:14:42 +000083 : _module(m), _target(t)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000084{
Daniel Dunbarb06913d2010-08-10 23:46:39 +000085}
86
87LTOModule *LTOModule::makeLTOModule(const char *path,
88 std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000089 OwningPtr<MemoryBuffer> buffer;
90 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000091 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000092 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000093 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +000094 return makeLTOModule(buffer.get(), errMsg);
95}
96
Rafael Espindolab4cc0312011-02-08 22:40:47 +000097LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Rafael Espindolaf21b1052011-03-17 00:36:11 +000098 size_t size,
99 std::string &errMsg) {
100 return makeLTOModule(fd, path, size, size, 0, errMsg);
101}
102
103LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
104 size_t file_size,
105 size_t map_size,
106 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000107 std::string &errMsg) {
108 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000109 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
110 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000111 errMsg = ec.message();
112 return NULL;
113 }
114 return makeLTOModule(buffer.get(), errMsg);
115}
116
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000117/// makeBuffer - Create a MemoryBuffer from a memory range. MemoryBuffer
118/// requires the byte past end of the buffer to be a zero. We might get lucky
119/// and already be that way, otherwise make a copy. Also if next byte is on a
120/// different page, don't assume it is readable.
121MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
122 const char *startPtr = (char*)mem;
123 const char *endPtr = startPtr+length;
124 if (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0 ||
125 *endPtr != 0)
126 return MemoryBuffer::getMemBufferCopy(StringRef(startPtr, length));
127
128 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length));
129}
130
131
132LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
133 std::string &errMsg) {
134 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
135 if (!buffer)
136 return NULL;
137 return makeLTOModule(buffer.get(), errMsg);
138}
139
140LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
141 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000142 static bool Initialized = false;
143 if (!Initialized) {
144 InitializeAllTargets();
145 InitializeAllAsmParsers();
146 Initialized = true;
147 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000148
149 // parse bitcode buffer
150 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
151 if (!m)
152 return NULL;
153
154 std::string Triple = m->getTargetTriple();
155 if (Triple.empty())
156 Triple = sys::getHostTriple();
157
158 // find machine architecture for this module
159 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
160 if (!march)
161 return NULL;
162
163 // construct LTModule, hand over ownership of module and target
164 SubtargetFeatures Features;
165 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
166 std::string FeatureStr = Features.getString();
167 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000168 LTOModule *Ret = new LTOModule(m.take(), target);
169 bool Err = Ret->ParseSymbols();
170 if (Err) {
171 delete Ret;
172 return NULL;
173 }
174 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000175}
176
177
178const char *LTOModule::getTargetTriple() {
179 return _module->getTargetTriple().c_str();
180}
181
182void LTOModule::setTargetTriple(const char *triple) {
183 _module->setTargetTriple(triple);
184}
185
186void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
187 // add to list of defined symbols
188 addDefinedSymbol(f, mangler, true);
189
190 // add external symbols referenced by this function.
191 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
192 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
193 for (unsigned count = 0, total = i->getNumOperands();
194 count != total; ++count) {
195 findExternalRefs(i->getOperand(count), mangler);
196 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000197 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000198 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000199}
200
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000201// Get string that data pointer points to.
202bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
203 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
204 Constant *op = ce->getOperand(0);
205 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
206 Constant *cn = gvn->getInitializer();
207 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
208 if (ca->isCString()) {
209 name = ".objc_class_name_" + ca->getAsString();
210 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000211 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000212 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000213 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000214 }
215 return false;
216}
217
218// Parse i386/ppc ObjC class data structure.
219void LTOModule::addObjCClass(GlobalVariable *clgv) {
220 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
221 // second slot in __OBJC,__class is pointer to superclass name
222 std::string superclassName;
223 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
224 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000225 StringMap<NameAndAttributes>::value_type &entry =
226 _undefines.GetOrCreateValue(superclassName.c_str());
227 if (!entry.getValue().name) {
228 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000229 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000230 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000231 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000232 }
233 }
234 // third slot in __OBJC,__class is pointer to class name
235 std::string className;
236 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000237 StringSet::value_type &entry =
238 _defines.GetOrCreateValue(className.c_str());
239 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000240 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000241 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000242 info.attributes = (lto_symbol_attributes)
243 (LTO_SYMBOL_PERMISSIONS_DATA |
244 LTO_SYMBOL_DEFINITION_REGULAR |
245 LTO_SYMBOL_SCOPE_DEFAULT);
246 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000247 }
248 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000249}
250
251
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000252// Parse i386/ppc ObjC category data structure.
253void LTOModule::addObjCCategory(GlobalVariable *clgv) {
254 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
255 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000256 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000257 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
258 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000259
260 StringMap<NameAndAttributes>::value_type &entry =
261 _undefines.GetOrCreateValue(targetclassName.c_str());
262
263 if (entry.getValue().name)
264 return;
265
266 const char *symbolName = entry.getKey().data();
267 info.name = symbolName;
268 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
269 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000270 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000271 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000272}
273
274
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000275// Parse i386/ppc ObjC class list data structure.
276void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
277 std::string targetclassName;
278 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000279 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000280
281 StringMap<NameAndAttributes>::value_type &entry =
282 _undefines.GetOrCreateValue(targetclassName.c_str());
283 if (entry.getValue().name)
284 return;
285
286 const char *symbolName = entry.getKey().data();
287 info.name = symbolName;
288 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
289 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000290 }
291}
292
293
294void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
295 // Add to list of defined symbols.
296 addDefinedSymbol(v, mangler, false);
297
298 // Special case i386/ppc ObjC data structures in magic sections:
299 // The issue is that the old ObjC object format did some strange
300 // contortions to avoid real linker symbols. For instance, the
301 // ObjC class data structure is allocated statically in the executable
302 // that defines that class. That data structures contains a pointer to
303 // its superclass. But instead of just initializing that part of the
304 // struct to the address of its superclass, and letting the static and
305 // dynamic linkers do the rest, the runtime works by having that field
306 // instead point to a C-string that is the name of the superclass.
307 // At runtime the objc initialization updates that pointer and sets
308 // it to point to the actual super class. As far as the linker
309 // knows it is just a pointer to a string. But then someone wanted the
310 // linker to issue errors at build time if the superclass was not found.
311 // So they figured out a way in mach-o object format to use an absolute
312 // symbols (.objc_class_name_Foo = 0) and a floating reference
313 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
314 // a class was missing.
315 // The following synthesizes the implicit .objc_* symbols for the linker
316 // from the ObjC data structures generated by the front end.
317 if (v->hasSection() /* && isTargetDarwin */) {
318 // special case if this data blob is an ObjC class definition
319 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
320 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
321 addObjCClass(gv);
322 }
323 }
324
325 // special case if this data blob is an ObjC category definition
326 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
327 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
328 addObjCCategory(gv);
329 }
330 }
331
332 // special case if this data blob is the list of referenced classes
333 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
334 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
335 addObjCClassRef(gv);
336 }
337 }
338 }
339
340 // add external symbols referenced by this data.
341 for (unsigned count = 0, total = v->getNumOperands();
342 count != total; ++count) {
343 findExternalRefs(v->getOperand(count), mangler);
344 }
345}
346
347
348void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
349 bool isFunction) {
350 // ignore all llvm.* symbols
351 if (def->getName().startswith("llvm."))
352 return;
353
Rafael Espindola4cb310b2011-02-01 00:41:51 +0000354 // ignore available_externally
355 if (def->hasAvailableExternallyLinkage())
356 return;
357
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000358 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000359 SmallString<64> Buffer;
360 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000361
362 // set alignment part log2() can have rounding errors
363 uint32_t align = def->getAlignment();
364 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
365
366 // set permissions part
367 if (isFunction)
368 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
369 else {
370 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
371 if (gv && gv->isConstant())
372 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
373 else
374 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
375 }
376
377 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000378 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
379 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000380 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000381 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000382 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000383 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000384 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000385 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000386
387 // set scope part
388 if (def->hasHiddenVisibility())
389 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
390 else if (def->hasProtectedVisibility())
391 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000392 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
393 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
394 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000395 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000396 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
397 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000398 else
399 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
400
401 // add to table of symbols
402 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000403 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
404 entry.setValue(1);
405
406 StringRef Name = entry.getKey();
407 info.name = Name.data();
408 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000409 info.attributes = (lto_symbol_attributes)attr;
410 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000411}
412
Rafael Espindola38c4e532011-03-02 04:14:42 +0000413void LTOModule::addAsmGlobalSymbol(const char *name,
414 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000415 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
416
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000417 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000418 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000419 return;
420
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000421 entry.setValue(1);
422 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000423 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000424 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000425 NameAndAttributes info;
426 info.name = symbolName;
427 info.attributes = (lto_symbol_attributes)attr;
428 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000429}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000430
Rafael Espindola38c4e532011-03-02 04:14:42 +0000431void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
432 StringMap<NameAndAttributes>::value_type &entry =
433 _undefines.GetOrCreateValue(name);
434
435 _asm_undefines.push_back(entry.getKey().data());
436
437 // we already have the symbol
438 if (entry.getValue().name)
439 return;
440
441 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
442 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
443 NameAndAttributes info;
444 info.name = entry.getKey().data();
445 info.attributes = (lto_symbol_attributes)attr;
446
447 entry.setValue(info);
448}
449
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000450void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
451 Mangler &mangler) {
452 // ignore all llvm.* symbols
453 if (decl->getName().startswith("llvm."))
454 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000455
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000456 // ignore all aliases
457 if (isa<GlobalAlias>(decl))
458 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000459
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000460 SmallString<64> name;
461 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000462
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000463 StringMap<NameAndAttributes>::value_type &entry =
464 _undefines.GetOrCreateValue(name.c_str());
465
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000466 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000467 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000468 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000469
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000470 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000471
472 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000473 if (decl->hasExternalWeakLinkage())
474 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
475 else
476 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000477
478 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000479}
480
481
482
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000483// Find external symbols referenced by VALUE. This is a recursive function.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000484void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
485 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
486 if (!gv->hasExternalLinkage())
487 addPotentialUndefinedSymbol(gv, mangler);
488 // If this is a variable definition, do not recursively process
489 // initializer. It might contain a reference to this variable
490 // and cause an infinite loop. The initializer will be
491 // processed in addDefinedDataSymbol().
492 return;
493 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000494
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000495 // GlobalValue, even with InternalLinkage type, may have operands with
496 // ExternalLinkage type. Do not ignore these operands.
497 if (Constant *c = dyn_cast<Constant>(value)) {
498 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
499 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
500 findExternalRefs(c->getOperand(i), mangler);
501 }
502}
503
Rafael Espindola38c4e532011-03-02 04:14:42 +0000504namespace {
505 class RecordStreamer : public MCStreamer {
506 public:
507 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000508
Rafael Espindola38c4e532011-03-02 04:14:42 +0000509 private:
510 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000511
Rafael Espindola38c4e532011-03-02 04:14:42 +0000512 void markDefined(const MCSymbol &Symbol) {
513 State &S = Symbols[Symbol.getName()];
514 switch (S) {
515 case DefinedGlobal:
516 case Global:
517 S = DefinedGlobal;
518 break;
519 case NeverSeen:
520 case Defined:
521 case Used:
522 S = Defined;
523 break;
524 }
525 }
526 void markGlobal(const MCSymbol &Symbol) {
527 State &S = Symbols[Symbol.getName()];
528 switch (S) {
529 case DefinedGlobal:
530 case Defined:
531 S = DefinedGlobal;
532 break;
533
534 case NeverSeen:
535 case Global:
536 case Used:
537 S = Global;
538 break;
539 }
540 }
541 void markUsed(const MCSymbol &Symbol) {
542 State &S = Symbols[Symbol.getName()];
543 switch (S) {
544 case DefinedGlobal:
545 case Defined:
546 case Global:
547 break;
548
549 case NeverSeen:
550 case Used:
551 S = Used;
552 break;
553 }
554 }
555
556 // FIXME: mostly copied for the obj streamer.
557 void AddValueSymbols(const MCExpr *Value) {
558 switch (Value->getKind()) {
559 case MCExpr::Target:
560 // FIXME: What should we do in here?
561 break;
562
563 case MCExpr::Constant:
564 break;
565
566 case MCExpr::Binary: {
567 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
568 AddValueSymbols(BE->getLHS());
569 AddValueSymbols(BE->getRHS());
570 break;
571 }
572
573 case MCExpr::SymbolRef:
574 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
575 break;
576
577 case MCExpr::Unary:
578 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
579 break;
580 }
581 }
582
583 public:
584 typedef StringMap<State>::const_iterator const_iterator;
585
586 const_iterator begin() {
587 return Symbols.begin();
588 }
589
590 const_iterator end() {
591 return Symbols.end();
592 }
593
594 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
595
596 virtual void ChangeSection(const MCSection *Section) {}
597 virtual void InitSections() {}
598 virtual void EmitLabel(MCSymbol *Symbol) {
599 Symbol->setSection(*getCurrentSection());
600 markDefined(*Symbol);
601 }
602 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
603 virtual void EmitThumbFunc(MCSymbol *Func) {}
604 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
605 // FIXME: should we handle aliases?
606 markDefined(*Symbol);
607 }
608 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
609 if (Attribute == MCSA_Global)
610 markGlobal(*Symbol);
611 }
612 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
613 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
614 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
615 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
616 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
617 unsigned Size , unsigned ByteAlignment) {
618 markDefined(*Symbol);
619 }
620 virtual void EmitCOFFSymbolType(int Type) {}
621 virtual void EndCOFFSymbolDef() {}
622 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
623 unsigned ByteAlignment) {
624 markDefined(*Symbol);
625 }
626 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
627 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
628 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
629 uint64_t Size, unsigned ByteAlignment) {}
630 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
631 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
632 bool isPCRel, unsigned AddrSpace) {}
633 virtual void EmitULEB128Value(const MCExpr *Value,
634 unsigned AddrSpace = 0) {}
635 virtual void EmitSLEB128Value(const MCExpr *Value,
636 unsigned AddrSpace = 0) {}
637 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
638 unsigned ValueSize,
639 unsigned MaxBytesToEmit) {}
640 virtual void EmitCodeAlignment(unsigned ByteAlignment,
641 unsigned MaxBytesToEmit) {}
642 virtual void EmitValueToOffset(const MCExpr *Offset,
643 unsigned char Value ) {}
644 virtual void EmitFileDirective(StringRef Filename) {}
645 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
646 const MCSymbol *LastLabel,
647 const MCSymbol *Label) {}
648
649 virtual void EmitInstruction(const MCInst &Inst) {
650 // Scan for values.
651 for (unsigned i = Inst.getNumOperands(); i--; )
652 if (Inst.getOperand(i).isExpr())
653 AddValueSymbols(Inst.getOperand(i).getExpr());
654 }
655 virtual void Finish() {}
656 };
657}
658
659bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
660 const std::string &inlineAsm = _module->getModuleInlineAsm();
661
662 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
663 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
664 SourceMgr SrcMgr;
665 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
666 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
667 Context, *Streamer,
668 *_target->getMCAsmInfo()));
669 OwningPtr<TargetAsmParser>
670 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
671 Parser->setTargetParser(*TAP);
672 int Res = Parser->Run(false);
673 if (Res)
674 return true;
675
676 for (RecordStreamer::const_iterator i = Streamer->begin(),
677 e = Streamer->end(); i != e; ++i) {
678 StringRef Key = i->first();
679 RecordStreamer::State Value = i->second;
680 if (Value == RecordStreamer::DefinedGlobal)
681 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
682 else if (Value == RecordStreamer::Defined)
683 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
684 else if (Value == RecordStreamer::Global ||
685 Value == RecordStreamer::Used)
686 addAsmGlobalSymbolUndef(Key.data());
687 }
688 return false;
689}
690
691bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000692 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000693 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000694 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000695
Daniel Dunbare41d9002010-08-10 23:46:46 +0000696 // add functions
697 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
698 if (f->isDeclaration())
699 addPotentialUndefinedSymbol(f, mangler);
700 else
701 addDefinedFunctionSymbol(f, mangler);
702 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000703
Daniel Dunbare41d9002010-08-10 23:46:46 +0000704 // add data
705 for (Module::global_iterator v = _module->global_begin(),
706 e = _module->global_end(); v != e; ++v) {
707 if (v->isDeclaration())
708 addPotentialUndefinedSymbol(v, mangler);
709 else
710 addDefinedDataSymbol(v, mangler);
711 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000712
Daniel Dunbare41d9002010-08-10 23:46:46 +0000713 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000714 if (addAsmGlobalSymbols(Context))
715 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000716
Rafael Espindola02003ca2010-10-20 04:57:22 +0000717 // add aliases
718 for (Module::alias_iterator i = _module->alias_begin(),
719 e = _module->alias_end(); i != e; ++i) {
720 if (i->isDeclaration())
721 addPotentialUndefinedSymbol(i, mangler);
722 else
723 addDefinedDataSymbol(i, mangler);
724 }
725
Daniel Dunbare41d9002010-08-10 23:46:46 +0000726 // make symbols for all undefines
727 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
728 it != _undefines.end(); ++it) {
729 // if this symbol also has a definition, then don't make an undefine
730 // because it is a tentative definition
731 if (_defines.count(it->getKey()) == 0) {
732 NameAndAttributes info = it->getValue();
733 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000734 }
735 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000736 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000737}
738
739
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000740uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000741 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000742}
743
744
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000745lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000746 if (index < _symbols.size())
747 return _symbols[index].attributes;
748 else
749 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000750}
751
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000752const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000753 if (index < _symbols.size())
754 return _symbols[index].name;
755 else
756 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000757}