blob: 981c9f7a51f894873524cc87f3752022dbcb5d47 [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 Cheng43966132011-07-19 06:37:02 +0000139 InitializeAllMCCodeGenInfos();
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000140 InitializeAllMCAsmInfos();
Cameron Zwarichbf843e62011-07-11 22:19:51 +0000141 InitializeAllMCSubtargetInfos();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000142 InitializeAllAsmParsers();
143 Initialized = true;
144 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000145
146 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000147 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
148 &errMsg));
149 if (!m) {
150 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000151 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000152 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000153
154 std::string Triple = m->getTargetTriple();
155 if (Triple.empty())
156 Triple = sys::getHostTriple();
157
158 // find machine architecture for this module
159 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
160 if (!march)
161 return NULL;
162
Nick Lewycky333ed452011-04-21 01:54:08 +0000163 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000164 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000165 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000166 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000167 std::string CPU;
168 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000169 LTOModule *Ret = new LTOModule(m.take(), target);
170 bool Err = Ret->ParseSymbols();
171 if (Err) {
172 delete Ret;
173 return NULL;
174 }
175 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000176}
177
178
179const char *LTOModule::getTargetTriple() {
180 return _module->getTargetTriple().c_str();
181}
182
183void LTOModule::setTargetTriple(const char *triple) {
184 _module->setTargetTriple(triple);
185}
186
187void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
188 // add to list of defined symbols
189 addDefinedSymbol(f, mangler, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000190}
191
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000192// Get string that data pointer points to.
193bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
194 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
195 Constant *op = ce->getOperand(0);
196 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
197 Constant *cn = gvn->getInitializer();
198 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
199 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000200 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000201 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000202 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000203 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000204 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000205 }
206 return false;
207}
208
209// Parse i386/ppc ObjC class data structure.
210void LTOModule::addObjCClass(GlobalVariable *clgv) {
211 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
212 // second slot in __OBJC,__class is pointer to superclass name
213 std::string superclassName;
214 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
215 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000216 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000217 _undefines.GetOrCreateValue(superclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000218 if (!entry.getValue().name) {
219 const char *symbolName = entry.getKey().data();
Daniel Dunbar8d0843d2010-08-11 00:11:17 +0000220 info.name = symbolName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000221 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000222 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000223 }
224 }
225 // third slot in __OBJC,__class is pointer to class name
226 std::string className;
227 if (objcClassNameFromExpression(c->getOperand(2), className)) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000228 StringSet::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000229 _defines.GetOrCreateValue(className);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000230 entry.setValue(1);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000231 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000232 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000233 info.attributes = (lto_symbol_attributes)
234 (LTO_SYMBOL_PERMISSIONS_DATA |
235 LTO_SYMBOL_DEFINITION_REGULAR |
236 LTO_SYMBOL_SCOPE_DEFAULT);
237 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000238 }
239 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000240}
241
242
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000243// Parse i386/ppc ObjC category data structure.
244void LTOModule::addObjCCategory(GlobalVariable *clgv) {
245 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
246 // second slot in __OBJC,__category is pointer to target class name
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000247 std::string targetclassName;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000248 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
249 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000250
251 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000252 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000253
254 if (entry.getValue().name)
255 return;
256
257 const char *symbolName = entry.getKey().data();
258 info.name = symbolName;
259 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
260 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000261 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000262 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000263}
264
265
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000266// Parse i386/ppc ObjC class list data structure.
267void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
268 std::string targetclassName;
269 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
Nick Kledzik77595fc2008-02-26 20:26:43 +0000270 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000271
272 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000273 _undefines.GetOrCreateValue(targetclassName);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000274 if (entry.getValue().name)
275 return;
276
277 const char *symbolName = entry.getKey().data();
278 info.name = symbolName;
279 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
280 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000281 }
282}
283
284
285void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
286 // Add to list of defined symbols.
287 addDefinedSymbol(v, mangler, false);
288
289 // Special case i386/ppc ObjC data structures in magic sections:
290 // The issue is that the old ObjC object format did some strange
291 // contortions to avoid real linker symbols. For instance, the
292 // ObjC class data structure is allocated statically in the executable
293 // that defines that class. That data structures contains a pointer to
294 // its superclass. But instead of just initializing that part of the
295 // struct to the address of its superclass, and letting the static and
296 // dynamic linkers do the rest, the runtime works by having that field
297 // instead point to a C-string that is the name of the superclass.
298 // At runtime the objc initialization updates that pointer and sets
299 // it to point to the actual super class. As far as the linker
300 // knows it is just a pointer to a string. But then someone wanted the
301 // linker to issue errors at build time if the superclass was not found.
302 // So they figured out a way in mach-o object format to use an absolute
303 // symbols (.objc_class_name_Foo = 0) and a floating reference
304 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
305 // a class was missing.
306 // The following synthesizes the implicit .objc_* symbols for the linker
307 // from the ObjC data structures generated by the front end.
308 if (v->hasSection() /* && isTargetDarwin */) {
309 // special case if this data blob is an ObjC class definition
310 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
311 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
312 addObjCClass(gv);
313 }
314 }
315
316 // special case if this data blob is an ObjC category definition
317 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
318 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
319 addObjCCategory(gv);
320 }
321 }
322
323 // special case if this data blob is the list of referenced classes
324 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
325 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
326 addObjCClassRef(gv);
327 }
328 }
329 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000330}
331
332
333void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
334 bool isFunction) {
335 // ignore all llvm.* symbols
336 if (def->getName().startswith("llvm."))
337 return;
338
339 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000340 SmallString<64> Buffer;
341 mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000342
343 // set alignment part log2() can have rounding errors
344 uint32_t align = def->getAlignment();
345 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
346
347 // set permissions part
348 if (isFunction)
349 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
350 else {
351 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
352 if (gv && gv->isConstant())
353 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
354 else
355 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
356 }
357
358 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000359 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
360 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000361 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000362 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000363 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000364 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000365 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000366 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000367
368 // set scope part
369 if (def->hasHiddenVisibility())
370 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
371 else if (def->hasProtectedVisibility())
372 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000373 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
374 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
375 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000376 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000377 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
378 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000379 else
380 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
381
382 // add to table of symbols
383 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000384 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000385 entry.setValue(1);
386
387 StringRef Name = entry.getKey();
388 info.name = Name.data();
389 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000390 info.attributes = (lto_symbol_attributes)attr;
391 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000392}
393
Rafael Espindola38c4e532011-03-02 04:14:42 +0000394void LTOModule::addAsmGlobalSymbol(const char *name,
395 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000396 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
397
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000398 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000399 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000400 return;
401
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000402 entry.setValue(1);
403 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000404 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000405 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000406 NameAndAttributes info;
407 info.name = symbolName;
408 info.attributes = (lto_symbol_attributes)attr;
409 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000410}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000411
Rafael Espindola38c4e532011-03-02 04:14:42 +0000412void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
413 StringMap<NameAndAttributes>::value_type &entry =
414 _undefines.GetOrCreateValue(name);
415
416 _asm_undefines.push_back(entry.getKey().data());
417
418 // we already have the symbol
419 if (entry.getValue().name)
420 return;
421
422 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
423 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
424 NameAndAttributes info;
425 info.name = entry.getKey().data();
426 info.attributes = (lto_symbol_attributes)attr;
427
428 entry.setValue(info);
429}
430
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000431void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
432 Mangler &mangler) {
433 // ignore all llvm.* symbols
434 if (decl->getName().startswith("llvm."))
435 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000436
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000437 // ignore all aliases
438 if (isa<GlobalAlias>(decl))
439 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000440
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000441 SmallString<64> name;
442 mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000443
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000444 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000445 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000446
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000447 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000448 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000449 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000450
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000451 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000452
453 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000454 if (decl->hasExternalWeakLinkage())
455 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
456 else
457 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000458
459 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000460}
461
462
Rafael Espindola38c4e532011-03-02 04:14:42 +0000463namespace {
464 class RecordStreamer : public MCStreamer {
465 public:
466 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000467
Rafael Espindola38c4e532011-03-02 04:14:42 +0000468 private:
469 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000470
Rafael Espindola38c4e532011-03-02 04:14:42 +0000471 void markDefined(const MCSymbol &Symbol) {
472 State &S = Symbols[Symbol.getName()];
473 switch (S) {
474 case DefinedGlobal:
475 case Global:
476 S = DefinedGlobal;
477 break;
478 case NeverSeen:
479 case Defined:
480 case Used:
481 S = Defined;
482 break;
483 }
484 }
485 void markGlobal(const MCSymbol &Symbol) {
486 State &S = Symbols[Symbol.getName()];
487 switch (S) {
488 case DefinedGlobal:
489 case Defined:
490 S = DefinedGlobal;
491 break;
492
493 case NeverSeen:
494 case Global:
495 case Used:
496 S = Global;
497 break;
498 }
499 }
500 void markUsed(const MCSymbol &Symbol) {
501 State &S = Symbols[Symbol.getName()];
502 switch (S) {
503 case DefinedGlobal:
504 case Defined:
505 case Global:
506 break;
507
508 case NeverSeen:
509 case Used:
510 S = Used;
511 break;
512 }
513 }
514
515 // FIXME: mostly copied for the obj streamer.
516 void AddValueSymbols(const MCExpr *Value) {
517 switch (Value->getKind()) {
518 case MCExpr::Target:
519 // FIXME: What should we do in here?
520 break;
521
522 case MCExpr::Constant:
523 break;
524
525 case MCExpr::Binary: {
526 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
527 AddValueSymbols(BE->getLHS());
528 AddValueSymbols(BE->getRHS());
529 break;
530 }
531
532 case MCExpr::SymbolRef:
533 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
534 break;
535
536 case MCExpr::Unary:
537 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
538 break;
539 }
540 }
541
542 public:
543 typedef StringMap<State>::const_iterator const_iterator;
544
545 const_iterator begin() {
546 return Symbols.begin();
547 }
548
549 const_iterator end() {
550 return Symbols.end();
551 }
552
553 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
554
555 virtual void ChangeSection(const MCSection *Section) {}
556 virtual void InitSections() {}
557 virtual void EmitLabel(MCSymbol *Symbol) {
558 Symbol->setSection(*getCurrentSection());
559 markDefined(*Symbol);
560 }
561 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
562 virtual void EmitThumbFunc(MCSymbol *Func) {}
563 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
564 // FIXME: should we handle aliases?
565 markDefined(*Symbol);
566 }
567 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
568 if (Attribute == MCSA_Global)
569 markGlobal(*Symbol);
570 }
571 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
572 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
573 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
574 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
575 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
576 unsigned Size , unsigned ByteAlignment) {
577 markDefined(*Symbol);
578 }
579 virtual void EmitCOFFSymbolType(int Type) {}
580 virtual void EndCOFFSymbolDef() {}
581 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
582 unsigned ByteAlignment) {
583 markDefined(*Symbol);
584 }
585 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
586 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
587 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
588 uint64_t Size, unsigned ByteAlignment) {}
589 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
590 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000591 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000592 virtual void EmitULEB128Value(const MCExpr *Value) {}
593 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000594 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
595 unsigned ValueSize,
596 unsigned MaxBytesToEmit) {}
597 virtual void EmitCodeAlignment(unsigned ByteAlignment,
598 unsigned MaxBytesToEmit) {}
599 virtual void EmitValueToOffset(const MCExpr *Offset,
600 unsigned char Value ) {}
601 virtual void EmitFileDirective(StringRef Filename) {}
602 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
603 const MCSymbol *LastLabel,
Evan Cheng672b93a2011-07-14 05:43:07 +0000604 const MCSymbol *Label,
605 unsigned PointerSize) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000606
607 virtual void EmitInstruction(const MCInst &Inst) {
608 // Scan for values.
609 for (unsigned i = Inst.getNumOperands(); i--; )
610 if (Inst.getOperand(i).isExpr())
611 AddValueSymbols(Inst.getOperand(i).getExpr());
612 }
613 virtual void Finish() {}
614 };
615}
616
617bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
618 const std::string &inlineAsm = _module->getModuleInlineAsm();
619
620 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
621 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
622 SourceMgr SrcMgr;
623 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
624 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
625 Context, *Streamer,
626 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000627 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
628 createMCSubtargetInfo(_target->getTargetTriple(),
629 _target->getTargetCPU(),
630 _target->getTargetFeatureString()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000631 OwningPtr<TargetAsmParser>
Evan Chengffc0e732011-07-09 05:47:46 +0000632 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000633 Parser->setTargetParser(*TAP);
634 int Res = Parser->Run(false);
635 if (Res)
636 return true;
637
638 for (RecordStreamer::const_iterator i = Streamer->begin(),
639 e = Streamer->end(); i != e; ++i) {
640 StringRef Key = i->first();
641 RecordStreamer::State Value = i->second;
642 if (Value == RecordStreamer::DefinedGlobal)
643 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
644 else if (Value == RecordStreamer::Defined)
645 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
646 else if (Value == RecordStreamer::Global ||
647 Value == RecordStreamer::Used)
648 addAsmGlobalSymbolUndef(Key.data());
649 }
650 return false;
651}
652
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000653static bool isDeclaration(const GlobalValue &V) {
654 if (V.hasAvailableExternallyLinkage())
655 return true;
656 if (V.isMaterializable())
657 return false;
658 return V.isDeclaration();
659}
660
661static bool isAliasToDeclaration(const GlobalAlias &V) {
662 return isDeclaration(*V.getAliasedGlobal());
663}
664
Rafael Espindola38c4e532011-03-02 04:14:42 +0000665bool LTOModule::ParseSymbols() {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000666 // Use mangler to add GlobalPrefix to names to match linker names.
Evan Cheng203576a2011-07-20 19:50:42 +0000667 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),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}