blob: 8ea680d53c53c7e5c4e9f9aa5350c4292759f95a [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"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000030#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Support/TargetSelect.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000032#include "llvm/Support/system_error.h"
Chris Lattneraf76e592009-08-22 20:48:53 +000033#include "llvm/MC/MCAsmInfo.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"
Nick Kledzik77595fc2008-02-26 20:26:43 +000044
Nick Kledzik77595fc2008-02-26 20:26:43 +000045using namespace llvm;
46
Daniel Dunbarb06913d2010-08-10 23:46:39 +000047bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
48 return llvm::sys::IdentifyFileType((char*)mem, length)
49 == llvm::sys::Bitcode_FileType;
Nick Kledzik77595fc2008-02-26 20:26:43 +000050}
51
Daniel Dunbarb06913d2010-08-10 23:46:39 +000052bool LTOModule::isBitcodeFile(const char *path) {
53 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik77595fc2008-02-26 20:26:43 +000054}
55
Daniel Dunbarb06913d2010-08-10 23:46:39 +000056bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
57 const char *triplePrefix) {
58 MemoryBuffer *buffer = makeBuffer(mem, length);
59 if (!buffer)
Nick Kledzik3eb445f2009-06-01 20:33:09 +000060 return false;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000061 return isTargetMatch(buffer, triplePrefix);
Nick Kledzik3eb445f2009-06-01 20:33:09 +000062}
63
Daniel Dunbarb06913d2010-08-10 23:46:39 +000064bool LTOModule::isBitcodeFileForTarget(const char *path,
65 const char *triplePrefix) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000066 OwningPtr<MemoryBuffer> buffer;
67 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbarb06913d2010-08-10 23:46:39 +000068 return false;
Michael J. Spencer3ff95632010-12-16 03:29:14 +000069 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000070}
71
72// Takes ownership of buffer.
73bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling34711742010-10-06 01:22:42 +000074 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
75 delete buffer;
Bill Wendling931d4c22011-11-04 18:48:00 +000076 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbarb06913d2010-08-10 23:46:39 +000077}
78
79
80LTOModule::LTOModule(Module *m, TargetMachine *t)
Bill Wendlingb9bff962011-11-04 09:24:40 +000081 : _module(m), _target(t),
Bill Wendlinga7280fd2011-11-04 09:30:19 +000082 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
83 _mangler(_context, *_target->getTargetData())
Nick Kledzik3eb445f2009-06-01 20:33:09 +000084{
Daniel Dunbarb06913d2010-08-10 23:46:39 +000085}
86
87LTOModule *LTOModule::makeLTOModule(const char *path,
88 std::string &errMsg) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000089 OwningPtr<MemoryBuffer> buffer;
90 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000091 errMsg = ec.message();
Daniel Dunbarb06913d2010-08-10 23:46:39 +000092 return NULL;
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000093 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +000094 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +000095}
96
Rafael Espindolab4cc0312011-02-08 22:40:47 +000097LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Bill Wendling931d4c22011-11-04 18:48:00 +000098 size_t size, std::string &errMsg) {
Rafael Espindolaf21b1052011-03-17 00:36:11 +000099 return makeLTOModule(fd, path, size, size, 0, errMsg);
100}
101
102LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
103 size_t file_size,
104 size_t map_size,
105 off_t offset,
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000106 std::string &errMsg) {
107 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolaf21b1052011-03-17 00:36:11 +0000108 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
109 map_size, offset, false)) {
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000110 errMsg = ec.message();
111 return NULL;
112 }
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000113 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindolab4cc0312011-02-08 22:40:47 +0000114}
115
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000116/// makeBuffer - Create a MemoryBuffer from a memory range.
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000117MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
118 const char *startPtr = (char*)mem;
Rafael Espindola9916d2a2011-03-17 22:18:42 +0000119 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000120}
121
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000122LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
123 std::string &errMsg) {
124 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
125 if (!buffer)
126 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000127 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000128}
129
130LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
131 std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000132 static bool Initialized = false;
133 if (!Initialized) {
134 InitializeAllTargets();
Evan Chenge78085a2011-07-22 21:58:54 +0000135 InitializeAllTargetMCs();
Rafael Espindola38c4e532011-03-02 04:14:42 +0000136 InitializeAllAsmParsers();
137 Initialized = true;
138 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000139
140 // parse bitcode buffer
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000141 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
142 &errMsg));
143 if (!m) {
144 delete buffer;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000145 return NULL;
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000146 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000147
148 std::string Triple = m->getTargetTriple();
149 if (Triple.empty())
Sebastian Pop01738642011-11-01 21:32:20 +0000150 Triple = sys::getDefaultTargetTriple();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000151
152 // find machine architecture for this module
153 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
154 if (!march)
155 return NULL;
156
Nick Lewycky333ed452011-04-21 01:54:08 +0000157 // construct LTOModule, hand over ownership of module and target
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000158 SubtargetFeatures Features;
Evan Cheng276365d2011-06-30 01:53:36 +0000159 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000160 std::string FeatureStr = Features.getString();
Evan Cheng276365d2011-06-30 01:53:36 +0000161 std::string CPU;
162 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000163 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling931d4c22011-11-04 18:48:00 +0000164 if (Ret->ParseSymbols(errMsg)) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000165 delete Ret;
166 return NULL;
167 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000168
Rafael Espindola38c4e532011-03-02 04:14:42 +0000169 return Ret;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000170}
171
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000172const char *LTOModule::getTargetTriple() {
173 return _module->getTargetTriple().c_str();
174}
175
176void LTOModule::setTargetTriple(const char *triple) {
177 _module->setTargetTriple(triple);
178}
179
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000180void LTOModule::addDefinedFunctionSymbol(Function *f) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000181 // add to list of defined symbols
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000182 addDefinedSymbol(f, true);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000183}
184
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000185// Get string that data pointer points to.
186bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
187 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
188 Constant *op = ce->getOperand(0);
189 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
190 Constant *cn = gvn->getInitializer();
191 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
192 if (ca->isCString()) {
Jay Foad4f910542011-06-28 08:24:19 +0000193 name = ".objc_class_name_" + ca->getAsCString();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000194 return true;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000195 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000196 }
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000197 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000198 }
199 return false;
200}
201
202// Parse i386/ppc ObjC class data structure.
203void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling931d4c22011-11-04 18:48:00 +0000204 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
205 if (!c) return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000206
Bill Wendling931d4c22011-11-04 18:48:00 +0000207 // second slot in __OBJC,__class is pointer to superclass name
208 std::string superclassName;
209 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
210 NameAndAttributes info;
211 StringMap<NameAndAttributes>::value_type &entry =
212 _undefines.GetOrCreateValue(superclassName);
213 if (!entry.getValue().name) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000214 const char *symbolName = entry.getKey().data();
215 info.name = symbolName;
216 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
217 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000218 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000219 }
Bill Wendling931d4c22011-11-04 18:48:00 +0000220
221 // third slot in __OBJC,__class is pointer to class name
222 std::string className;
223 if (objcClassNameFromExpression(c->getOperand(2), className)) {
224 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
225 entry.setValue(1);
226 NameAndAttributes info;
227 info.name = entry.getKey().data();
228 info.attributes = lto_symbol_attributes(LTO_SYMBOL_PERMISSIONS_DATA |
229 LTO_SYMBOL_DEFINITION_REGULAR |
230 LTO_SYMBOL_SCOPE_DEFAULT);
231 _symbols.push_back(info);
232 }
233}
234
235
236// Parse i386/ppc ObjC category data structure.
237void LTOModule::addObjCCategory(GlobalVariable *clgv) {
238 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
239 if (!c) return;
240
241 // second slot in __OBJC,__category is pointer to target class name
242 std::string targetclassName;
243 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
244 return;
245
246 NameAndAttributes info;
247 StringMap<NameAndAttributes>::value_type &entry =
248 _undefines.GetOrCreateValue(targetclassName);
249
250 if (entry.getValue().name)
251 return;
252
253 const char *symbolName = entry.getKey().data();
254 info.name = symbolName;
255 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
256 entry.setValue(info);
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000257}
258
259
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000260// Parse i386/ppc ObjC class list data structure.
261void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
262 std::string targetclassName;
Bill Wendling931d4c22011-11-04 18:48:00 +0000263 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
264 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000265
Bill Wendling931d4c22011-11-04 18:48:00 +0000266 NameAndAttributes info;
267 StringMap<NameAndAttributes>::value_type &entry =
268 _undefines.GetOrCreateValue(targetclassName);
269 if (entry.getValue().name)
270 return;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000271
Bill Wendling931d4c22011-11-04 18:48:00 +0000272 const char *symbolName = entry.getKey().data();
273 info.name = symbolName;
274 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
275 entry.setValue(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000276}
277
278
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000279void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000280 // Add to list of defined symbols.
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000281 addDefinedSymbol(v, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000282
283 // Special case i386/ppc ObjC data structures in magic sections:
284 // The issue is that the old ObjC object format did some strange
285 // contortions to avoid real linker symbols. For instance, the
286 // ObjC class data structure is allocated statically in the executable
287 // that defines that class. That data structures contains a pointer to
288 // its superclass. But instead of just initializing that part of the
289 // struct to the address of its superclass, and letting the static and
290 // dynamic linkers do the rest, the runtime works by having that field
291 // instead point to a C-string that is the name of the superclass.
292 // At runtime the objc initialization updates that pointer and sets
293 // it to point to the actual super class. As far as the linker
294 // knows it is just a pointer to a string. But then someone wanted the
295 // linker to issue errors at build time if the superclass was not found.
296 // So they figured out a way in mach-o object format to use an absolute
297 // symbols (.objc_class_name_Foo = 0) and a floating reference
298 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
299 // a class was missing.
300 // The following synthesizes the implicit .objc_* symbols for the linker
301 // from the ObjC data structures generated by the front end.
302 if (v->hasSection() /* && isTargetDarwin */) {
303 // special case if this data blob is an ObjC class definition
304 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
305 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
306 addObjCClass(gv);
307 }
308 }
309
310 // special case if this data blob is an ObjC category definition
311 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
312 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
313 addObjCCategory(gv);
314 }
315 }
316
317 // special case if this data blob is the list of referenced classes
318 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
319 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320 addObjCClassRef(gv);
321 }
322 }
323 }
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000324}
325
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000326void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000327 // ignore all llvm.* symbols
328 if (def->getName().startswith("llvm."))
329 return;
330
331 // string is owned by _defines
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000332 SmallString<64> Buffer;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000333 _mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000334
335 // set alignment part log2() can have rounding errors
336 uint32_t align = def->getAlignment();
337 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
338
339 // set permissions part
340 if (isFunction)
341 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
342 else {
343 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
344 if (gv && gv->isConstant())
345 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
346 else
347 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
348 }
349
350 // set definition part
Bill Wendling563ef5e2010-09-27 18:05:19 +0000351 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
352 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendling7afea0c2010-09-27 20:17:45 +0000353 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000354 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000355 else if (def->hasCommonLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000356 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000357 else
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000358 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000359
360 // set scope part
361 if (def->hasHiddenVisibility())
362 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
363 else if (def->hasProtectedVisibility())
364 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000365 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
366 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
367 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000368 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendling7afea0c2010-09-27 20:17:45 +0000369 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
370 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000371 else
372 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
373
374 // add to table of symbols
375 NameAndAttributes info;
Chad Rosierbd35f272011-06-28 18:26:12 +0000376 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000377 entry.setValue(1);
378
379 StringRef Name = entry.getKey();
380 info.name = Name.data();
381 assert(info.name[Name.size()] == '\0');
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000382 info.attributes = (lto_symbol_attributes)attr;
383 _symbols.push_back(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000384}
385
Rafael Espindola38c4e532011-03-02 04:14:42 +0000386void LTOModule::addAsmGlobalSymbol(const char *name,
387 lto_symbol_attributes scope) {
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000388 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
389
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000390 // only add new define if not already defined
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000391 if (entry.getValue())
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000392 return;
393
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000394 entry.setValue(1);
395 const char *symbolName = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000396 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000397 attr |= scope;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000398 NameAndAttributes info;
399 info.name = symbolName;
400 info.attributes = (lto_symbol_attributes)attr;
401 _symbols.push_back(info);
Devang Patelc2aec572008-07-16 18:06:52 +0000402}
Nick Kledzik77595fc2008-02-26 20:26:43 +0000403
Rafael Espindola38c4e532011-03-02 04:14:42 +0000404void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
405 StringMap<NameAndAttributes>::value_type &entry =
406 _undefines.GetOrCreateValue(name);
407
408 _asm_undefines.push_back(entry.getKey().data());
409
410 // we already have the symbol
411 if (entry.getValue().name)
412 return;
413
414 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
415 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
416 NameAndAttributes info;
417 info.name = entry.getKey().data();
418 info.attributes = (lto_symbol_attributes)attr;
419
420 entry.setValue(info);
421}
422
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000423void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000424 // ignore all llvm.* symbols
425 if (decl->getName().startswith("llvm."))
426 return;
Nick Kledzik3eb445f2009-06-01 20:33:09 +0000427
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000428 // ignore all aliases
429 if (isa<GlobalAlias>(decl))
430 return;
Nick Lewycky485ded02009-07-09 06:03:04 +0000431
Rafael Espindolaef1860a2011-02-11 05:23:09 +0000432 SmallString<64> name;
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000433 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola7431af02009-04-24 16:55:21 +0000434
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000435 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosierbd35f272011-06-28 18:26:12 +0000436 _undefines.GetOrCreateValue(name);
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000437
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000438 // we already have the symbol
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000439 if (entry.getValue().name)
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000440 return;
Rafael Espindola7431af02009-04-24 16:55:21 +0000441
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000442 NameAndAttributes info;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000443
444 info.name = entry.getKey().data();
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000445 if (decl->hasExternalWeakLinkage())
446 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
447 else
448 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindolacd6c93e2011-02-20 16:27:25 +0000449
450 entry.setValue(info);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000451}
452
Rafael Espindola38c4e532011-03-02 04:14:42 +0000453namespace {
454 class RecordStreamer : public MCStreamer {
455 public:
456 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000457
Rafael Espindola38c4e532011-03-02 04:14:42 +0000458 private:
459 StringMap<State> Symbols;
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000460
Rafael Espindola38c4e532011-03-02 04:14:42 +0000461 void markDefined(const MCSymbol &Symbol) {
462 State &S = Symbols[Symbol.getName()];
463 switch (S) {
464 case DefinedGlobal:
465 case Global:
466 S = DefinedGlobal;
467 break;
468 case NeverSeen:
469 case Defined:
470 case Used:
471 S = Defined;
472 break;
473 }
474 }
475 void markGlobal(const MCSymbol &Symbol) {
476 State &S = Symbols[Symbol.getName()];
477 switch (S) {
478 case DefinedGlobal:
479 case Defined:
480 S = DefinedGlobal;
481 break;
482
483 case NeverSeen:
484 case Global:
485 case Used:
486 S = Global;
487 break;
488 }
489 }
490 void markUsed(const MCSymbol &Symbol) {
491 State &S = Symbols[Symbol.getName()];
492 switch (S) {
493 case DefinedGlobal:
494 case Defined:
495 case Global:
496 break;
497
498 case NeverSeen:
499 case Used:
500 S = Used;
501 break;
502 }
503 }
504
505 // FIXME: mostly copied for the obj streamer.
506 void AddValueSymbols(const MCExpr *Value) {
507 switch (Value->getKind()) {
508 case MCExpr::Target:
509 // FIXME: What should we do in here?
510 break;
511
512 case MCExpr::Constant:
513 break;
514
515 case MCExpr::Binary: {
516 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
517 AddValueSymbols(BE->getLHS());
518 AddValueSymbols(BE->getRHS());
519 break;
520 }
521
522 case MCExpr::SymbolRef:
523 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
524 break;
525
526 case MCExpr::Unary:
527 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
528 break;
529 }
530 }
531
532 public:
533 typedef StringMap<State>::const_iterator const_iterator;
534
535 const_iterator begin() {
536 return Symbols.begin();
537 }
538
539 const_iterator end() {
540 return Symbols.end();
541 }
542
543 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
544
545 virtual void ChangeSection(const MCSection *Section) {}
546 virtual void InitSections() {}
547 virtual void EmitLabel(MCSymbol *Symbol) {
548 Symbol->setSection(*getCurrentSection());
549 markDefined(*Symbol);
550 }
551 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
552 virtual void EmitThumbFunc(MCSymbol *Func) {}
553 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
554 // FIXME: should we handle aliases?
555 markDefined(*Symbol);
556 }
557 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
558 if (Attribute == MCSA_Global)
559 markGlobal(*Symbol);
560 }
561 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
562 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
563 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
564 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
565 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
566 unsigned Size , unsigned ByteAlignment) {
567 markDefined(*Symbol);
568 }
569 virtual void EmitCOFFSymbolType(int Type) {}
570 virtual void EndCOFFSymbolDef() {}
571 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
572 unsigned ByteAlignment) {
573 markDefined(*Symbol);
574 }
575 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
Benjamin Kramer36a16012011-09-01 23:04:27 +0000576 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
577 unsigned ByteAlignment) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000578 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
579 uint64_t Size, unsigned ByteAlignment) {}
580 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
581 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindoladebd7e42011-05-01 03:50:49 +0000582 unsigned AddrSpace) {}
Rafael Espindolae8cfbd82011-04-21 23:39:26 +0000583 virtual void EmitULEB128Value(const MCExpr *Value) {}
584 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000585 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
586 unsigned ValueSize,
587 unsigned MaxBytesToEmit) {}
588 virtual void EmitCodeAlignment(unsigned ByteAlignment,
589 unsigned MaxBytesToEmit) {}
590 virtual void EmitValueToOffset(const MCExpr *Offset,
591 unsigned char Value ) {}
592 virtual void EmitFileDirective(StringRef Filename) {}
593 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
594 const MCSymbol *LastLabel,
Evan Cheng672b93a2011-07-14 05:43:07 +0000595 const MCSymbol *Label,
596 unsigned PointerSize) {}
Rafael Espindola38c4e532011-03-02 04:14:42 +0000597
598 virtual void EmitInstruction(const MCInst &Inst) {
599 // Scan for values.
600 for (unsigned i = Inst.getNumOperands(); i--; )
601 if (Inst.getOperand(i).isExpr())
602 AddValueSymbols(Inst.getOperand(i).getExpr());
603 }
604 virtual void Finish() {}
605 };
606}
607
Bill Wendlingb9bff962011-11-04 09:24:40 +0000608bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000609 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasin6d483c22011-09-08 07:38:25 +0000610 if (inlineAsm.empty())
611 return false;
Rafael Espindola38c4e532011-03-02 04:14:42 +0000612
Bill Wendlingb9bff962011-11-04 09:24:40 +0000613 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000614 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
615 SourceMgr SrcMgr;
616 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000617 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingb9bff962011-11-04 09:24:40 +0000618 _context, *Streamer,
Rafael Espindola38c4e532011-03-02 04:14:42 +0000619 *_target->getMCAsmInfo()));
Evan Chengffc0e732011-07-09 05:47:46 +0000620 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
621 createMCSubtargetInfo(_target->getTargetTriple(),
622 _target->getTargetCPU(),
623 _target->getTargetFeatureString()));
Evan Cheng94b95502011-07-26 00:24:13 +0000624 OwningPtr<MCTargetAsmParser>
625 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin603e1032011-09-08 07:36:39 +0000626 if (!TAP) {
627 errMsg = "target " + std::string(_target->getTarget().getName()) +
628 " does not define AsmParser.";
629 return true;
630 }
631
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
Ivan Krasin603e1032011-09-08 07:36:39 +0000664bool LTOModule::ParseSymbols(std::string &errMsg) {
Daniel Dunbare41d9002010-08-10 23:46:46 +0000665 // add functions
666 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000667 if (isDeclaration(*f))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000668 addPotentialUndefinedSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000669 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000670 addDefinedFunctionSymbol(f);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000671 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000672
Daniel Dunbare41d9002010-08-10 23:46:46 +0000673 // add data
674 for (Module::global_iterator v = _module->global_begin(),
675 e = _module->global_end(); v != e; ++v) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000676 if (isDeclaration(*v))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000677 addPotentialUndefinedSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000678 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000679 addDefinedDataSymbol(v);
Daniel Dunbare41d9002010-08-10 23:46:46 +0000680 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000681
Daniel Dunbare41d9002010-08-10 23:46:46 +0000682 // add asm globals
Bill Wendlingb9bff962011-11-04 09:24:40 +0000683 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000684 return true;
Daniel Dunbare41d9002010-08-10 23:46:46 +0000685
Rafael Espindola02003ca2010-10-20 04:57:22 +0000686 // add aliases
687 for (Module::alias_iterator i = _module->alias_begin(),
688 e = _module->alias_end(); i != e; ++i) {
Rafael Espindolaf19d7a72011-03-18 19:51:00 +0000689 if (isAliasToDeclaration(*i))
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000690 addPotentialUndefinedSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000691 else
Bill Wendlinga7280fd2011-11-04 09:30:19 +0000692 addDefinedDataSymbol(i);
Rafael Espindola02003ca2010-10-20 04:57:22 +0000693 }
694
Daniel Dunbare41d9002010-08-10 23:46:46 +0000695 // make symbols for all undefines
696 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
697 it != _undefines.end(); ++it) {
698 // if this symbol also has a definition, then don't make an undefine
699 // because it is a tentative definition
700 if (_defines.count(it->getKey()) == 0) {
701 NameAndAttributes info = it->getValue();
702 _symbols.push_back(info);
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000703 }
704 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000705 return false;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000706}
707
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000708uint32_t LTOModule::getSymbolCount() {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000709 return _symbols.size();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000710}
711
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000712lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000713 if (index < _symbols.size())
714 return _symbols[index].attributes;
715 else
716 return lto_symbol_attributes(0);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000717}
718
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000719const char *LTOModule::getSymbolName(uint32_t index) {
Daniel Dunbarb06913d2010-08-10 23:46:39 +0000720 if (index < _symbols.size())
721 return _symbols[index].name;
722 else
723 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000724}