blob: 83fdbbe7d271bb9e3a588d51cd1041bb501b15cc [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"
Chris Lattneraf76e592009-08-22 20:48:53 +000032#include "llvm/MC/MCAsmInfo.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000033#include "llvm/MC/MCContext.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000034#include "llvm/MC/MCExpr.h"
35#include "llvm/MC/MCInst.h"
36#include "llvm/MC/MCParser/MCAsmParser.h"
37#include "llvm/MC/MCStreamer.h"
Evan Chengffc0e732011-07-09 05:47:46 +000038#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000039#include "llvm/MC/MCSymbol.h"
Evan Chengab8be962011-06-29 01:14:12 +000040#include "llvm/MC/SubtargetFeature.h"
Rafael Espindola38c4e532011-03-02 04:14:42 +000041#include "llvm/Target/TargetAsmParser.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000042#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetRegistry.h"
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000044#include "llvm/Target/TargetSelect.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000045
Nick Kledzik77595fc2008-02-26 20:26:43 +000046using namespace llvm;
47
Daniel Dunbarb06913d2010-08-10 23:46:39 +000048bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
49 return llvm::sys::IdentifyFileType((char*)mem, length)
50 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000051}
52
Daniel Dunbarb06913d2010-08-10 23:46:39 +000053bool LTOModule::isBitcodeFile(const char *path) {
54 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000055}
56
Daniel Dunbarb06913d2010-08-10 23:46:39 +000057bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
58 const char *triplePrefix) {
59 MemoryBuffer *buffer = makeBuffer(mem, length);
60 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000061 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000062 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000063}
64
Daniel Dunbarb06913d2010-08-10 23:46:39 +000065
66bool LTOModule::isBitcodeFileForTarget(const char *path,
67 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000068 OwningPtr<MemoryBuffer> buffer;
69 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000070 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000071 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000072}
73
74// Takes ownership of buffer.
75bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000076 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
77 delete buffer;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000078 return (strncmp(Triple.c_str(), triplePrefix,
Bill Wendling34711742010-10-06 01:22:42 +000079 strlen(triplePrefix)) == 0);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000080}
81
82
83LTOModule::LTOModule(Module *m, TargetMachine *t)
Rafael Espindola38c4e532011-03-02 04:14:42 +000084 : _module(m), _target(t)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000085{
Daniel Dunbarb06913d2010-08-10 23:46:39 +000086}
87
88LTOModule *LTOModule::makeLTOModule(const char *path,
89 std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000090 OwningPtr<MemoryBuffer> buffer;
91 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000092 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000093 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000094 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000095 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000096}
97
Rafael Espindolab4cc0312011-02-08 22:40:47 +000098LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Rafael Espindolaf21b1052011-03-17 00:36:11 +000099 size_t size,
100 std::string &errMsg) {
101 return makeLTOModule(fd, path, size, size, 0, errMsg);
102}
103
104LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
105 size_t file_size,
106 size_t map_size,
107 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000108 std::string &errMsg) {
109 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000110 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
111 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000112 errMsg = ec.message();
113 return NULL;
114 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000115 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000116}
117
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000118/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000119MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
120 const char *startPtr = (char*)mem;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000121 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000122}
123
124
125LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
126 std::string &errMsg) {
127 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
128 if (!buffer)
129 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000130 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000131}
132
133LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
134 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000135 static bool Initialized = false;
136 if (!Initialized) {
137 InitializeAllTargets();
138 InitializeAllAsmParsers();
139 Initialized = true;
140 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000141
142 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000143 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
144 &errMsg));
145 if (!m) {
146 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000147 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000148 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000149
150 std::string Triple = m->getTargetTriple();
151 if (Triple.empty())
152 Triple = sys::getHostTriple();
153
154 // find machine architecture for this module
155 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
156 if (!march)
157 return NULL;
158
Nick Lewycky333ed452011-04-21 01:54:08 +0000159 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000160 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000161 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000162 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000163 std::string CPU;
164 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000165 LTOModule *Ret = new LTOModule(m.take(), target);
166 bool Err = Ret->ParseSymbols();
167 if (Err) {
168 delete Ret;
169 return NULL;
170 }
171 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000172}
173
174
175const char *LTOModule::getTargetTriple() {
176 return _module->getTargetTriple().c_str();
177}
178
179void LTOModule::setTargetTriple(const char *triple) {
180 _module->setTargetTriple(triple);
181}
182
183void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
184 // add to list of defined symbols
185 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000186}
187
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000188// Get string that data pointer points to.
189bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
190 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
191 Constant *op = ce->getOperand(0);
192 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
193 Constant *cn = gvn->getInitializer();
194 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
195 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000196 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000197 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000198 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000199 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000200 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000201 }
202 return false;
203}
204
205// Parse i386/ppc ObjC class data structure.
206void LTOModule::addObjCClass(GlobalVariable *clgv) {
207 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
208 // second slot in __OBJC,__class is pointer to superclass name
209 std::string superclassName;
210 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
211 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000212 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000213 _undefines.GetOrCreateValue(superclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000214 if (!entry.getValue().name) {
215 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000216 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000217 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000218 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000219 }
220 }
221 // third slot in __OBJC,__class is pointer to class name
222 std::string className;
223 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000224 StringSet::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000225 _defines.GetOrCreateValue(className);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000226 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000227 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000228 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000229 info.attributes = (lto_symbol_attributes)
230 (LTO_SYMBOL_PERMISSIONS_DATA |
231 LTO_SYMBOL_DEFINITION_REGULAR |
232 LTO_SYMBOL_SCOPE_DEFAULT);
233 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000234 }
235 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000236}
237
238
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000239// Parse i386/ppc ObjC category data structure.
240void LTOModule::addObjCCategory(GlobalVariable *clgv) {
241 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
242 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000243 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000244 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
245 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000246
247 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000248 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000249
250 if (entry.getValue().name)
251 return;
252
253 const char *symbolName = entry.getKey().data();
254 info.name = symbolName;
255 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
256 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000257 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000258 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000259}
260
261
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000262// Parse i386/ppc ObjC class list data structure.
263void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
264 std::string targetclassName;
265 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000266 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000267
268 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000269 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000270 if (entry.getValue().name)
271 return;
272
273 const char *symbolName = entry.getKey().data();
274 info.name = symbolName;
275 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
276 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000277 }
278}
279
280
281void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
282 // Add to list of defined symbols.
283 addDefinedSymbol(v, mangler, false);
284
285 // Special case i386/ppc ObjC data structures in magic sections:
286 // The issue is that the old ObjC object format did some strange
287 // contortions to avoid real linker symbols. For instance, the
288 // ObjC class data structure is allocated statically in the executable
289 // that defines that class. That data structures contains a pointer to
290 // its superclass. But instead of just initializing that part of the
291 // struct to the address of its superclass, and letting the static and
292 // dynamic linkers do the rest, the runtime works by having that field
293 // instead point to a C-string that is the name of the superclass.
294 // At runtime the objc initialization updates that pointer and sets
295 // it to point to the actual super class. As far as the linker
296 // knows it is just a pointer to a string. But then someone wanted the
297 // linker to issue errors at build time if the superclass was not found.
298 // So they figured out a way in mach-o object format to use an absolute
299 // symbols (.objc_class_name_Foo = 0) and a floating reference
300 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
301 // a class was missing.
302 // The following synthesizes the implicit .objc_* symbols for the linker
303 // from the ObjC data structures generated by the front end.
304 if (v->hasSection() /* && isTargetDarwin */) {
305 // special case if this data blob is an ObjC class definition
306 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
307 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
308 addObjCClass(gv);
309 }
310 }
311
312 // special case if this data blob is an ObjC category definition
313 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
314 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
315 addObjCCategory(gv);
316 }
317 }
318
319 // special case if this data blob is the list of referenced classes
320 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
321 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
322 addObjCClassRef(gv);
323 }
324 }
325 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000326}
327
328
329void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
330 bool isFunction) {
331 // ignore all llvm.* symbols
332 if (def->getName().startswith("llvm."))
333 return;
334
335 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000336 SmallString<64> Buffer;
337 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000338
339 // set alignment part log2() can have rounding errors
340 uint32_t align = def->getAlignment();
341 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
342
343 // set permissions part
344 if (isFunction)
345 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
346 else {
347 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
348 if (gv && gv->isConstant())
349 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
350 else
351 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
352 }
353
354 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000355 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
356 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000357 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000358 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000359 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000360 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000361 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000362 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000363
364 // set scope part
365 if (def->hasHiddenVisibility())
366 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
367 else if (def->hasProtectedVisibility())
368 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000369 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
370 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
371 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000372 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000373 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
374 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000375 else
376 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
377
378 // add to table of symbols
379 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000380 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000381 entry.setValue(1);
382
383 StringRef Name = entry.getKey();
384 info.name = Name.data();
385 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000386 info.attributes = (lto_symbol_attributes)attr;
387 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000388}
389
Rafael Espindola38c4e532011-03-02 04:14:42 +0000390void LTOModule::addAsmGlobalSymbol(const char *name,
391 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000392 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
393
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000394 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000395 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000396 return;
397
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000398 entry.setValue(1);
399 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000400 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000401 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000402 NameAndAttributes info;
403 info.name = symbolName;
404 info.attributes = (lto_symbol_attributes)attr;
405 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000406}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000407
Rafael Espindola38c4e532011-03-02 04:14:42 +0000408void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
409 StringMap<NameAndAttributes>::value_type &entry =
410 _undefines.GetOrCreateValue(name);
411
412 _asm_undefines.push_back(entry.getKey().data());
413
414 // we already have the symbol
415 if (entry.getValue().name)
416 return;
417
418 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
419 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
420 NameAndAttributes info;
421 info.name = entry.getKey().data();
422 info.attributes = (lto_symbol_attributes)attr;
423
424 entry.setValue(info);
425}
426
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000427void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
428 Mangler &mangler) {
429 // ignore all llvm.* symbols
430 if (decl->getName().startswith("llvm."))
431 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000432
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000433 // ignore all aliases
434 if (isa<GlobalAlias>(decl))
435 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000436
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000437 SmallString<64> name;
438 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000439
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000440 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000441 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000442
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000443 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000444 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000445 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000446
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000447 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000448
449 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000450 if (decl->hasExternalWeakLinkage())
451 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
452 else
453 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000454
455 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000456}
457
458
Rafael Espindola38c4e532011-03-02 04:14:42 +0000459namespace {
460 class RecordStreamer : public MCStreamer {
461 public:
462 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000463
Rafael Espindola38c4e532011-03-02 04:14:42 +0000464 private:
465 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000466
Rafael Espindola38c4e532011-03-02 04:14:42 +0000467 void markDefined(const MCSymbol &Symbol) {
468 State &S = Symbols[Symbol.getName()];
469 switch (S) {
470 case DefinedGlobal:
471 case Global:
472 S = DefinedGlobal;
473 break;
474 case NeverSeen:
475 case Defined:
476 case Used:
477 S = Defined;
478 break;
479 }
480 }
481 void markGlobal(const MCSymbol &Symbol) {
482 State &S = Symbols[Symbol.getName()];
483 switch (S) {
484 case DefinedGlobal:
485 case Defined:
486 S = DefinedGlobal;
487 break;
488
489 case NeverSeen:
490 case Global:
491 case Used:
492 S = Global;
493 break;
494 }
495 }
496 void markUsed(const MCSymbol &Symbol) {
497 State &S = Symbols[Symbol.getName()];
498 switch (S) {
499 case DefinedGlobal:
500 case Defined:
501 case Global:
502 break;
503
504 case NeverSeen:
505 case Used:
506 S = Used;
507 break;
508 }
509 }
510
511 // FIXME: mostly copied for the obj streamer.
512 void AddValueSymbols(const MCExpr *Value) {
513 switch (Value->getKind()) {
514 case MCExpr::Target:
515 // FIXME: What should we do in here?
516 break;
517
518 case MCExpr::Constant:
519 break;
520
521 case MCExpr::Binary: {
522 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
523 AddValueSymbols(BE->getLHS());
524 AddValueSymbols(BE->getRHS());
525 break;
526 }
527
528 case MCExpr::SymbolRef:
529 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
530 break;
531
532 case MCExpr::Unary:
533 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
534 break;
535 }
536 }
537
538 public:
539 typedef StringMap<State>::const_iterator const_iterator;
540
541 const_iterator begin() {
542 return Symbols.begin();
543 }
544
545 const_iterator end() {
546 return Symbols.end();
547 }
548
549 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
550
551 virtual void ChangeSection(const MCSection *Section) {}
552 virtual void InitSections() {}
553 virtual void EmitLabel(MCSymbol *Symbol) {
554 Symbol->setSection(*getCurrentSection());
555 markDefined(*Symbol);
556 }
557 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
558 virtual void EmitThumbFunc(MCSymbol *Func) {}
559 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
560 // FIXME: should we handle aliases?
561 markDefined(*Symbol);
562 }
563 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
564 if (Attribute == MCSA_Global)
565 markGlobal(*Symbol);
566 }
567 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
568 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
569 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
570 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
571 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
572 unsigned Size , unsigned ByteAlignment) {
573 markDefined(*Symbol);
574 }
575 virtual void EmitCOFFSymbolType(int Type) {}
576 virtual void EndCOFFSymbolDef() {}
577 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
578 unsigned ByteAlignment) {
579 markDefined(*Symbol);
580 }
581 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
582 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
583 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
584 uint64_t Size, unsigned ByteAlignment) {}
585 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
586 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000587 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000588 virtual void EmitULEB128Value(const MCExpr *Value) {}
589 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000590 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
591 unsigned ValueSize,
592 unsigned MaxBytesToEmit) {}
593 virtual void EmitCodeAlignment(unsigned ByteAlignment,
594 unsigned MaxBytesToEmit) {}
595 virtual void EmitValueToOffset(const MCExpr *Offset,
596 unsigned char Value ) {}
597 virtual void EmitFileDirective(StringRef Filename) {}
598 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
599 const MCSymbol *LastLabel,
600 const MCSymbol *Label) {}
601
602 virtual void EmitInstruction(const MCInst &Inst) {
603 // Scan for values.
604 for (unsigned i = Inst.getNumOperands(); i--; )
605 if (Inst.getOperand(i).isExpr())
606 AddValueSymbols(Inst.getOperand(i).getExpr());
607 }
608 virtual void Finish() {}
609 };
610}
611
612bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
613 const std::string &inlineAsm = _module->getModuleInlineAsm();
614
615 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
616 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
617 SourceMgr SrcMgr;
618 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
619 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
620 Context, *Streamer,
621 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000622 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
623 createMCSubtargetInfo(_target->getTargetTriple(),
624 _target->getTargetCPU(),
625 _target->getTargetFeatureString()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000626 OwningPtr<TargetAsmParser>
Evan Chengffc0e732011-07-09 05:47:46 +0000627 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000628 Parser->setTargetParser(*TAP);
629 int Res = Parser->Run(false);
630 if (Res)
631 return true;
632
633 for (RecordStreamer::const_iterator i = Streamer->begin(),
634 e = Streamer->end(); i != e; ++i) {
635 StringRef Key = i->first();
636 RecordStreamer::State Value = i->second;
637 if (Value == RecordStreamer::DefinedGlobal)
638 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
639 else if (Value == RecordStreamer::Defined)
640 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
641 else if (Value == RecordStreamer::Global ||
642 Value == RecordStreamer::Used)
643 addAsmGlobalSymbolUndef(Key.data());
644 }
645 return false;
646}
647
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000648static bool isDeclaration(const GlobalValue &V) {
649 if (V.hasAvailableExternallyLinkage())
650 return true;
651 if (V.isMaterializable())
652 return false;
653 return V.isDeclaration();
654}
655
656static bool isAliasToDeclaration(const GlobalAlias &V) {
657 return isDeclaration(*V.getAliasedGlobal());
658}
659
Rafael Espindola38c4e532011-03-02 04:14:42 +0000660bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000661 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000662 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000663 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000664
Daniel Dunbare41d9002010-08-10 23:46:46 +0000665 // add functions
666 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000667 if (isDeclaration(*f))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000668 addPotentialUndefinedSymbol(f, mangler);
669 else
670 addDefinedFunctionSymbol(f, mangler);
671 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000672
Daniel Dunbare41d9002010-08-10 23:46:46 +0000673 // add data
674 for (Module::global_iterator v = _module->global_begin(),
675 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000676 if (isDeclaration(*v))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000677 addPotentialUndefinedSymbol(v, mangler);
678 else
679 addDefinedDataSymbol(v, mangler);
680 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000681
Daniel Dunbare41d9002010-08-10 23:46:46 +0000682 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000683 if (addAsmGlobalSymbols(Context))
684 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685
Rafael Espindola02003ca2010-10-20 04:57:22 +0000686 // add aliases
687 for (Module::alias_iterator i = _module->alias_begin(),
688 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000689 if (isAliasToDeclaration(*i))
Rafael Espindola02003ca2010-10-20 04:57:22 +0000690 addPotentialUndefinedSymbol(i, mangler);
691 else
692 addDefinedDataSymbol(i, mangler);
693 }
694
Daniel Dunbare41d9002010-08-10 23:46:46 +0000695 // make symbols for all undefines
696 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
697 it != _undefines.end(); ++it) {
698 // if this symbol also has a definition, then don't make an undefine
699 // because it is a tentative definition
700 if (_defines.count(it->getKey()) == 0) {
701 NameAndAttributes info = it->getValue();
702 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000703 }
704 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000705 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000706}
707
708
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000709uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000710 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000711}
712
713
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000714lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000715 if (index < _symbols.size())
716 return _symbols[index].attributes;
717 else
718 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000719}
720
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000721const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000722 if (index < _symbols.size())
723 return _symbols[index].name;
724 else
725 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000726}