blob: 45890a58d5fce93149182d4bf2293c8ea5ba672e [file] [log] [blame]
Chris Lattner2eff5052010-03-12 18:44:54 +00001//===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
Nick Kledzik07b4a622008-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 Dunbar5657e7b2010-08-10 23:46:39 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzik91a6dcf2008-02-27 22:25:36 +000015#include "LTOModule.h"
Nick Kledzikb481c202009-06-01 20:33:09 +000016#include "llvm/Constants.h"
Owen Anderson6773d382009-07-01 16:58:40 +000017#include "llvm/LLVMContext.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000018#include "llvm/Module.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000019#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner7b26fce2009-08-22 20:48:53 +000020#include "llvm/MC/MCAsmInfo.h"
Rafael Espindola1e49a6d2011-03-02 04:14:42 +000021#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCInst.h"
Rafael Espindola1e49a6d2011-03-02 04:14:42 +000023#include "llvm/MC/MCStreamer.h"
Evan Cheng91111d22011-07-09 05:47:46 +000024#include "llvm/MC/MCSubtargetInfo.h"
Rafael Espindola1e49a6d2011-03-02 04:14:42 +000025#include "llvm/MC/MCSymbol.h"
Evan Cheng11424442011-07-26 00:24:13 +000026#include "llvm/MC/MCTargetAsmParser.h"
Bill Wendling8f6c8a92012-03-30 23:26:06 +000027#include "llvm/MC/SubtargetFeature.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
Daniel Dunbar45806382009-07-16 02:41:19 +000029#include "llvm/Target/TargetMachine.h"
Evan Chengd60fa58b2011-07-18 20:57:22 +000030#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendling8f6c8a92012-03-30 23:26:06 +000031#include "llvm/Support/Host.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/Process.h"
36#include "llvm/Support/SourceMgr.h"
37#include "llvm/Support/SystemUtils.h"
38#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Support/TargetSelect.h"
40#include "llvm/Support/system_error.h"
41#include "llvm/ADT/OwningPtr.h"
42#include "llvm/ADT/Triple.h"
43
Nick Kledzik07b4a622008-02-26 20:26:43 +000044using namespace llvm;
45
Bill Wendlingfb440502012-03-28 20:46:54 +000046LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
47 : _module(m), _target(t),
48 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
49 _mangler(_context, *_target->getTargetData()) {}
50
51/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
52/// bitcode.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000053bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
54 return llvm::sys::IdentifyFileType((char*)mem, length)
55 == llvm::sys::Bitcode_FileType;
Nick Kledzik07b4a622008-02-26 20:26:43 +000056}
57
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000058bool LTOModule::isBitcodeFile(const char *path) {
59 return llvm::sys::Path(path).isBitcodeFile();
Nick Kledzik07b4a622008-02-26 20:26:43 +000060}
61
Bill Wendlingfb440502012-03-28 20:46:54 +000062/// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
63/// LLVM bitcode for the specified triple.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000064bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
65 const char *triplePrefix) {
66 MemoryBuffer *buffer = makeBuffer(mem, length);
67 if (!buffer)
Nick Kledzikb481c202009-06-01 20:33:09 +000068 return false;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000069 return isTargetMatch(buffer, triplePrefix);
Nick Kledzikb481c202009-06-01 20:33:09 +000070}
71
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000072bool LTOModule::isBitcodeFileForTarget(const char *path,
73 const char *triplePrefix) {
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +000074 OwningPtr<MemoryBuffer> buffer;
75 if (MemoryBuffer::getFile(path, buffer))
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000076 return false;
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +000077 return isTargetMatch(buffer.take(), triplePrefix);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000078}
79
Bill Wendlingfb440502012-03-28 20:46:54 +000080/// isTargetMatch - Returns 'true' if the memory buffer is for the specified
81/// target triple.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000082bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
Bill Wendling0198ce02010-10-06 01:22:42 +000083 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
84 delete buffer;
Bill Wendling5f689e72011-11-04 18:48:00 +000085 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000086}
87
Bill Wendlingfb440502012-03-28 20:46:54 +000088/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
89/// the buffer.
90LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +000091 OwningPtr<MemoryBuffer> buffer;
92 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
Michael J. Spencerd4227232010-12-09 18:06:07 +000093 errMsg = ec.message();
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000094 return NULL;
Michael J. Spencerd4227232010-12-09 18:06:07 +000095 }
Rafael Espindola5b778b22011-03-18 19:51:00 +000096 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +000097}
98
Rafael Espindola56e41f72011-02-08 22:40:47 +000099LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
Bill Wendling5f689e72011-11-04 18:48:00 +0000100 size_t size, std::string &errMsg) {
Rafael Espindolab39c7c72011-03-17 00:36:11 +0000101 return makeLTOModule(fd, path, size, size, 0, errMsg);
102}
103
104LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
105 size_t file_size,
106 size_t map_size,
107 off_t offset,
Rafael Espindola56e41f72011-02-08 22:40:47 +0000108 std::string &errMsg) {
109 OwningPtr<MemoryBuffer> buffer;
Rafael Espindolab39c7c72011-03-17 00:36:11 +0000110 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
111 map_size, offset, false)) {
Rafael Espindola56e41f72011-02-08 22:40:47 +0000112 errMsg = ec.message();
113 return NULL;
114 }
Rafael Espindola5b778b22011-03-18 19:51:00 +0000115 return makeLTOModule(buffer.take(), errMsg);
Rafael Espindola56e41f72011-02-08 22:40:47 +0000116}
117
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000118LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
119 std::string &errMsg) {
120 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
121 if (!buffer)
122 return NULL;
Rafael Espindola5b778b22011-03-18 19:51:00 +0000123 return makeLTOModule(buffer.take(), errMsg);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000124}
125
126LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
127 std::string &errMsg) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000128 static bool Initialized = false;
129 if (!Initialized) {
130 InitializeAllTargets();
Evan Cheng8c886a42011-07-22 21:58:54 +0000131 InitializeAllTargetMCs();
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000132 InitializeAllAsmParsers();
133 Initialized = true;
134 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000135
136 // parse bitcode buffer
Rafael Espindola5b778b22011-03-18 19:51:00 +0000137 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
138 &errMsg));
139 if (!m) {
140 delete buffer;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000141 return NULL;
Rafael Espindola5b778b22011-03-18 19:51:00 +0000142 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000143
144 std::string Triple = m->getTargetTriple();
145 if (Triple.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000146 Triple = sys::getDefaultTargetTriple();
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000147
148 // find machine architecture for this module
149 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
150 if (!march)
151 return NULL;
152
Nick Lewycky364c04a2011-04-21 01:54:08 +0000153 // construct LTOModule, hand over ownership of module and target
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000154 SubtargetFeatures Features;
Evan Chengfe6e4052011-06-30 01:53:36 +0000155 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000156 std::string FeatureStr = Features.getString();
Evan Chengfe6e4052011-06-30 01:53:36 +0000157 std::string CPU;
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000158 TargetOptions Options;
159 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
160 Options);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000161 LTOModule *Ret = new LTOModule(m.take(), target);
Bill Wendling7e58b382012-03-28 23:12:18 +0000162 if (Ret->parseSymbols(errMsg)) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000163 delete Ret;
164 return NULL;
165 }
Bill Wendling5f689e72011-11-04 18:48:00 +0000166
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000167 return Ret;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000168}
169
Bill Wendlingfb440502012-03-28 20:46:54 +0000170/// makeBuffer - Create a MemoryBuffer from a memory range.
171MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
172 const char *startPtr = (char*)mem;
173 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000174}
175
Bill Wendlingfb440502012-03-28 20:46:54 +0000176/// objcClassNameFromExpression - Get string that the data pointer points to.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000177bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
178 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
179 Constant *op = ce->getOperand(0);
180 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
181 Constant *cn = gvn->getInitializer();
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000182 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000183 if (ca->isCString()) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000184 name = ".objc_class_name_" + ca->getAsCString().str();
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000185 return true;
Nick Kledzikb481c202009-06-01 20:33:09 +0000186 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000187 }
Nick Kledzikb481c202009-06-01 20:33:09 +0000188 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000189 }
190 return false;
191}
192
Bill Wendlingfb440502012-03-28 20:46:54 +0000193/// addObjCClass - Parse i386/ppc ObjC class data structure.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000194void LTOModule::addObjCClass(GlobalVariable *clgv) {
Bill Wendling5f689e72011-11-04 18:48:00 +0000195 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
196 if (!c) return;
Nick Kledzikb481c202009-06-01 20:33:09 +0000197
Bill Wendling5f689e72011-11-04 18:48:00 +0000198 // second slot in __OBJC,__class is pointer to superclass name
199 std::string superclassName;
200 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
201 NameAndAttributes info;
202 StringMap<NameAndAttributes>::value_type &entry =
203 _undefines.GetOrCreateValue(superclassName);
204 if (!entry.getValue().name) {
Rafael Espindola477d11f2011-02-20 16:27:25 +0000205 const char *symbolName = entry.getKey().data();
206 info.name = symbolName;
207 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000208 info.isFunction = false;
209 info.symbol = clgv;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000210 entry.setValue(info);
Nick Kledzikb481c202009-06-01 20:33:09 +0000211 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000212 }
Bill Wendling5f689e72011-11-04 18:48:00 +0000213
214 // third slot in __OBJC,__class is pointer to class name
215 std::string className;
216 if (objcClassNameFromExpression(c->getOperand(2), className)) {
217 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
218 entry.setValue(1);
Bill Wendling9ee2d332012-03-29 08:27:32 +0000219
Bill Wendling5f689e72011-11-04 18:48:00 +0000220 NameAndAttributes info;
221 info.name = entry.getKey().data();
Bill Wendling9ee2d332012-03-29 08:27:32 +0000222 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
223 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
224 info.isFunction = false;
225 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000226 _symbols.push_back(info);
227 }
228}
229
Bill Wendlingfb440502012-03-28 20:46:54 +0000230/// addObjCCategory - Parse i386/ppc ObjC category data structure.
Bill Wendling5f689e72011-11-04 18:48:00 +0000231void LTOModule::addObjCCategory(GlobalVariable *clgv) {
232 ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
233 if (!c) return;
234
235 // second slot in __OBJC,__category is pointer to target class name
236 std::string targetclassName;
237 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
238 return;
239
240 NameAndAttributes info;
241 StringMap<NameAndAttributes>::value_type &entry =
242 _undefines.GetOrCreateValue(targetclassName);
243
244 if (entry.getValue().name)
245 return;
246
247 const char *symbolName = entry.getKey().data();
248 info.name = symbolName;
249 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000250 info.isFunction = false;
251 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000252 entry.setValue(info);
Nick Kledzikb481c202009-06-01 20:33:09 +0000253}
254
Bill Wendlingfb440502012-03-28 20:46:54 +0000255/// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000256void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
257 std::string targetclassName;
Bill Wendling5f689e72011-11-04 18:48:00 +0000258 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
259 return;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000260
Bill Wendling5f689e72011-11-04 18:48:00 +0000261 NameAndAttributes info;
262 StringMap<NameAndAttributes>::value_type &entry =
263 _undefines.GetOrCreateValue(targetclassName);
264 if (entry.getValue().name)
265 return;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000266
Bill Wendling5f689e72011-11-04 18:48:00 +0000267 const char *symbolName = entry.getKey().data();
268 info.name = symbolName;
269 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000270 info.isFunction = false;
271 info.symbol = clgv;
Bill Wendling5f689e72011-11-04 18:48:00 +0000272 entry.setValue(info);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000273}
274
Bill Wendlingfb440502012-03-28 20:46:54 +0000275/// addDefinedDataSymbol - Add a data symbol as defined to the list.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000276void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000277 // Add to list of defined symbols.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000278 addDefinedSymbol(v, false);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000279
280 // Special case i386/ppc ObjC data structures in magic sections:
281 // The issue is that the old ObjC object format did some strange
282 // contortions to avoid real linker symbols. For instance, the
283 // ObjC class data structure is allocated statically in the executable
284 // that defines that class. That data structures contains a pointer to
285 // its superclass. But instead of just initializing that part of the
286 // struct to the address of its superclass, and letting the static and
287 // dynamic linkers do the rest, the runtime works by having that field
288 // instead point to a C-string that is the name of the superclass.
289 // At runtime the objc initialization updates that pointer and sets
290 // it to point to the actual super class. As far as the linker
291 // knows it is just a pointer to a string. But then someone wanted the
292 // linker to issue errors at build time if the superclass was not found.
293 // So they figured out a way in mach-o object format to use an absolute
294 // symbols (.objc_class_name_Foo = 0) and a floating reference
295 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
296 // a class was missing.
297 // The following synthesizes the implicit .objc_* symbols for the linker
298 // from the ObjC data structures generated by the front end.
299 if (v->hasSection() /* && isTargetDarwin */) {
300 // special case if this data blob is an ObjC class definition
301 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
302 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
303 addObjCClass(gv);
304 }
305 }
306
307 // special case if this data blob is an ObjC category definition
308 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
309 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
310 addObjCCategory(gv);
311 }
312 }
313
314 // special case if this data blob is the list of referenced classes
315 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
316 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
317 addObjCClassRef(gv);
318 }
319 }
320 }
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000321}
322
Bill Wendlingfb440502012-03-28 20:46:54 +0000323/// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
324void LTOModule::addDefinedFunctionSymbol(Function *f) {
325 // add to list of defined symbols
326 addDefinedSymbol(f, true);
327}
328
329/// addDefinedSymbol - Add a defined symbol to the list.
Bill Wendlinga2af6742011-11-04 09:30:19 +0000330void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000331 // ignore all llvm.* symbols
332 if (def->getName().startswith("llvm."))
333 return;
334
335 // string is owned by _defines
Rafael Espindola34b59382011-02-11 05:23:09 +0000336 SmallString<64> Buffer;
Bill Wendlinga2af6742011-11-04 09:30:19 +0000337 _mangler.getNameWithPrefix(Buffer, def, false);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000338
339 // set alignment part log2() can have rounding errors
340 uint32_t align = def->getAlignment();
341 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
342
343 // set permissions part
Bill Wendling9ee2d332012-03-29 08:27:32 +0000344 if (isFunction) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000345 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
Bill Wendling9ee2d332012-03-29 08:27:32 +0000346 } else {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000347 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
348 if (gv && gv->isConstant())
349 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
350 else
351 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
352 }
353
354 // set definition part
Bill Wendling2776d462010-09-27 18:05:19 +0000355 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
356 def->hasLinkerPrivateWeakLinkage() ||
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000357 def->hasLinkerPrivateWeakDefAutoLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000358 attr |= LTO_SYMBOL_DEFINITION_WEAK;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000359 else if (def->hasCommonLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000360 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000361 else
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000362 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000363
364 // set scope part
365 if (def->hasHiddenVisibility())
366 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
367 else if (def->hasProtectedVisibility())
368 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000369 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
370 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
371 def->hasLinkerPrivateWeakLinkage())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000372 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
Bill Wendlingdcd7c2b2010-09-27 20:17:45 +0000373 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
374 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000375 else
376 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
377
Chad Rosier772a91f2011-06-28 18:26:12 +0000378 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
Rafael Espindola477d11f2011-02-20 16:27:25 +0000379 entry.setValue(1);
380
Bill Wendling9ee2d332012-03-29 08:27:32 +0000381 // fill information structure
382 NameAndAttributes info;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000383 StringRef Name = entry.getKey();
384 info.name = Name.data();
385 assert(info.name[Name.size()] == '\0');
Bill Wendling9ee2d332012-03-29 08:27:32 +0000386 info.attributes = attr;
387 info.isFunction = isFunction;
388 info.symbol = def;
389
390 // add to table of symbols
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000391 _symbols.push_back(info);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000392}
393
Bill Wendlingfb440502012-03-28 20:46:54 +0000394/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
395/// defined list.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000396void LTOModule::addAsmGlobalSymbol(const char *name,
397 lto_symbol_attributes scope) {
Rafael Espindola477d11f2011-02-20 16:27:25 +0000398 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
399
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000400 // only add new define if not already defined
Rafael Espindola477d11f2011-02-20 16:27:25 +0000401 if (entry.getValue())
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000402 return;
403
Rafael Espindola477d11f2011-02-20 16:27:25 +0000404 entry.setValue(1);
Bill Wendling9ee2d332012-03-29 08:27:32 +0000405
406 NameAndAttributes &info = _undefines[entry.getKey().data()];
407
408 if (info.isFunction)
409 addDefinedFunctionSymbol(cast<Function>(info.symbol));
410 else
411 addDefinedDataSymbol(info.symbol);
Bill Wendling8f6c8a92012-03-30 23:26:06 +0000412
413 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
414 _symbols.back().attributes |= scope;
Devang Patela59fe952008-07-16 18:06:52 +0000415}
Nick Kledzik07b4a622008-02-26 20:26:43 +0000416
Bill Wendlingfb440502012-03-28 20:46:54 +0000417/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
418/// undefined list.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000419void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
420 StringMap<NameAndAttributes>::value_type &entry =
421 _undefines.GetOrCreateValue(name);
422
423 _asm_undefines.push_back(entry.getKey().data());
424
425 // we already have the symbol
426 if (entry.getValue().name)
427 return;
428
429 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
430 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
431 NameAndAttributes info;
432 info.name = entry.getKey().data();
Bill Wendling9ee2d332012-03-29 08:27:32 +0000433 info.attributes = attr;
434 info.isFunction = false;
435 info.symbol = 0;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000436
437 entry.setValue(info);
438}
439
Bill Wendlingfb440502012-03-28 20:46:54 +0000440/// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
441/// list to be resolved later.
Bill Wendling9ee2d332012-03-29 08:27:32 +0000442void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) {
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000443 // ignore all llvm.* symbols
444 if (decl->getName().startswith("llvm."))
445 return;
Nick Kledzikb481c202009-06-01 20:33:09 +0000446
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000447 // ignore all aliases
448 if (isa<GlobalAlias>(decl))
449 return;
Nick Lewycky0661b932009-07-09 06:03:04 +0000450
Rafael Espindola34b59382011-02-11 05:23:09 +0000451 SmallString<64> name;
Bill Wendlinga2af6742011-11-04 09:30:19 +0000452 _mangler.getNameWithPrefix(name, decl, false);
Rafael Espindola56548522009-04-24 16:55:21 +0000453
Rafael Espindola477d11f2011-02-20 16:27:25 +0000454 StringMap<NameAndAttributes>::value_type &entry =
Chad Rosier772a91f2011-06-28 18:26:12 +0000455 _undefines.GetOrCreateValue(name);
Rafael Espindola477d11f2011-02-20 16:27:25 +0000456
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000457 // we already have the symbol
Rafael Espindola477d11f2011-02-20 16:27:25 +0000458 if (entry.getValue().name)
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000459 return;
Rafael Espindola56548522009-04-24 16:55:21 +0000460
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000461 NameAndAttributes info;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000462
463 info.name = entry.getKey().data();
Bill Wendlingfb440502012-03-28 20:46:54 +0000464
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000465 if (decl->hasExternalWeakLinkage())
466 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
467 else
468 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
Rafael Espindola477d11f2011-02-20 16:27:25 +0000469
Bill Wendling9ee2d332012-03-29 08:27:32 +0000470 info.isFunction = isFunc;
471 info.symbol = decl;
472
Rafael Espindola477d11f2011-02-20 16:27:25 +0000473 entry.setValue(info);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000474}
475
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000476namespace {
477 class RecordStreamer : public MCStreamer {
478 public:
479 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000480
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000481 private:
482 StringMap<State> Symbols;
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000483
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000484 void markDefined(const MCSymbol &Symbol) {
485 State &S = Symbols[Symbol.getName()];
486 switch (S) {
487 case DefinedGlobal:
488 case Global:
489 S = DefinedGlobal;
490 break;
491 case NeverSeen:
492 case Defined:
493 case Used:
494 S = Defined;
495 break;
496 }
497 }
498 void markGlobal(const MCSymbol &Symbol) {
499 State &S = Symbols[Symbol.getName()];
500 switch (S) {
501 case DefinedGlobal:
502 case Defined:
503 S = DefinedGlobal;
504 break;
505
506 case NeverSeen:
507 case Global:
508 case Used:
509 S = Global;
510 break;
511 }
512 }
513 void markUsed(const MCSymbol &Symbol) {
514 State &S = Symbols[Symbol.getName()];
515 switch (S) {
516 case DefinedGlobal:
517 case Defined:
518 case Global:
519 break;
520
521 case NeverSeen:
522 case Used:
523 S = Used;
524 break;
525 }
526 }
527
528 // FIXME: mostly copied for the obj streamer.
529 void AddValueSymbols(const MCExpr *Value) {
530 switch (Value->getKind()) {
531 case MCExpr::Target:
532 // FIXME: What should we do in here?
533 break;
534
535 case MCExpr::Constant:
536 break;
537
538 case MCExpr::Binary: {
539 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
540 AddValueSymbols(BE->getLHS());
541 AddValueSymbols(BE->getRHS());
542 break;
543 }
544
545 case MCExpr::SymbolRef:
546 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
547 break;
548
549 case MCExpr::Unary:
550 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
551 break;
552 }
553 }
554
555 public:
556 typedef StringMap<State>::const_iterator const_iterator;
557
558 const_iterator begin() {
559 return Symbols.begin();
560 }
561
562 const_iterator end() {
563 return Symbols.end();
564 }
565
566 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
567
568 virtual void ChangeSection(const MCSection *Section) {}
569 virtual void InitSections() {}
570 virtual void EmitLabel(MCSymbol *Symbol) {
571 Symbol->setSection(*getCurrentSection());
572 markDefined(*Symbol);
573 }
574 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
575 virtual void EmitThumbFunc(MCSymbol *Func) {}
576 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
577 // FIXME: should we handle aliases?
578 markDefined(*Symbol);
579 }
580 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
581 if (Attribute == MCSA_Global)
582 markGlobal(*Symbol);
583 }
584 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
585 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
586 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
587 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
588 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
589 unsigned Size , unsigned ByteAlignment) {
590 markDefined(*Symbol);
591 }
592 virtual void EmitCOFFSymbolType(int Type) {}
593 virtual void EndCOFFSymbolDef() {}
594 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
595 unsigned ByteAlignment) {
596 markDefined(*Symbol);
597 }
598 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
Benjamin Kramer63970512011-09-01 23:04:27 +0000599 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
600 unsigned ByteAlignment) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000601 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
602 uint64_t Size, unsigned ByteAlignment) {}
603 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
604 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
Rafael Espindolafd057852011-05-01 03:50:49 +0000605 unsigned AddrSpace) {}
Rafael Espindola6aea5922011-04-21 23:39:26 +0000606 virtual void EmitULEB128Value(const MCExpr *Value) {}
607 virtual void EmitSLEB128Value(const MCExpr *Value) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000608 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
609 unsigned ValueSize,
610 unsigned MaxBytesToEmit) {}
611 virtual void EmitCodeAlignment(unsigned ByteAlignment,
612 unsigned MaxBytesToEmit) {}
Jim Grosbachb5912772012-01-27 00:37:08 +0000613 virtual bool EmitValueToOffset(const MCExpr *Offset,
614 unsigned char Value ) { return false; }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000615 virtual void EmitFileDirective(StringRef Filename) {}
616 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
617 const MCSymbol *LastLabel,
Evan Chengc7ac6902011-07-14 05:43:07 +0000618 const MCSymbol *Label,
619 unsigned PointerSize) {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000620
621 virtual void EmitInstruction(const MCInst &Inst) {
622 // Scan for values.
623 for (unsigned i = Inst.getNumOperands(); i--; )
624 if (Inst.getOperand(i).isExpr())
625 AddValueSymbols(Inst.getOperand(i).getExpr());
626 }
Rafael Espindola07082092012-01-07 03:13:18 +0000627 virtual void FinishImpl() {}
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000628 };
Bill Wendling9ee2d332012-03-29 08:27:32 +0000629} // end anonymous namespace
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000630
Bill Wendlingfb440502012-03-28 20:46:54 +0000631/// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
632/// defined or undefined lists.
Bill Wendlingac2abde2011-11-04 09:24:40 +0000633bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000634 const std::string &inlineAsm = _module->getModuleInlineAsm();
Ivan Krasincc2a8012011-09-08 07:38:25 +0000635 if (inlineAsm.empty())
636 return false;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000637
Bill Wendlingac2abde2011-11-04 09:24:40 +0000638 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000639 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
640 SourceMgr SrcMgr;
641 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
Jim Grosbach345768c2011-08-16 18:33:49 +0000642 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
Bill Wendlingac2abde2011-11-04 09:24:40 +0000643 _context, *Streamer,
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000644 *_target->getMCAsmInfo()));
Evan Cheng91111d22011-07-09 05:47:46 +0000645 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
646 createMCSubtargetInfo(_target->getTargetTriple(),
647 _target->getTargetCPU(),
648 _target->getTargetFeatureString()));
Evan Cheng11424442011-07-26 00:24:13 +0000649 OwningPtr<MCTargetAsmParser>
650 TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
Ivan Krasin8149dd62011-09-08 07:36:39 +0000651 if (!TAP) {
652 errMsg = "target " + std::string(_target->getTarget().getName()) +
653 " does not define AsmParser.";
654 return true;
655 }
656
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000657 Parser->setTargetParser(*TAP);
658 int Res = Parser->Run(false);
659 if (Res)
660 return true;
661
662 for (RecordStreamer::const_iterator i = Streamer->begin(),
663 e = Streamer->end(); i != e; ++i) {
664 StringRef Key = i->first();
665 RecordStreamer::State Value = i->second;
666 if (Value == RecordStreamer::DefinedGlobal)
667 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
668 else if (Value == RecordStreamer::Defined)
669 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
670 else if (Value == RecordStreamer::Global ||
671 Value == RecordStreamer::Used)
672 addAsmGlobalSymbolUndef(Key.data());
673 }
674 return false;
675}
676
Bill Wendlingfb440502012-03-28 20:46:54 +0000677/// isDeclaration - Return 'true' if the global value is a declaration.
Rafael Espindola5b778b22011-03-18 19:51:00 +0000678static bool isDeclaration(const GlobalValue &V) {
679 if (V.hasAvailableExternallyLinkage())
680 return true;
681 if (V.isMaterializable())
682 return false;
683 return V.isDeclaration();
684}
685
Bill Wendling7e58b382012-03-28 23:12:18 +0000686/// parseSymbols - Parse the symbols from the module and model-level ASM and add
Bill Wendlingfb440502012-03-28 20:46:54 +0000687/// them to either the defined or undefined lists.
Bill Wendling7e58b382012-03-28 23:12:18 +0000688bool LTOModule::parseSymbols(std::string &errMsg) {
Daniel Dunbar919660b2010-08-10 23:46:46 +0000689 // add functions
Bill Wendling763acfc2012-03-29 03:34:57 +0000690 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
Rafael Espindola5b778b22011-03-18 19:51:00 +0000691 if (isDeclaration(*f))
Bill Wendling9ee2d332012-03-29 08:27:32 +0000692 addPotentialUndefinedSymbol(f, true);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000693 else
Bill Wendlinga2af6742011-11-04 09:30:19 +0000694 addDefinedFunctionSymbol(f);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000695 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000696
Daniel Dunbar919660b2010-08-10 23:46:46 +0000697 // add data
698 for (Module::global_iterator v = _module->global_begin(),
699 e = _module->global_end(); v != e; ++v) {
Rafael Espindola5b778b22011-03-18 19:51:00 +0000700 if (isDeclaration(*v))
Bill Wendling9ee2d332012-03-29 08:27:32 +0000701 addPotentialUndefinedSymbol(v, false);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000702 else
Bill Wendlinga2af6742011-11-04 09:30:19 +0000703 addDefinedDataSymbol(v);
Daniel Dunbar919660b2010-08-10 23:46:46 +0000704 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000705
Daniel Dunbar919660b2010-08-10 23:46:46 +0000706 // add asm globals
Bill Wendlingac2abde2011-11-04 09:24:40 +0000707 if (addAsmGlobalSymbols(errMsg))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000708 return true;
Daniel Dunbar919660b2010-08-10 23:46:46 +0000709
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000710 // add aliases
Bill Wendling9ee2d332012-03-29 08:27:32 +0000711 for (Module::alias_iterator a = _module->alias_begin(),
712 e = _module->alias_end(); a != e; ++a) {
713 if (isDeclaration(*a->getAliasedGlobal()))
Bill Wendlingd58ed732012-03-28 20:48:49 +0000714 // Is an alias to a declaration.
Bill Wendling9ee2d332012-03-29 08:27:32 +0000715 addPotentialUndefinedSymbol(a, false);
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000716 else
Bill Wendling9ee2d332012-03-29 08:27:32 +0000717 addDefinedDataSymbol(a);
Rafael Espindolaa8a74ec2010-10-20 04:57:22 +0000718 }
719
Daniel Dunbar919660b2010-08-10 23:46:46 +0000720 // make symbols for all undefines
Bill Wendling9ee2d332012-03-29 08:27:32 +0000721 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
722 e = _undefines.end(); u != e; ++u) {
723 // If this symbol also has a definition, then don't make an undefine because
724 // it is a tentative definition.
725 if (_defines.count(u->getKey())) continue;
726 NameAndAttributes info = u->getValue();
727 _symbols.push_back(info);
Daniel Dunbar5657e7b2010-08-10 23:46:39 +0000728 }
Bill Wendling9ee2d332012-03-29 08:27:32 +0000729
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000730 return false;
Nick Kledzik91a6dcf2008-02-27 22:25:36 +0000731}