blob: a2634231a6d138ed5d363bcae57e3caf535ba289 [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"
Evan Cheng94b95502011-07-26 00:24:13 +000041#include "llvm/MC/MCTargetAsmParser.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 Chenge78085a2011-07-22 21:58:54 +0000139 InitializeAllTargetMCs();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000140 InitializeAllAsmParsers();
141 Initialized = true;
142 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000143
144 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000145 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
146 &errMsg));
147 if (!m) {
148 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000149 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000150 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000151
152 std::string Triple = m->getTargetTriple();
153 if (Triple.empty())
154 Triple = sys::getHostTriple();
155
156 // find machine architecture for this module
157 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
158 if (!march)
159 return NULL;
160
Nick Lewycky333ed452011-04-21 01:54:08 +0000161 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000162 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000163 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000164 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000165 std::string CPU;
166 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000167 LTOModule *Ret = new LTOModule(m.take(), target);
168 bool Err = Ret->ParseSymbols();
169 if (Err) {
170 delete Ret;
171 return NULL;
172 }
173 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000174}
175
176
177const char *LTOModule::getTargetTriple() {
178 return _module->getTargetTriple().c_str();
179}
180
181void LTOModule::setTargetTriple(const char *triple) {
182 _module->setTargetTriple(triple);
183}
184
185void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
186 // add to list of defined symbols
187 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000188}
189
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000190// Get string that data pointer points to.
191bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
192 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
193 Constant *op = ce->getOperand(0);
194 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
195 Constant *cn = gvn->getInitializer();
196 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
197 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000198 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000199 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000200 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000201 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000202 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000203 }
204 return false;
205}
206
207// Parse i386/ppc ObjC class data structure.
208void LTOModule::addObjCClass(GlobalVariable *clgv) {
209 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
210 // second slot in __OBJC,__class is pointer to superclass name
211 std::string superclassName;
212 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
213 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000214 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000215 _undefines.GetOrCreateValue(superclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000216 if (!entry.getValue().name) {
217 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000218 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000219 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000220 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000221 }
222 }
223 // third slot in __OBJC,__class is pointer to class name
224 std::string className;
225 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000226 StringSet::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000227 _defines.GetOrCreateValue(className);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000228 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000229 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000230 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000231 info.attributes = (lto_symbol_attributes)
232 (LTO_SYMBOL_PERMISSIONS_DATA |
233 LTO_SYMBOL_DEFINITION_REGULAR |
234 LTO_SYMBOL_SCOPE_DEFAULT);
235 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000236 }
237 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000238}
239
240
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000241// Parse i386/ppc ObjC category data structure.
242void LTOModule::addObjCCategory(GlobalVariable *clgv) {
243 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
244 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000245 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000246 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
247 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000248
249 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000250 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000251
252 if (entry.getValue().name)
253 return;
254
255 const char *symbolName = entry.getKey().data();
256 info.name = symbolName;
257 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000259 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000260 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000261}
262
263
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000264// Parse i386/ppc ObjC class list data structure.
265void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
266 std::string targetclassName;
267 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000268 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000269
270 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000271 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000272 if (entry.getValue().name)
273 return;
274
275 const char *symbolName = entry.getKey().data();
276 info.name = symbolName;
277 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
278 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000279 }
280}
281
282
283void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
284 // Add to list of defined symbols.
285 addDefinedSymbol(v, mangler, false);
286
287 // Special case i386/ppc ObjC data structures in magic sections:
288 // The issue is that the old ObjC object format did some strange
289 // contortions to avoid real linker symbols. For instance, the
290 // ObjC class data structure is allocated statically in the executable
291 // that defines that class. That data structures contains a pointer to
292 // its superclass. But instead of just initializing that part of the
293 // struct to the address of its superclass, and letting the static and
294 // dynamic linkers do the rest, the runtime works by having that field
295 // instead point to a C-string that is the name of the superclass.
296 // At runtime the objc initialization updates that pointer and sets
297 // it to point to the actual super class. As far as the linker
298 // knows it is just a pointer to a string. But then someone wanted the
299 // linker to issue errors at build time if the superclass was not found.
300 // So they figured out a way in mach-o object format to use an absolute
301 // symbols (.objc_class_name_Foo = 0) and a floating reference
302 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
303 // a class was missing.
304 // The following synthesizes the implicit .objc_* symbols for the linker
305 // from the ObjC data structures generated by the front end.
306 if (v->hasSection() /* && isTargetDarwin */) {
307 // special case if this data blob is an ObjC class definition
308 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
309 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
310 addObjCClass(gv);
311 }
312 }
313
314 // special case if this data blob is an ObjC category definition
315 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
316 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
317 addObjCCategory(gv);
318 }
319 }
320
321 // special case if this data blob is the list of referenced classes
322 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
323 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
324 addObjCClassRef(gv);
325 }
326 }
327 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000328}
329
330
331void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
332 bool isFunction) {
333 // ignore all llvm.* symbols
334 if (def->getName().startswith("llvm."))
335 return;
336
337 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000338 SmallString<64> Buffer;
339 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000340
341 // set alignment part log2() can have rounding errors
342 uint32_t align = def->getAlignment();
343 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
344
345 // set permissions part
346 if (isFunction)
347 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
348 else {
349 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
350 if (gv && gv->isConstant())
351 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
352 else
353 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
354 }
355
356 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000357 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
358 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000359 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000360 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000361 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000362 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000363 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000364 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000365
366 // set scope part
367 if (def->hasHiddenVisibility())
368 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
369 else if (def->hasProtectedVisibility())
370 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000371 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
372 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
373 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000374 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000375 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
376 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000377 else
378 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
379
380 // add to table of symbols
381 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000382 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000383 entry.setValue(1);
384
385 StringRef Name = entry.getKey();
386 info.name = Name.data();
387 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000388 info.attributes = (lto_symbol_attributes)attr;
389 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000390}
391
Rafael Espindola38c4e532011-03-02 04:14:42 +0000392void LTOModule::addAsmGlobalSymbol(const char *name,
393 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000394 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
395
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000396 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000397 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000398 return;
399
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000400 entry.setValue(1);
401 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000402 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000403 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000404 NameAndAttributes info;
405 info.name = symbolName;
406 info.attributes = (lto_symbol_attributes)attr;
407 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000408}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000409
Rafael Espindola38c4e532011-03-02 04:14:42 +0000410void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
411 StringMap<NameAndAttributes>::value_type &entry =
412 _undefines.GetOrCreateValue(name);
413
414 _asm_undefines.push_back(entry.getKey().data());
415
416 // we already have the symbol
417 if (entry.getValue().name)
418 return;
419
420 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
421 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
422 NameAndAttributes info;
423 info.name = entry.getKey().data();
424 info.attributes = (lto_symbol_attributes)attr;
425
426 entry.setValue(info);
427}
428
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000429void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
430 Mangler &mangler) {
431 // ignore all llvm.* symbols
432 if (decl->getName().startswith("llvm."))
433 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000434
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000435 // ignore all aliases
436 if (isa<GlobalAlias>(decl))
437 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000438
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000439 SmallString<64> name;
440 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000441
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000442 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000443 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000444
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000445 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000446 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000447 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000448
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000449 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000450
451 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000452 if (decl->hasExternalWeakLinkage())
453 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
454 else
455 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000456
457 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000458}
459
460
Rafael Espindola38c4e532011-03-02 04:14:42 +0000461namespace {
462 class RecordStreamer : public MCStreamer {
463 public:
464 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000465
Rafael Espindola38c4e532011-03-02 04:14:42 +0000466 private:
467 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000468
Rafael Espindola38c4e532011-03-02 04:14:42 +0000469 void markDefined(const MCSymbol &Symbol) {
470 State &S = Symbols[Symbol.getName()];
471 switch (S) {
472 case DefinedGlobal:
473 case Global:
474 S = DefinedGlobal;
475 break;
476 case NeverSeen:
477 case Defined:
478 case Used:
479 S = Defined;
480 break;
481 }
482 }
483 void markGlobal(const MCSymbol &Symbol) {
484 State &S = Symbols[Symbol.getName()];
485 switch (S) {
486 case DefinedGlobal:
487 case Defined:
488 S = DefinedGlobal;
489 break;
490
491 case NeverSeen:
492 case Global:
493 case Used:
494 S = Global;
495 break;
496 }
497 }
498 void markUsed(const MCSymbol &Symbol) {
499 State &S = Symbols[Symbol.getName()];
500 switch (S) {
501 case DefinedGlobal:
502 case Defined:
503 case Global:
504 break;
505
506 case NeverSeen:
507 case Used:
508 S = Used;
509 break;
510 }
511 }
512
513 // FIXME: mostly copied for the obj streamer.
514 void AddValueSymbols(const MCExpr *Value) {
515 switch (Value->getKind()) {
516 case MCExpr::Target:
517 // FIXME: What should we do in here?
518 break;
519
520 case MCExpr::Constant:
521 break;
522
523 case MCExpr::Binary: {
524 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
525 AddValueSymbols(BE->getLHS());
526 AddValueSymbols(BE->getRHS());
527 break;
528 }
529
530 case MCExpr::SymbolRef:
531 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
532 break;
533
534 case MCExpr::Unary:
535 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
536 break;
537 }
538 }
539
540 public:
541 typedef StringMap<State>::const_iterator const_iterator;
542
543 const_iterator begin() {
544 return Symbols.begin();
545 }
546
547 const_iterator end() {
548 return Symbols.end();
549 }
550
551 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
552
553 virtual void ChangeSection(const MCSection *Section) {}
554 virtual void InitSections() {}
555 virtual void EmitLabel(MCSymbol *Symbol) {
556 Symbol->setSection(*getCurrentSection());
557 markDefined(*Symbol);
558 }
559 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
560 virtual void EmitThumbFunc(MCSymbol *Func) {}
561 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
562 // FIXME: should we handle aliases?
563 markDefined(*Symbol);
564 }
565 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
566 if (Attribute == MCSA_Global)
567 markGlobal(*Symbol);
568 }
569 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
570 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
571 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
572 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
573 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
574 unsigned Size , unsigned ByteAlignment) {
575 markDefined(*Symbol);
576 }
577 virtual void EmitCOFFSymbolType(int Type) {}
578 virtual void EndCOFFSymbolDef() {}
579 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
580 unsigned ByteAlignment) {
581 markDefined(*Symbol);
582 }
583 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
584 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
585 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
586 uint64_t Size, unsigned ByteAlignment) {}
587 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
588 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000589 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000590 virtual void EmitULEB128Value(const MCExpr *Value) {}
591 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000592 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
593 unsigned ValueSize,
594 unsigned MaxBytesToEmit) {}
595 virtual void EmitCodeAlignment(unsigned ByteAlignment,
596 unsigned MaxBytesToEmit) {}
597 virtual void EmitValueToOffset(const MCExpr *Offset,
598 unsigned char Value ) {}
599 virtual void EmitFileDirective(StringRef Filename) {}
600 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
601 const MCSymbol *LastLabel,
Evan Cheng672b93a2011-07-14 05:43:07 +0000602 const MCSymbol *Label,
603 unsigned PointerSize) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000604
605 virtual void EmitInstruction(const MCInst &Inst) {
606 // Scan for values.
607 for (unsigned i = Inst.getNumOperands(); i--; )
608 if (Inst.getOperand(i).isExpr())
609 AddValueSymbols(Inst.getOperand(i).getExpr());
610 }
611 virtual void Finish() {}
612 };
613}
614
615bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
616 const std::string &inlineAsm = _module->getModuleInlineAsm();
617
618 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
619 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
620 SourceMgr SrcMgr;
621 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
622 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
623 Context, *Streamer,
624 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000625 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
626 createMCSubtargetInfo(_target->getTargetTriple(),
627 _target->getTargetCPU(),
628 _target->getTargetFeatureString()));
Evan Cheng94b95502011-07-26 00:24:13 +0000629 OwningPtr<MCTargetAsmParser>
630 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000631 Parser->setTargetParser(*TAP);
632 int Res = Parser->Run(false);
633 if (Res)
634 return true;
635
636 for (RecordStreamer::const_iterator i = Streamer->begin(),
637 e = Streamer->end(); i != e; ++i) {
638 StringRef Key = i->first();
639 RecordStreamer::State Value = i->second;
640 if (Value == RecordStreamer::DefinedGlobal)
641 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
642 else if (Value == RecordStreamer::Defined)
643 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
644 else if (Value == RecordStreamer::Global ||
645 Value == RecordStreamer::Used)
646 addAsmGlobalSymbolUndef(Key.data());
647 }
648 return false;
649}
650
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000651static bool isDeclaration(const GlobalValue &V) {
652 if (V.hasAvailableExternallyLinkage())
653 return true;
654 if (V.isMaterializable())
655 return false;
656 return V.isDeclaration();
657}
658
659static bool isAliasToDeclaration(const GlobalAlias &V) {
660 return isDeclaration(*V.getAliasedGlobal());
661}
662
Rafael Espindola38c4e532011-03-02 04:14:42 +0000663bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000664 // Use mangler to add GlobalPrefix to names to match linker names.
Evan Cheng203576a2011-07-20 19:50:42 +0000665 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000666 Mangler mangler(Context, *_target->getTargetData());
Gabor Greif4136e7b2009-09-23 02:46:12 +0000667
Daniel Dunbare41d9002010-08-10 23:46:46 +0000668 // add functions
669 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000670 if (isDeclaration(*f))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000671 addPotentialUndefinedSymbol(f, mangler);
672 else
673 addDefinedFunctionSymbol(f, mangler);
674 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000675
Daniel Dunbare41d9002010-08-10 23:46:46 +0000676 // add data
677 for (Module::global_iterator v = _module->global_begin(),
678 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000679 if (isDeclaration(*v))
Daniel Dunbare41d9002010-08-10 23:46:46 +0000680 addPotentialUndefinedSymbol(v, mangler);
681 else
682 addDefinedDataSymbol(v, mangler);
683 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000684
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685 // add asm globals
Rafael Espindola38c4e532011-03-02 04:14:42 +0000686 if (addAsmGlobalSymbols(Context))
687 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000688
Rafael Espindola02003ca2010-10-20 04:57:22 +0000689 // add aliases
690 for (Module::alias_iterator i = _module->alias_begin(),
691 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000692 if (isAliasToDeclaration(*i))
Rafael Espindola02003ca2010-10-20 04:57:22 +0000693 addPotentialUndefinedSymbol(i, mangler);
694 else
695 addDefinedDataSymbol(i, mangler);
696 }
697
Daniel Dunbare41d9002010-08-10 23:46:46 +0000698 // make symbols for all undefines
699 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
700 it != _undefines.end(); ++it) {
701 // if this symbol also has a definition, then don't make an undefine
702 // because it is a tentative definition
703 if (_defines.count(it->getKey()) == 0) {
704 NameAndAttributes info = it->getValue();
705 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000706 }
707 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000708 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000709}
710
711
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000712uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000713 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000714}
715
716
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000717lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000718 if (index < _symbols.size())
719 return _symbols[index].attributes;
720 else
721 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000722}
723
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000724const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000725 if (index < _symbols.size())
726 return _symbols[index].name;
727 else
728 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000729}