blob: 92b2e9aa1a561695a4dcc77b2304d2e072fccc22 [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"
Evan Cheng0e6a0522011-07-18 20:57:22 +000043#include "llvm/Target/TargetRegisterInfo.h"
Daniel Dunbarff9834a2009-07-16 02:41:19 +000044#include "llvm/Target/TargetRegistry.h"
Nick Lewyckyd42b58b2009-07-26 22:16:39 +000045#include "llvm/Target/TargetSelect.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000046
Nick Kledzik77595fc2008-02-26 20:26:43 +000047using namespace llvm;
48
Daniel Dunbarb06913d2010-08-10 23:46:39 +000049bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
50 return llvm::sys::IdentifyFileType((char*)mem, length)
51 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000052}
53
Daniel Dunbarb06913d2010-08-10 23:46:39 +000054bool LTOModule::isBitcodeFile(const char *path) {
55 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000056}
57
Daniel Dunbarb06913d2010-08-10 23:46:39 +000058bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
59 const char *triplePrefix) {
60 MemoryBuffer *buffer = makeBuffer(mem, length);
61 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000062 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000063 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000064}
65
Daniel Dunbarb06913d2010-08-10 23:46:39 +000066
67bool LTOModule::isBitcodeFileForTarget(const char *path,
68 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000069 OwningPtr<MemoryBuffer> buffer;
70 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000071 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000072 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000073}
74
75// Takes ownership of buffer.
76bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000077 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
78 delete buffer;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000079 return (strncmp(Triple.c_str(), triplePrefix,
Bill Wendling34711742010-10-06 01:22:42 +000080 strlen(triplePrefix)) == 0);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000081}
82
83
84LTOModule::LTOModule(Module *m, TargetMachine *t)
Rafael Espindola38c4e532011-03-02 04:14:42 +000085 : _module(m), _target(t)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000086{
Daniel Dunbarb06913d2010-08-10 23:46:39 +000087}
88
89LTOModule *LTOModule::makeLTOModule(const char *path,
90 std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000091 OwningPtr<MemoryBuffer> buffer;
92 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000093 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000094 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000095 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000096 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000097}
98
Rafael Espindolab4cc0312011-02-08 22:40:47 +000099LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000100 size_t size,
101 std::string &errMsg) {
102 return makeLTOModule(fd, path, size, size, 0, errMsg);
103}
104
105LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
106 size_t file_size,
107 size_t map_size,
108 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000109 std::string &errMsg) {
110 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000111 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
112 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000113 errMsg = ec.message();
114 return NULL;
115 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000116 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000117}
118
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000119/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000120MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
121 const char *startPtr = (char*)mem;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000122 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000123}
124
125
126LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
127 std::string &errMsg) {
128 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
129 if (!buffer)
130 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000131 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000132}
133
134LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
135 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000136 static bool Initialized = false;
137 if (!Initialized) {
138 InitializeAllTargets();
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000139 InitializeAllMCAsmInfos();
Cameron Zwarichbf843e62011-07-11 22:19:51 +0000140 InitializeAllMCSubtargetInfos();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000141 InitializeAllAsmParsers();
142 Initialized = true;
143 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000144
145 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000146 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
147 &errMsg));
148 if (!m) {
149 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000150 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000151 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000152
153 std::string Triple = m->getTargetTriple();
154 if (Triple.empty())
155 Triple = sys::getHostTriple();
156
157 // find machine architecture for this module
158 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
159 if (!march)
160 return NULL;
161
Nick Lewycky333ed452011-04-21 01:54:08 +0000162 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000163 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000164 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000165 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000166 std::string CPU;
167 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000168 LTOModule *Ret = new LTOModule(m.take(), target);
169 bool Err = Ret->ParseSymbols();
170 if (Err) {
171 delete Ret;
172 return NULL;
173 }
174 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000175}
176
177
178const char *LTOModule::getTargetTriple() {
179 return _module->getTargetTriple().c_str();
180}
181
182void LTOModule::setTargetTriple(const char *triple) {
183 _module->setTargetTriple(triple);
184}
185
186void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
187 // add to list of defined symbols
188 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000189}
190
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000191// Get string that data pointer points to.
192bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
193 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
194 Constant *op = ce->getOperand(0);
195 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
196 Constant *cn = gvn->getInitializer();
197 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
198 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000199 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000200 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000201 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000202 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000203 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000204 }
205 return false;
206}
207
208// Parse i386/ppc ObjC class data structure.
209void LTOModule::addObjCClass(GlobalVariable *clgv) {
210 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
211 // second slot in __OBJC,__class is pointer to superclass name
212 std::string superclassName;
213 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
214 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000215 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000216 _undefines.GetOrCreateValue(superclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000217 if (!entry.getValue().name) {
218 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000219 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000220 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000221 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000222 }
223 }
224 // third slot in __OBJC,__class is pointer to class name
225 std::string className;
226 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000227 StringSet::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000228 _defines.GetOrCreateValue(className);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000229 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000230 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000231 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000232 info.attributes = (lto_symbol_attributes)
233 (LTO_SYMBOL_PERMISSIONS_DATA |
234 LTO_SYMBOL_DEFINITION_REGULAR |
235 LTO_SYMBOL_SCOPE_DEFAULT);
236 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000237 }
238 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000239}
240
241
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000242// Parse i386/ppc ObjC category data structure.
243void LTOModule::addObjCCategory(GlobalVariable *clgv) {
244 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
245 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000246 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000247 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
248 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000249
250 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000251 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000252
253 if (entry.getValue().name)
254 return;
255
256 const char *symbolName = entry.getKey().data();
257 info.name = symbolName;
258 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
259 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000260 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000261 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000262}
263
264
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000265// Parse i386/ppc ObjC class list data structure.
266void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
267 std::string targetclassName;
268 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000269 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000270
271 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000272 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000273 if (entry.getValue().name)
274 return;
275
276 const char *symbolName = entry.getKey().data();
277 info.name = symbolName;
278 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
279 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000280 }
281}
282
283
284void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
285 // Add to list of defined symbols.
286 addDefinedSymbol(v, mangler, false);
287
288 // Special case i386/ppc ObjC data structures in magic sections:
289 // The issue is that the old ObjC object format did some strange
290 // contortions to avoid real linker symbols. For instance, the
291 // ObjC class data structure is allocated statically in the executable
292 // that defines that class. That data structures contains a pointer to
293 // its superclass. But instead of just initializing that part of the
294 // struct to the address of its superclass, and letting the static and
295 // dynamic linkers do the rest, the runtime works by having that field
296 // instead point to a C-string that is the name of the superclass.
297 // At runtime the objc initialization updates that pointer and sets
298 // it to point to the actual super class. As far as the linker
299 // knows it is just a pointer to a string. But then someone wanted the
300 // linker to issue errors at build time if the superclass was not found.
301 // So they figured out a way in mach-o object format to use an absolute
302 // symbols (.objc_class_name_Foo = 0) and a floating reference
303 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
304 // a class was missing.
305 // The following synthesizes the implicit .objc_* symbols for the linker
306 // from the ObjC data structures generated by the front end.
307 if (v->hasSection() /* && isTargetDarwin */) {
308 // special case if this data blob is an ObjC class definition
309 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
310 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
311 addObjCClass(gv);
312 }
313 }
314
315 // special case if this data blob is an ObjC category definition
316 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
317 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
318 addObjCCategory(gv);
319 }
320 }
321
322 // special case if this data blob is the list of referenced classes
323 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
324 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
325 addObjCClassRef(gv);
326 }
327 }
328 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000329}
330
331
332void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
333 bool isFunction) {
334 // ignore all llvm.* symbols
335 if (def->getName().startswith("llvm."))
336 return;
337
338 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000339 SmallString<64> Buffer;
340 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000341
342 // set alignment part log2() can have rounding errors
343 uint32_t align = def->getAlignment();
344 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
345
346 // set permissions part
347 if (isFunction)
348 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
349 else {
350 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
351 if (gv && gv->isConstant())
352 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
353 else
354 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
355 }
356
357 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000358 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
359 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000360 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000361 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000362 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000363 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000364 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000365 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000366
367 // set scope part
368 if (def->hasHiddenVisibility())
369 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
370 else if (def->hasProtectedVisibility())
371 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000372 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
373 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
374 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000375 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000376 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
377 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000378 else
379 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
380
381 // add to table of symbols
382 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000383 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000384 entry.setValue(1);
385
386 StringRef Name = entry.getKey();
387 info.name = Name.data();
388 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000389 info.attributes = (lto_symbol_attributes)attr;
390 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000391}
392
Rafael Espindola38c4e532011-03-02 04:14:42 +0000393void LTOModule::addAsmGlobalSymbol(const char *name,
394 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000395 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
396
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000397 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000398 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000399 return;
400
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000401 entry.setValue(1);
402 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000403 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000404 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000405 NameAndAttributes info;
406 info.name = symbolName;
407 info.attributes = (lto_symbol_attributes)attr;
408 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000409}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000410
Rafael Espindola38c4e532011-03-02 04:14:42 +0000411void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
412 StringMap<NameAndAttributes>::value_type &entry =
413 _undefines.GetOrCreateValue(name);
414
415 _asm_undefines.push_back(entry.getKey().data());
416
417 // we already have the symbol
418 if (entry.getValue().name)
419 return;
420
421 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
422 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
423 NameAndAttributes info;
424 info.name = entry.getKey().data();
425 info.attributes = (lto_symbol_attributes)attr;
426
427 entry.setValue(info);
428}
429
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000430void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
431 Mangler &mangler) {
432 // ignore all llvm.* symbols
433 if (decl->getName().startswith("llvm."))
434 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000435
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000436 // ignore all aliases
437 if (isa<GlobalAlias>(decl))
438 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000439
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000440 SmallString<64> name;
441 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000442
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000443 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000444 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000445
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000446 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000447 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000448 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000449
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000450 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000451
452 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000453 if (decl->hasExternalWeakLinkage())
454 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
455 else
456 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000457
458 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000459}
460
461
Rafael Espindola38c4e532011-03-02 04:14:42 +0000462namespace {
463 class RecordStreamer : public MCStreamer {
464 public:
465 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000466
Rafael Espindola38c4e532011-03-02 04:14:42 +0000467 private:
468 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000469
Rafael Espindola38c4e532011-03-02 04:14:42 +0000470 void markDefined(const MCSymbol &Symbol) {
471 State &S = Symbols[Symbol.getName()];
472 switch (S) {
473 case DefinedGlobal:
474 case Global:
475 S = DefinedGlobal;
476 break;
477 case NeverSeen:
478 case Defined:
479 case Used:
480 S = Defined;
481 break;
482 }
483 }
484 void markGlobal(const MCSymbol &Symbol) {
485 State &S = Symbols[Symbol.getName()];
486 switch (S) {
487 case DefinedGlobal:
488 case Defined:
489 S = DefinedGlobal;
490 break;
491
492 case NeverSeen:
493 case Global:
494 case Used:
495 S = Global;
496 break;
497 }
498 }
499 void markUsed(const MCSymbol &Symbol) {
500 State &S = Symbols[Symbol.getName()];
501 switch (S) {
502 case DefinedGlobal:
503 case Defined:
504 case Global:
505 break;
506
507 case NeverSeen:
508 case Used:
509 S = Used;
510 break;
511 }
512 }
513
514 // FIXME: mostly copied for the obj streamer.
515 void AddValueSymbols(const MCExpr *Value) {
516 switch (Value->getKind()) {
517 case MCExpr::Target:
518 // FIXME: What should we do in here?
519 break;
520
521 case MCExpr::Constant:
522 break;
523
524 case MCExpr::Binary: {
525 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
526 AddValueSymbols(BE->getLHS());
527 AddValueSymbols(BE->getRHS());
528 break;
529 }
530
531 case MCExpr::SymbolRef:
532 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
533 break;
534
535 case MCExpr::Unary:
536 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
537 break;
538 }
539 }
540
541 public:
542 typedef StringMap<State>::const_iterator const_iterator;
543
544 const_iterator begin() {
545 return Symbols.begin();
546 }
547
548 const_iterator end() {
549 return Symbols.end();
550 }
551
552 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
553
554 virtual void ChangeSection(const MCSection *Section) {}
555 virtual void InitSections() {}
556 virtual void EmitLabel(MCSymbol *Symbol) {
557 Symbol->setSection(*getCurrentSection());
558 markDefined(*Symbol);
559 }
560 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
561 virtual void EmitThumbFunc(MCSymbol *Func) {}
562 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
563 // FIXME: should we handle aliases?
564 markDefined(*Symbol);
565 }
566 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
567 if (Attribute == MCSA_Global)
568 markGlobal(*Symbol);
569 }
570 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
571 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
572 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
573 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
574 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
575 unsigned Size , unsigned ByteAlignment) {
576 markDefined(*Symbol);
577 }
578 virtual void EmitCOFFSymbolType(int Type) {}
579 virtual void EndCOFFSymbolDef() {}
580 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
581 unsigned ByteAlignment) {
582 markDefined(*Symbol);
583 }
584 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
585 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
586 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
587 uint64_t Size, unsigned ByteAlignment) {}
588 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
589 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000590 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000591 virtual void EmitULEB128Value(const MCExpr *Value) {}
592 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000593 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
594 unsigned ValueSize,
595 unsigned MaxBytesToEmit) {}
596 virtual void EmitCodeAlignment(unsigned ByteAlignment,
597 unsigned MaxBytesToEmit) {}
598 virtual void EmitValueToOffset(const MCExpr *Offset,
599 unsigned char Value ) {}
600 virtual void EmitFileDirective(StringRef Filename) {}
601 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
602 const MCSymbol *LastLabel,
Evan Cheng672b93a2011-07-14 05:43:07 +0000603 const MCSymbol *Label,
604 unsigned PointerSize) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000605
606 virtual void EmitInstruction(const MCInst &Inst) {
607 // Scan for values.
608 for (unsigned i = Inst.getNumOperands(); i--; )
609 if (Inst.getOperand(i).isExpr())
610 AddValueSymbols(Inst.getOperand(i).getExpr());
611 }
612 virtual void Finish() {}
613 };
614}
615
616bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
617 const std::string &inlineAsm = _module->getModuleInlineAsm();
618
619 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
620 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
621 SourceMgr SrcMgr;
622 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
623 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
624 Context, *Streamer,
625 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000626 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
627 createMCSubtargetInfo(_target->getTargetTriple(),
628 _target->getTargetCPU(),
629 _target->getTargetFeatureString()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000630 OwningPtr<TargetAsmParser>
Evan Chengffc0e732011-07-09 05:47:46 +0000631 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000632 Parser->setTargetParser(*TAP);
633 int Res = Parser->Run(false);
634 if (Res)
635 return true;
636
637 for (RecordStreamer::const_iterator i = Streamer->begin(),
638 e = Streamer->end(); i != e; ++i) {
639 StringRef Key = i->first();
640 RecordStreamer::State Value = i->second;
641 if (Value == RecordStreamer::DefinedGlobal)
642 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
643 else if (Value == RecordStreamer::Defined)
644 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
645 else if (Value == RecordStreamer::Global ||
646 Value == RecordStreamer::Used)
647 addAsmGlobalSymbolUndef(Key.data());
648 }
649 return false;
650}
651
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000652static bool isDeclaration(const GlobalValue &V) {
653 if (V.hasAvailableExternallyLinkage())
654 return true;
655 if (V.isMaterializable())
656 return false;
657 return V.isDeclaration();
658}
659
660static bool isAliasToDeclaration(const GlobalAlias &V) {
661 return isDeclaration(*V.getAliasedGlobal());
662}
663
Rafael Espindola38c4e532011-03-02 04:14:42 +0000664bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000665 // Use mangler to add GlobalPrefix to names to match linker names.
Evan Cheng0e6a0522011-07-18 20:57:22 +0000666 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),
667 NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000668 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000669
Daniel Dunbare41d9002010-08-10 23:46:46 +0000670 // add functions
671 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000672 if (isDeclaration(*f))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000673 addPotentialUndefinedSymbol(f, mangler);
674 else
675 addDefinedFunctionSymbol(f, mangler);
676 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000677
Daniel Dunbare41d9002010-08-10 23:46:46 +0000678 // add data
679 for (Module::global_iterator v = _module->global_begin(),
680 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000681 if (isDeclaration(*v))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000682 addPotentialUndefinedSymbol(v, mangler);
683 else
684 addDefinedDataSymbol(v, mangler);
685 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000686
Daniel Dunbare41d9002010-08-10 23:46:46 +0000687 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000688 if (addAsmGlobalSymbols(Context))
689 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000690
Rafael Espindola02003ca2010-10-20 04:57:22 +0000691 // add aliases
692 for (Module::alias_iterator i = _module->alias_begin(),
693 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000694 if (isAliasToDeclaration(*i))
Rafael Espindola02003ca2010-10-20 04:57:22 +0000695 addPotentialUndefinedSymbol(i, mangler);
696 else
697 addDefinedDataSymbol(i, mangler);
698 }
699
Daniel Dunbare41d9002010-08-10 23:46:46 +0000700 // make symbols for all undefines
701 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
702 it != _undefines.end(); ++it) {
703 // if this symbol also has a definition, then don't make an undefine
704 // because it is a tentative definition
705 if (_defines.count(it->getKey()) == 0) {
706 NameAndAttributes info = it->getValue();
707 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000708 }
709 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000710 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000711}
712
713
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000714uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000715 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000716}
717
718
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000719lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000720 if (index < _symbols.size())
721 return _symbols[index].attributes;
722 else
723 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000724}
725
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000726const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000727 if (index < _symbols.size())
728 return _symbols[index].name;
729 else
730 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000731}