blob: 06305eac0997a9d9f7bd004a6fbf3a275354caec [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();
Cameron Zwarichbf843e62011-07-11 22:19:51 +0000138 InitializeAllMCSubtargetInfos();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000139 InitializeAllAsmParsers();
140 Initialized = true;
141 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000142
143 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000144 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
145 &errMsg));
146 if (!m) {
147 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000148 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000149 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000150
151 std::string Triple = m->getTargetTriple();
152 if (Triple.empty())
153 Triple = sys::getHostTriple();
154
155 // find machine architecture for this module
156 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
157 if (!march)
158 return NULL;
159
Nick Lewycky333ed452011-04-21 01:54:08 +0000160 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000161 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000162 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000163 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000164 std::string CPU;
165 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000166 LTOModule *Ret = new LTOModule(m.take(), target);
167 bool Err = Ret->ParseSymbols();
168 if (Err) {
169 delete Ret;
170 return NULL;
171 }
172 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000173}
174
175
176const char *LTOModule::getTargetTriple() {
177 return _module->getTargetTriple().c_str();
178}
179
180void LTOModule::setTargetTriple(const char *triple) {
181 _module->setTargetTriple(triple);
182}
183
184void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
185 // add to list of defined symbols
186 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000187}
188
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000189// Get string that data pointer points to.
190bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
191 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
192 Constant *op = ce->getOperand(0);
193 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
194 Constant *cn = gvn->getInitializer();
195 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
196 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000197 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000198 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000199 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000200 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000201 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000202 }
203 return false;
204}
205
206// Parse i386/ppc ObjC class data structure.
207void LTOModule::addObjCClass(GlobalVariable *clgv) {
208 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
209 // second slot in __OBJC,__class is pointer to superclass name
210 std::string superclassName;
211 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
212 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000213 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000214 _undefines.GetOrCreateValue(superclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000215 if (!entry.getValue().name) {
216 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000217 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000218 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000219 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000220 }
221 }
222 // third slot in __OBJC,__class is pointer to class name
223 std::string className;
224 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000225 StringSet::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000226 _defines.GetOrCreateValue(className);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000227 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000228 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000229 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000230 info.attributes = (lto_symbol_attributes)
231 (LTO_SYMBOL_PERMISSIONS_DATA |
232 LTO_SYMBOL_DEFINITION_REGULAR |
233 LTO_SYMBOL_SCOPE_DEFAULT);
234 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000235 }
236 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000237}
238
239
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000240// Parse i386/ppc ObjC category data structure.
241void LTOModule::addObjCCategory(GlobalVariable *clgv) {
242 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
243 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000244 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000245 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
246 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000247
248 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000249 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000250
251 if (entry.getValue().name)
252 return;
253
254 const char *symbolName = entry.getKey().data();
255 info.name = symbolName;
256 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
257 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000258 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000259 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000260}
261
262
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000263// Parse i386/ppc ObjC class list data structure.
264void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
265 std::string targetclassName;
266 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000267 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000268
269 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000270 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000271 if (entry.getValue().name)
272 return;
273
274 const char *symbolName = entry.getKey().data();
275 info.name = symbolName;
276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
277 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000278 }
279}
280
281
282void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
283 // Add to list of defined symbols.
284 addDefinedSymbol(v, mangler, false);
285
286 // Special case i386/ppc ObjC data structures in magic sections:
287 // The issue is that the old ObjC object format did some strange
288 // contortions to avoid real linker symbols. For instance, the
289 // ObjC class data structure is allocated statically in the executable
290 // that defines that class. That data structures contains a pointer to
291 // its superclass. But instead of just initializing that part of the
292 // struct to the address of its superclass, and letting the static and
293 // dynamic linkers do the rest, the runtime works by having that field
294 // instead point to a C-string that is the name of the superclass.
295 // At runtime the objc initialization updates that pointer and sets
296 // it to point to the actual super class. As far as the linker
297 // knows it is just a pointer to a string. But then someone wanted the
298 // linker to issue errors at build time if the superclass was not found.
299 // So they figured out a way in mach-o object format to use an absolute
300 // symbols (.objc_class_name_Foo = 0) and a floating reference
301 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
302 // a class was missing.
303 // The following synthesizes the implicit .objc_* symbols for the linker
304 // from the ObjC data structures generated by the front end.
305 if (v->hasSection() /* && isTargetDarwin */) {
306 // special case if this data blob is an ObjC class definition
307 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
308 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
309 addObjCClass(gv);
310 }
311 }
312
313 // special case if this data blob is an ObjC category definition
314 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
315 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
316 addObjCCategory(gv);
317 }
318 }
319
320 // special case if this data blob is the list of referenced classes
321 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
322 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
323 addObjCClassRef(gv);
324 }
325 }
326 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000327}
328
329
330void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
331 bool isFunction) {
332 // ignore all llvm.* symbols
333 if (def->getName().startswith("llvm."))
334 return;
335
336 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000337 SmallString<64> Buffer;
338 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000339
340 // set alignment part log2() can have rounding errors
341 uint32_t align = def->getAlignment();
342 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
343
344 // set permissions part
345 if (isFunction)
346 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
347 else {
348 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
349 if (gv && gv->isConstant())
350 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
351 else
352 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
353 }
354
355 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000356 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
357 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000358 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000359 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000360 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000361 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000362 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000363 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000364
365 // set scope part
366 if (def->hasHiddenVisibility())
367 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
368 else if (def->hasProtectedVisibility())
369 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000370 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
371 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
372 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000373 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000374 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
375 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000376 else
377 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
378
379 // add to table of symbols
380 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000381 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000382 entry.setValue(1);
383
384 StringRef Name = entry.getKey();
385 info.name = Name.data();
386 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000387 info.attributes = (lto_symbol_attributes)attr;
388 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000389}
390
Rafael Espindola38c4e532011-03-02 04:14:42 +0000391void LTOModule::addAsmGlobalSymbol(const char *name,
392 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000393 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
394
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000395 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000396 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000397 return;
398
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000399 entry.setValue(1);
400 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000401 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000402 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000403 NameAndAttributes info;
404 info.name = symbolName;
405 info.attributes = (lto_symbol_attributes)attr;
406 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000407}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000408
Rafael Espindola38c4e532011-03-02 04:14:42 +0000409void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
410 StringMap<NameAndAttributes>::value_type &entry =
411 _undefines.GetOrCreateValue(name);
412
413 _asm_undefines.push_back(entry.getKey().data());
414
415 // we already have the symbol
416 if (entry.getValue().name)
417 return;
418
419 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
420 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
421 NameAndAttributes info;
422 info.name = entry.getKey().data();
423 info.attributes = (lto_symbol_attributes)attr;
424
425 entry.setValue(info);
426}
427
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000428void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
429 Mangler &mangler) {
430 // ignore all llvm.* symbols
431 if (decl->getName().startswith("llvm."))
432 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000433
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000434 // ignore all aliases
435 if (isa<GlobalAlias>(decl))
436 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000437
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000438 SmallString<64> name;
439 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000440
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000441 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000442 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000443
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000444 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000445 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000446 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000447
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000448 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000449
450 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000451 if (decl->hasExternalWeakLinkage())
452 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
453 else
454 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000455
456 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000457}
458
459
Rafael Espindola38c4e532011-03-02 04:14:42 +0000460namespace {
461 class RecordStreamer : public MCStreamer {
462 public:
463 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000464
Rafael Espindola38c4e532011-03-02 04:14:42 +0000465 private:
466 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000467
Rafael Espindola38c4e532011-03-02 04:14:42 +0000468 void markDefined(const MCSymbol &Symbol) {
469 State &S = Symbols[Symbol.getName()];
470 switch (S) {
471 case DefinedGlobal:
472 case Global:
473 S = DefinedGlobal;
474 break;
475 case NeverSeen:
476 case Defined:
477 case Used:
478 S = Defined;
479 break;
480 }
481 }
482 void markGlobal(const MCSymbol &Symbol) {
483 State &S = Symbols[Symbol.getName()];
484 switch (S) {
485 case DefinedGlobal:
486 case Defined:
487 S = DefinedGlobal;
488 break;
489
490 case NeverSeen:
491 case Global:
492 case Used:
493 S = Global;
494 break;
495 }
496 }
497 void markUsed(const MCSymbol &Symbol) {
498 State &S = Symbols[Symbol.getName()];
499 switch (S) {
500 case DefinedGlobal:
501 case Defined:
502 case Global:
503 break;
504
505 case NeverSeen:
506 case Used:
507 S = Used;
508 break;
509 }
510 }
511
512 // FIXME: mostly copied for the obj streamer.
513 void AddValueSymbols(const MCExpr *Value) {
514 switch (Value->getKind()) {
515 case MCExpr::Target:
516 // FIXME: What should we do in here?
517 break;
518
519 case MCExpr::Constant:
520 break;
521
522 case MCExpr::Binary: {
523 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
524 AddValueSymbols(BE->getLHS());
525 AddValueSymbols(BE->getRHS());
526 break;
527 }
528
529 case MCExpr::SymbolRef:
530 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
531 break;
532
533 case MCExpr::Unary:
534 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
535 break;
536 }
537 }
538
539 public:
540 typedef StringMap<State>::const_iterator const_iterator;
541
542 const_iterator begin() {
543 return Symbols.begin();
544 }
545
546 const_iterator end() {
547 return Symbols.end();
548 }
549
550 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
551
552 virtual void ChangeSection(const MCSection *Section) {}
553 virtual void InitSections() {}
554 virtual void EmitLabel(MCSymbol *Symbol) {
555 Symbol->setSection(*getCurrentSection());
556 markDefined(*Symbol);
557 }
558 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
559 virtual void EmitThumbFunc(MCSymbol *Func) {}
560 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
561 // FIXME: should we handle aliases?
562 markDefined(*Symbol);
563 }
564 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
565 if (Attribute == MCSA_Global)
566 markGlobal(*Symbol);
567 }
568 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
569 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
570 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
571 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
572 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
573 unsigned Size , unsigned ByteAlignment) {
574 markDefined(*Symbol);
575 }
576 virtual void EmitCOFFSymbolType(int Type) {}
577 virtual void EndCOFFSymbolDef() {}
578 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
579 unsigned ByteAlignment) {
580 markDefined(*Symbol);
581 }
582 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
583 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
584 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
585 uint64_t Size, unsigned ByteAlignment) {}
586 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
587 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000588 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000589 virtual void EmitULEB128Value(const MCExpr *Value) {}
590 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000591 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
592 unsigned ValueSize,
593 unsigned MaxBytesToEmit) {}
594 virtual void EmitCodeAlignment(unsigned ByteAlignment,
595 unsigned MaxBytesToEmit) {}
596 virtual void EmitValueToOffset(const MCExpr *Offset,
597 unsigned char Value ) {}
598 virtual void EmitFileDirective(StringRef Filename) {}
599 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
600 const MCSymbol *LastLabel,
601 const MCSymbol *Label) {}
602
603 virtual void EmitInstruction(const MCInst &Inst) {
604 // Scan for values.
605 for (unsigned i = Inst.getNumOperands(); i--; )
606 if (Inst.getOperand(i).isExpr())
607 AddValueSymbols(Inst.getOperand(i).getExpr());
608 }
609 virtual void Finish() {}
610 };
611}
612
613bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
614 const std::string &inlineAsm = _module->getModuleInlineAsm();
615
616 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
617 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
618 SourceMgr SrcMgr;
619 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
620 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
621 Context, *Streamer,
622 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000623 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
624 createMCSubtargetInfo(_target->getTargetTriple(),
625 _target->getTargetCPU(),
626 _target->getTargetFeatureString()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000627 OwningPtr<TargetAsmParser>
Evan Chengffc0e732011-07-09 05:47:46 +0000628 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000629 Parser->setTargetParser(*TAP);
630 int Res = Parser->Run(false);
631 if (Res)
632 return true;
633
634 for (RecordStreamer::const_iterator i = Streamer->begin(),
635 e = Streamer->end(); i != e; ++i) {
636 StringRef Key = i->first();
637 RecordStreamer::State Value = i->second;
638 if (Value == RecordStreamer::DefinedGlobal)
639 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
640 else if (Value == RecordStreamer::Defined)
641 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
642 else if (Value == RecordStreamer::Global ||
643 Value == RecordStreamer::Used)
644 addAsmGlobalSymbolUndef(Key.data());
645 }
646 return false;
647}
648
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000649static bool isDeclaration(const GlobalValue &V) {
650 if (V.hasAvailableExternallyLinkage())
651 return true;
652 if (V.isMaterializable())
653 return false;
654 return V.isDeclaration();
655}
656
657static bool isAliasToDeclaration(const GlobalAlias &V) {
658 return isDeclaration(*V.getAliasedGlobal());
659}
660
Rafael Espindola38c4e532011-03-02 04:14:42 +0000661bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000662 // Use mangler to add GlobalPrefix to names to match linker names.
Rafael Espindola89b93722010-12-10 07:39:47 +0000663 MCContext Context(*_target->getMCAsmInfo(), NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000664 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000665
Daniel Dunbare41d9002010-08-10 23:46:46 +0000666 // add functions
667 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000668 if (isDeclaration(*f))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000669 addPotentialUndefinedSymbol(f, mangler);
670 else
671 addDefinedFunctionSymbol(f, mangler);
672 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000673
Daniel Dunbare41d9002010-08-10 23:46:46 +0000674 // add data
675 for (Module::global_iterator v = _module->global_begin(),
676 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000677 if (isDeclaration(*v))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000678 addPotentialUndefinedSymbol(v, mangler);
679 else
680 addDefinedDataSymbol(v, mangler);
681 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000682
Daniel Dunbare41d9002010-08-10 23:46:46 +0000683 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000684 if (addAsmGlobalSymbols(Context))
685 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000686
Rafael Espindola02003ca2010-10-20 04:57:22 +0000687 // add aliases
688 for (Module::alias_iterator i = _module->alias_begin(),
689 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000690 if (isAliasToDeclaration(*i))
Rafael Espindola02003ca2010-10-20 04:57:22 +0000691 addPotentialUndefinedSymbol(i, mangler);
692 else
693 addDefinedDataSymbol(i, mangler);
694 }
695
Daniel Dunbare41d9002010-08-10 23:46:46 +0000696 // make symbols for all undefines
697 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
698 it != _undefines.end(); ++it) {
699 // if this symbol also has a definition, then don't make an undefine
700 // because it is a tentative definition
701 if (_defines.count(it->getKey()) == 0) {
702 NameAndAttributes info = it->getValue();
703 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000704 }
705 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000706 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000707}
708
709
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000710uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000711 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000712}
713
714
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000715lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000716 if (index < _symbols.size())
717 return _symbols[index].attributes;
718 else
719 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000720}
721
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000722const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000723 if (index < _symbols.size())
724 return _symbols[index].name;
725 else
726 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000727}