blob: 4e9e74f498496e7f719101647e138340abfba0e9 [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
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000117/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000118MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
119 const char *startPtr = (char*)mem;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000120 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000121}
122
123
124LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
125 std::string &errMsg) {
126 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
127 if (!buffer)
128 return NULL;
129 return makeLTOModule(buffer.get(), errMsg);
130}
131
132LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
133 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000134 static bool Initialized = false;
135 if (!Initialized) {
136 InitializeAllTargets();
137 InitializeAllAsmParsers();
138 Initialized = true;
139 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000140
141 // parse bitcode buffer
142 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
143 if (!m)
144 return NULL;
145
146 std::string Triple = m->getTargetTriple();
147 if (Triple.empty())
148 Triple = sys::getHostTriple();
149
150 // find machine architecture for this module
151 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
152 if (!march)
153 return NULL;
154
155 // construct LTModule, hand over ownership of module and target
156 SubtargetFeatures Features;
157 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
158 std::string FeatureStr = Features.getString();
159 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000160 LTOModule *Ret = new LTOModule(m.take(), target);
161 bool Err = Ret->ParseSymbols();
162 if (Err) {
163 delete Ret;
164 return NULL;
165 }
166 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000167}
168
169
170const char *LTOModule::getTargetTriple() {
171 return _module->getTargetTriple().c_str();
172}
173
174void LTOModule::setTargetTriple(const char *triple) {
175 _module->setTargetTriple(triple);
176}
177
178void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
179 // add to list of defined symbols
180 addDefinedSymbol(f, mangler, true);
181
182 // add external symbols referenced by this function.
183 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
184 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
185 for (unsigned count = 0, total = i->getNumOperands();
186 count != total; ++count) {
187 findExternalRefs(i->getOperand(count), mangler);
188 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000189 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000190 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000191}
192
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000193// Get string that data pointer points to.
194bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
195 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
196 Constant *op = ce->getOperand(0);
197 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
198 Constant *cn = gvn->getInitializer();
199 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
200 if (ca->isCString()) {
201 name = ".objc_class_name_" + ca->getAsString();
202 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000203 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000204 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000205 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000206 }
207 return false;
208}
209
210// Parse i386/ppc ObjC class data structure.
211void LTOModule::addObjCClass(GlobalVariable *clgv) {
212 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
213 // second slot in __OBJC,__class is pointer to superclass name
214 std::string superclassName;
215 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
216 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000217 StringMap<NameAndAttributes>::value_type &entry =
218 _undefines.GetOrCreateValue(superclassName.c_str());
219 if (!entry.getValue().name) {
220 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000221 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000222 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000223 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000224 }
225 }
226 // third slot in __OBJC,__class is pointer to class name
227 std::string className;
228 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000229 StringSet::value_type &entry =
230 _defines.GetOrCreateValue(className.c_str());
231 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000232 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000233 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000234 info.attributes = (lto_symbol_attributes)
235 (LTO_SYMBOL_PERMISSIONS_DATA |
236 LTO_SYMBOL_DEFINITION_REGULAR |
237 LTO_SYMBOL_SCOPE_DEFAULT);
238 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000239 }
240 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000241}
242
243
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000244// Parse i386/ppc ObjC category data structure.
245void LTOModule::addObjCCategory(GlobalVariable *clgv) {
246 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
247 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000248 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000249 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
250 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000251
252 StringMap<NameAndAttributes>::value_type &entry =
253 _undefines.GetOrCreateValue(targetclassName.c_str());
254
255 if (entry.getValue().name)
256 return;
257
258 const char *symbolName = entry.getKey().data();
259 info.name = symbolName;
260 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
261 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000262 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000263 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000264}
265
266
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000267// Parse i386/ppc ObjC class list data structure.
268void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
269 std::string targetclassName;
270 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000271 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000272
273 StringMap<NameAndAttributes>::value_type &entry =
274 _undefines.GetOrCreateValue(targetclassName.c_str());
275 if (entry.getValue().name)
276 return;
277
278 const char *symbolName = entry.getKey().data();
279 info.name = symbolName;
280 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
281 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000282 }
283}
284
285
286void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
287 // Add to list of defined symbols.
288 addDefinedSymbol(v, mangler, false);
289
290 // Special case i386/ppc ObjC data structures in magic sections:
291 // The issue is that the old ObjC object format did some strange
292 // contortions to avoid real linker symbols. For instance, the
293 // ObjC class data structure is allocated statically in the executable
294 // that defines that class. That data structures contains a pointer to
295 // its superclass. But instead of just initializing that part of the
296 // struct to the address of its superclass, and letting the static and
297 // dynamic linkers do the rest, the runtime works by having that field
298 // instead point to a C-string that is the name of the superclass.
299 // At runtime the objc initialization updates that pointer and sets
300 // it to point to the actual super class. As far as the linker
301 // knows it is just a pointer to a string. But then someone wanted the
302 // linker to issue errors at build time if the superclass was not found.
303 // So they figured out a way in mach-o object format to use an absolute
304 // symbols (.objc_class_name_Foo = 0) and a floating reference
305 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
306 // a class was missing.
307 // The following synthesizes the implicit .objc_* symbols for the linker
308 // from the ObjC data structures generated by the front end.
309 if (v->hasSection() /* && isTargetDarwin */) {
310 // special case if this data blob is an ObjC class definition
311 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
312 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
313 addObjCClass(gv);
314 }
315 }
316
317 // special case if this data blob is an ObjC category definition
318 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
319 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320 addObjCCategory(gv);
321 }
322 }
323
324 // special case if this data blob is the list of referenced classes
325 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
326 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
327 addObjCClassRef(gv);
328 }
329 }
330 }
331
332 // add external symbols referenced by this data.
333 for (unsigned count = 0, total = v->getNumOperands();
334 count != total; ++count) {
335 findExternalRefs(v->getOperand(count), mangler);
336 }
337}
338
339
340void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
341 bool isFunction) {
342 // ignore all llvm.* symbols
343 if (def->getName().startswith("llvm."))
344 return;
345
Rafael Espindola4cb310b2011-02-01 00:41:51 +0000346 // ignore available_externally
347 if (def->hasAvailableExternallyLinkage())
348 return;
349
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000350 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000351 SmallString<64> Buffer;
352 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000353
354 // set alignment part log2() can have rounding errors
355 uint32_t align = def->getAlignment();
356 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
357
358 // set permissions part
359 if (isFunction)
360 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
361 else {
362 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
363 if (gv && gv->isConstant())
364 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
365 else
366 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
367 }
368
369 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000370 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
371 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000372 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000373 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000374 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000375 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000376 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000377 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000378
379 // set scope part
380 if (def->hasHiddenVisibility())
381 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
382 else if (def->hasProtectedVisibility())
383 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000384 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
385 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
386 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000387 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000388 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
389 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000390 else
391 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
392
393 // add to table of symbols
394 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000395 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer.c_str());
396 entry.setValue(1);
397
398 StringRef Name = entry.getKey();
399 info.name = Name.data();
400 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000401 info.attributes = (lto_symbol_attributes)attr;
402 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000403}
404
Rafael Espindola38c4e532011-03-02 04:14:42 +0000405void LTOModule::addAsmGlobalSymbol(const char *name,
406 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000407 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
408
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000409 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000410 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000411 return;
412
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000413 entry.setValue(1);
414 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000415 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000416 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000417 NameAndAttributes info;
418 info.name = symbolName;
419 info.attributes = (lto_symbol_attributes)attr;
420 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000421}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000422
Rafael Espindola38c4e532011-03-02 04:14:42 +0000423void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
424 StringMap<NameAndAttributes>::value_type &entry =
425 _undefines.GetOrCreateValue(name);
426
427 _asm_undefines.push_back(entry.getKey().data());
428
429 // we already have the symbol
430 if (entry.getValue().name)
431 return;
432
433 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
434 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
435 NameAndAttributes info;
436 info.name = entry.getKey().data();
437 info.attributes = (lto_symbol_attributes)attr;
438
439 entry.setValue(info);
440}
441
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000442void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
443 Mangler &mangler) {
444 // ignore all llvm.* symbols
445 if (decl->getName().startswith("llvm."))
446 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000447
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000448 // ignore all aliases
449 if (isa<GlobalAlias>(decl))
450 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000451
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000452 SmallString<64> name;
453 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000454
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000455 StringMap<NameAndAttributes>::value_type &entry =
456 _undefines.GetOrCreateValue(name.c_str());
457
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000458 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000459 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000460 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000461
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000462 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000463
464 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000465 if (decl->hasExternalWeakLinkage())
466 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
467 else
468 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000469
470 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000471}
472
473
474
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000475// Find external symbols referenced by VALUE. This is a recursive function.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000476void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
477 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
478 if (!gv->hasExternalLinkage())
479 addPotentialUndefinedSymbol(gv, mangler);
480 // If this is a variable definition, do not recursively process
481 // initializer. It might contain a reference to this variable
482 // and cause an infinite loop. The initializer will be
483 // processed in addDefinedDataSymbol().
484 return;
485 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000486
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000487 // GlobalValue, even with InternalLinkage type, may have operands with
488 // ExternalLinkage type. Do not ignore these operands.
489 if (Constant *c = dyn_cast<Constant>(value)) {
490 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
491 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
492 findExternalRefs(c->getOperand(i), mangler);
493 }
494}
495
Rafael Espindola38c4e532011-03-02 04:14:42 +0000496namespace {
497 class RecordStreamer : public MCStreamer {
498 public:
499 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000500
Rafael Espindola38c4e532011-03-02 04:14:42 +0000501 private:
502 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000503
Rafael Espindola38c4e532011-03-02 04:14:42 +0000504 void markDefined(const MCSymbol &Symbol) {
505 State &S = Symbols[Symbol.getName()];
506 switch (S) {
507 case DefinedGlobal:
508 case Global:
509 S = DefinedGlobal;
510 break;
511 case NeverSeen:
512 case Defined:
513 case Used:
514 S = Defined;
515 break;
516 }
517 }
518 void markGlobal(const MCSymbol &Symbol) {
519 State &S = Symbols[Symbol.getName()];
520 switch (S) {
521 case DefinedGlobal:
522 case Defined:
523 S = DefinedGlobal;
524 break;
525
526 case NeverSeen:
527 case Global:
528 case Used:
529 S = Global;
530 break;
531 }
532 }
533 void markUsed(const MCSymbol &Symbol) {
534 State &S = Symbols[Symbol.getName()];
535 switch (S) {
536 case DefinedGlobal:
537 case Defined:
538 case Global:
539 break;
540
541 case NeverSeen:
542 case Used:
543 S = Used;
544 break;
545 }
546 }
547
548 // FIXME: mostly copied for the obj streamer.
549 void AddValueSymbols(const MCExpr *Value) {
550 switch (Value->getKind()) {
551 case MCExpr::Target:
552 // FIXME: What should we do in here?
553 break;
554
555 case MCExpr::Constant:
556 break;
557
558 case MCExpr::Binary: {
559 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
560 AddValueSymbols(BE->getLHS());
561 AddValueSymbols(BE->getRHS());
562 break;
563 }
564
565 case MCExpr::SymbolRef:
566 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
567 break;
568
569 case MCExpr::Unary:
570 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
571 break;
572 }
573 }
574
575 public:
576 typedef StringMap<State>::const_iterator const_iterator;
577
578 const_iterator begin() {
579 return Symbols.begin();
580 }
581
582 const_iterator end() {
583 return Symbols.end();
584 }
585
586 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
587
588 virtual void ChangeSection(const MCSection *Section) {}
589 virtual void InitSections() {}
590 virtual void EmitLabel(MCSymbol *Symbol) {
591 Symbol->setSection(*getCurrentSection());
592 markDefined(*Symbol);
593 }
594 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
595 virtual void EmitThumbFunc(MCSymbol *Func) {}
596 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
597 // FIXME: should we handle aliases?
598 markDefined(*Symbol);
599 }
600 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
601 if (Attribute == MCSA_Global)
602 markGlobal(*Symbol);
603 }
604 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
605 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
606 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
607 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
608 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
609 unsigned Size , unsigned ByteAlignment) {
610 markDefined(*Symbol);
611 }
612 virtual void EmitCOFFSymbolType(int Type) {}
613 virtual void EndCOFFSymbolDef() {}
614 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
615 unsigned ByteAlignment) {
616 markDefined(*Symbol);
617 }
618 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
619 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
620 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
621 uint64_t Size, unsigned ByteAlignment) {}
622 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
623 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
624 bool isPCRel, unsigned AddrSpace) {}
625 virtual void EmitULEB128Value(const MCExpr *Value,
626 unsigned AddrSpace = 0) {}
627 virtual void EmitSLEB128Value(const MCExpr *Value,
628 unsigned AddrSpace = 0) {}
629 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
630 unsigned ValueSize,
631 unsigned MaxBytesToEmit) {}
632 virtual void EmitCodeAlignment(unsigned ByteAlignment,
633 unsigned MaxBytesToEmit) {}
634 virtual void EmitValueToOffset(const MCExpr *Offset,
635 unsigned char Value ) {}
636 virtual void EmitFileDirective(StringRef Filename) {}
637 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
638 const MCSymbol *LastLabel,
639 const MCSymbol *Label) {}
640
641 virtual void EmitInstruction(const MCInst &Inst) {
642 // Scan for values.
643 for (unsigned i = Inst.getNumOperands(); i--; )
644 if (Inst.getOperand(i).isExpr())
645 AddValueSymbols(Inst.getOperand(i).getExpr());
646 }
647 virtual void Finish() {}
648 };
649}
650
651bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
652 const std::string &inlineAsm = _module->getModuleInlineAsm();
653
654 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
655 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
656 SourceMgr SrcMgr;
657 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
658 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
659 Context, *Streamer,
660 *_target->getMCAsmInfo()));
661 OwningPtr<TargetAsmParser>
662 TAP(_target->getTarget().createAsmParser(*Parser.get(), *_target.get()));
663 Parser->setTargetParser(*TAP);
664 int Res = Parser->Run(false);
665 if (Res)
666 return true;
667
668 for (RecordStreamer::const_iterator i = Streamer->begin(),
669 e = Streamer->end(); i != e; ++i) {
670 StringRef Key = i->first();
671 RecordStreamer::State Value = i->second;
672 if (Value == RecordStreamer::DefinedGlobal)
673 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
674 else if (Value == RecordStreamer::Defined)
675 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
676 else if (Value == RecordStreamer::Global ||
677 Value == RecordStreamer::Used)
678 addAsmGlobalSymbolUndef(Key.data());
679 }
680 return false;
681}
682
683bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000684 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000685 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000686 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000687
Daniel Dunbare41d9002010-08-10 23:46:46 +0000688 // add functions
689 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
690 if (f->isDeclaration())
691 addPotentialUndefinedSymbol(f, mangler);
692 else
693 addDefinedFunctionSymbol(f, mangler);
694 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000695
Daniel Dunbare41d9002010-08-10 23:46:46 +0000696 // add data
697 for (Module::global_iterator v = _module->global_begin(),
698 e = _module->global_end(); v != e; ++v) {
699 if (v->isDeclaration())
700 addPotentialUndefinedSymbol(v, mangler);
701 else
702 addDefinedDataSymbol(v, mangler);
703 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000704
Daniel Dunbare41d9002010-08-10 23:46:46 +0000705 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000706 if (addAsmGlobalSymbols(Context))
707 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000708
Rafael Espindola02003ca2010-10-20 04:57:22 +0000709 // add aliases
710 for (Module::alias_iterator i = _module->alias_begin(),
711 e = _module->alias_end(); i != e; ++i) {
712 if (i->isDeclaration())
713 addPotentialUndefinedSymbol(i, mangler);
714 else
715 addDefinedDataSymbol(i, mangler);
716 }
717
Daniel Dunbare41d9002010-08-10 23:46:46 +0000718 // make symbols for all undefines
719 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
720 it != _undefines.end(); ++it) {
721 // if this symbol also has a definition, then don't make an undefine
722 // because it is a tentative definition
723 if (_defines.count(it->getKey()) == 0) {
724 NameAndAttributes info = it->getValue();
725 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000726 }
727 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000728 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000729}
730
731
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000732uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000733 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000734}
735
736
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000737lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000738 if (index < _symbols.size())
739 return _symbols[index].attributes;
740 else
741 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000742}
743
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000744const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000745 if (index < _symbols.size())
746 return _symbols[index].name;
747 else
748 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000749}