1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
2 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LTOModule.h"
16
17 #include "llvm/Constants.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/system_error.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Target/TargetAsmParser.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46
47 using namespace llvm;
48
isBitcodeFile(const void * mem,size_t length)49 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
50 return llvm::sys::IdentifyFileType((char*)mem, length)
51 == llvm::sys::Bitcode_FileType;
52 }
53
isBitcodeFile(const char * path)54 bool LTOModule::isBitcodeFile(const char *path) {
55 return llvm::sys::Path(path).isBitcodeFile();
56 }
57
isBitcodeFileForTarget(const void * mem,size_t length,const char * triplePrefix)58 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
59 const char *triplePrefix) {
60 MemoryBuffer *buffer = makeBuffer(mem, length);
61 if (!buffer)
62 return false;
63 return isTargetMatch(buffer, triplePrefix);
64 }
65
66
isBitcodeFileForTarget(const char * path,const char * triplePrefix)67 bool LTOModule::isBitcodeFileForTarget(const char *path,
68 const char *triplePrefix) {
69 OwningPtr<MemoryBuffer> buffer;
70 if (MemoryBuffer::getFile(path, buffer))
71 return false;
72 return isTargetMatch(buffer.take(), triplePrefix);
73 }
74
75 // Takes ownership of buffer.
isTargetMatch(MemoryBuffer * buffer,const char * triplePrefix)76 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
77 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
78 delete buffer;
79 return (strncmp(Triple.c_str(), triplePrefix,
80 strlen(triplePrefix)) == 0);
81 }
82
83
LTOModule(Module * m,TargetMachine * t)84 LTOModule::LTOModule(Module *m, TargetMachine *t)
85 : _module(m), _target(t)
86 {
87 }
88
makeLTOModule(const char * path,std::string & errMsg)89 LTOModule *LTOModule::makeLTOModule(const char *path,
90 std::string &errMsg) {
91 OwningPtr<MemoryBuffer> buffer;
92 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
93 errMsg = ec.message();
94 return NULL;
95 }
96 return makeLTOModule(buffer.take(), errMsg);
97 }
98
makeLTOModule(int fd,const char * path,size_t size,std::string & errMsg)99 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
100 size_t size,
101 std::string &errMsg) {
102 return makeLTOModule(fd, path, size, size, 0, errMsg);
103 }
104
makeLTOModule(int fd,const char * path,size_t file_size,size_t map_size,off_t offset,std::string & errMsg)105 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
106 size_t file_size,
107 size_t map_size,
108 off_t offset,
109 std::string &errMsg) {
110 OwningPtr<MemoryBuffer> buffer;
111 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
112 map_size, offset, false)) {
113 errMsg = ec.message();
114 return NULL;
115 }
116 return makeLTOModule(buffer.take(), errMsg);
117 }
118
119 /// makeBuffer - Create a MemoryBuffer from a memory range.
makeBuffer(const void * mem,size_t length)120 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
121 const char *startPtr = (char*)mem;
122 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
123 }
124
125
makeLTOModule(const void * mem,size_t length,std::string & errMsg)126 LTOModule *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;
131 return makeLTOModule(buffer.take(), errMsg);
132 }
133
makeLTOModule(MemoryBuffer * buffer,std::string & errMsg)134 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
135 std::string &errMsg) {
136 static bool Initialized = false;
137 if (!Initialized) {
138 InitializeAllTargets();
139 InitializeAllMCCodeGenInfos();
140 InitializeAllMCAsmInfos();
141 InitializeAllMCSubtargetInfos();
142 InitializeAllAsmParsers();
143 Initialized = true;
144 }
145
146 // parse bitcode buffer
147 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
148 &errMsg));
149 if (!m) {
150 delete buffer;
151 return NULL;
152 }
153
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
163 // construct LTOModule, hand over ownership of module and target
164 SubtargetFeatures Features;
165 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
166 std::string FeatureStr = Features.getString();
167 std::string CPU;
168 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
169 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;
176 }
177
178
getTargetTriple()179 const char *LTOModule::getTargetTriple() {
180 return _module->getTargetTriple().c_str();
181 }
182
setTargetTriple(const char * triple)183 void LTOModule::setTargetTriple(const char *triple) {
184 _module->setTargetTriple(triple);
185 }
186
addDefinedFunctionSymbol(Function * f,Mangler & mangler)187 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
188 // add to list of defined symbols
189 addDefinedSymbol(f, mangler, true);
190 }
191
192 // Get string that data pointer points to.
objcClassNameFromExpression(Constant * c,std::string & name)193 bool 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()) {
200 name = ".objc_class_name_" + ca->getAsCString();
201 return true;
202 }
203 }
204 }
205 }
206 return false;
207 }
208
209 // Parse i386/ppc ObjC class data structure.
addObjCClass(GlobalVariable * clgv)210 void 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;
216 StringMap<NameAndAttributes>::value_type &entry =
217 _undefines.GetOrCreateValue(superclassName);
218 if (!entry.getValue().name) {
219 const char *symbolName = entry.getKey().data();
220 info.name = symbolName;
221 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
222 entry.setValue(info);
223 }
224 }
225 // third slot in __OBJC,__class is pointer to class name
226 std::string className;
227 if (objcClassNameFromExpression(c->getOperand(2), className)) {
228 StringSet::value_type &entry =
229 _defines.GetOrCreateValue(className);
230 entry.setValue(1);
231 NameAndAttributes info;
232 info.name = entry.getKey().data();
233 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);
238 }
239 }
240 }
241
242
243 // Parse i386/ppc ObjC category data structure.
addObjCCategory(GlobalVariable * clgv)244 void 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
247 std::string targetclassName;
248 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
249 NameAndAttributes info;
250
251 StringMap<NameAndAttributes>::value_type &entry =
252 _undefines.GetOrCreateValue(targetclassName);
253
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);
261 }
262 }
263 }
264
265
266 // Parse i386/ppc ObjC class list data structure.
addObjCClassRef(GlobalVariable * clgv)267 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
268 std::string targetclassName;
269 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
270 NameAndAttributes info;
271
272 StringMap<NameAndAttributes>::value_type &entry =
273 _undefines.GetOrCreateValue(targetclassName);
274 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);
281 }
282 }
283
284
addDefinedDataSymbol(GlobalValue * v,Mangler & mangler)285 void 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 }
330 }
331
332
addDefinedSymbol(GlobalValue * def,Mangler & mangler,bool isFunction)333 void 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
340 SmallString<64> Buffer;
341 mangler.getNameWithPrefix(Buffer, def, false);
342
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
359 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
360 def->hasLinkerPrivateWeakLinkage() ||
361 def->hasLinkerPrivateWeakDefAutoLinkage())
362 attr |= LTO_SYMBOL_DEFINITION_WEAK;
363 else if (def->hasCommonLinkage())
364 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
365 else
366 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
367
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;
373 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
374 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
375 def->hasLinkerPrivateWeakLinkage())
376 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
377 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
378 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
379 else
380 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
381
382 // add to table of symbols
383 NameAndAttributes info;
384 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
385 entry.setValue(1);
386
387 StringRef Name = entry.getKey();
388 info.name = Name.data();
389 assert(info.name[Name.size()] == '\0');
390 info.attributes = (lto_symbol_attributes)attr;
391 _symbols.push_back(info);
392 }
393
addAsmGlobalSymbol(const char * name,lto_symbol_attributes scope)394 void LTOModule::addAsmGlobalSymbol(const char *name,
395 lto_symbol_attributes scope) {
396 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
397
398 // only add new define if not already defined
399 if (entry.getValue())
400 return;
401
402 entry.setValue(1);
403 const char *symbolName = entry.getKey().data();
404 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
405 attr |= scope;
406 NameAndAttributes info;
407 info.name = symbolName;
408 info.attributes = (lto_symbol_attributes)attr;
409 _symbols.push_back(info);
410 }
411
addAsmGlobalSymbolUndef(const char * name)412 void 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
addPotentialUndefinedSymbol(GlobalValue * decl,Mangler & mangler)431 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
432 Mangler &mangler) {
433 // ignore all llvm.* symbols
434 if (decl->getName().startswith("llvm."))
435 return;
436
437 // ignore all aliases
438 if (isa<GlobalAlias>(decl))
439 return;
440
441 SmallString<64> name;
442 mangler.getNameWithPrefix(name, decl, false);
443
444 StringMap<NameAndAttributes>::value_type &entry =
445 _undefines.GetOrCreateValue(name);
446
447 // we already have the symbol
448 if (entry.getValue().name)
449 return;
450
451 NameAndAttributes info;
452
453 info.name = entry.getKey().data();
454 if (decl->hasExternalWeakLinkage())
455 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
456 else
457 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
458
459 entry.setValue(info);
460 }
461
462
463 namespace {
464 class RecordStreamer : public MCStreamer {
465 public:
466 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
467
468 private:
469 StringMap<State> Symbols;
470
markDefined(const MCSymbol & Symbol)471 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 }
markGlobal(const MCSymbol & Symbol)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 }
markUsed(const MCSymbol & Symbol)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.
AddValueSymbols(const MCExpr * Value)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
begin()545 const_iterator begin() {
546 return Symbols.begin();
547 }
548
end()549 const_iterator end() {
550 return Symbols.end();
551 }
552
RecordStreamer(MCContext & Context)553 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
554
ChangeSection(const MCSection * Section)555 virtual void ChangeSection(const MCSection *Section) {}
InitSections()556 virtual void InitSections() {}
EmitLabel(MCSymbol * Symbol)557 virtual void EmitLabel(MCSymbol *Symbol) {
558 Symbol->setSection(*getCurrentSection());
559 markDefined(*Symbol);
560 }
EmitAssemblerFlag(MCAssemblerFlag Flag)561 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
EmitThumbFunc(MCSymbol * Func)562 virtual void EmitThumbFunc(MCSymbol *Func) {}
EmitAssignment(MCSymbol * Symbol,const MCExpr * Value)563 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
564 // FIXME: should we handle aliases?
565 markDefined(*Symbol);
566 }
EmitSymbolAttribute(MCSymbol * Symbol,MCSymbolAttr Attribute)567 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
568 if (Attribute == MCSA_Global)
569 markGlobal(*Symbol);
570 }
EmitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)571 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
EmitWeakReference(MCSymbol * Alias,const MCSymbol * Symbol)572 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
BeginCOFFSymbolDef(const MCSymbol * Symbol)573 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
EmitCOFFSymbolStorageClass(int StorageClass)574 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
EmitZerofill(const MCSection * Section,MCSymbol * Symbol,unsigned Size,unsigned ByteAlignment)575 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
576 unsigned Size , unsigned ByteAlignment) {
577 markDefined(*Symbol);
578 }
EmitCOFFSymbolType(int Type)579 virtual void EmitCOFFSymbolType(int Type) {}
EndCOFFSymbolDef()580 virtual void EndCOFFSymbolDef() {}
EmitCommonSymbol(MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)581 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
582 unsigned ByteAlignment) {
583 markDefined(*Symbol);
584 }
EmitELFSize(MCSymbol * Symbol,const MCExpr * Value)585 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
EmitLocalCommonSymbol(MCSymbol * Symbol,uint64_t Size)586 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
EmitTBSSSymbol(const MCSection * Section,MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)587 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
588 uint64_t Size, unsigned ByteAlignment) {}
EmitBytes(StringRef Data,unsigned AddrSpace)589 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
EmitValueImpl(const MCExpr * Value,unsigned Size,unsigned AddrSpace)590 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
591 unsigned AddrSpace) {}
EmitULEB128Value(const MCExpr * Value)592 virtual void EmitULEB128Value(const MCExpr *Value) {}
EmitSLEB128Value(const MCExpr * Value)593 virtual void EmitSLEB128Value(const MCExpr *Value) {}
EmitValueToAlignment(unsigned ByteAlignment,int64_t Value,unsigned ValueSize,unsigned MaxBytesToEmit)594 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
595 unsigned ValueSize,
596 unsigned MaxBytesToEmit) {}
EmitCodeAlignment(unsigned ByteAlignment,unsigned MaxBytesToEmit)597 virtual void EmitCodeAlignment(unsigned ByteAlignment,
598 unsigned MaxBytesToEmit) {}
EmitValueToOffset(const MCExpr * Offset,unsigned char Value)599 virtual void EmitValueToOffset(const MCExpr *Offset,
600 unsigned char Value ) {}
EmitFileDirective(StringRef Filename)601 virtual void EmitFileDirective(StringRef Filename) {}
EmitDwarfAdvanceLineAddr(int64_t LineDelta,const MCSymbol * LastLabel,const MCSymbol * Label,unsigned PointerSize)602 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
603 const MCSymbol *LastLabel,
604 const MCSymbol *Label,
605 unsigned PointerSize) {}
606
EmitInstruction(const MCInst & Inst)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 }
Finish()613 virtual void Finish() {}
614 };
615 }
616
addAsmGlobalSymbols(MCContext & Context)617 bool 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()));
627 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
628 createMCSubtargetInfo(_target->getTargetTriple(),
629 _target->getTargetCPU(),
630 _target->getTargetFeatureString()));
631 OwningPtr<TargetAsmParser>
632 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
633 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
isDeclaration(const GlobalValue & V)653 static 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
isAliasToDeclaration(const GlobalAlias & V)661 static bool isAliasToDeclaration(const GlobalAlias &V) {
662 return isDeclaration(*V.getAliasedGlobal());
663 }
664
ParseSymbols()665 bool LTOModule::ParseSymbols() {
666 // Use mangler to add GlobalPrefix to names to match linker names.
667 MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),
668 NULL, NULL);
669 Mangler mangler(Context, *_target->getTargetData());
670
671 // add functions
672 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
673 if (isDeclaration(*f))
674 addPotentialUndefinedSymbol(f, mangler);
675 else
676 addDefinedFunctionSymbol(f, mangler);
677 }
678
679 // add data
680 for (Module::global_iterator v = _module->global_begin(),
681 e = _module->global_end(); v != e; ++v) {
682 if (isDeclaration(*v))
683 addPotentialUndefinedSymbol(v, mangler);
684 else
685 addDefinedDataSymbol(v, mangler);
686 }
687
688 // add asm globals
689 if (addAsmGlobalSymbols(Context))
690 return true;
691
692 // add aliases
693 for (Module::alias_iterator i = _module->alias_begin(),
694 e = _module->alias_end(); i != e; ++i) {
695 if (isAliasToDeclaration(*i))
696 addPotentialUndefinedSymbol(i, mangler);
697 else
698 addDefinedDataSymbol(i, mangler);
699 }
700
701 // make symbols for all undefines
702 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
703 it != _undefines.end(); ++it) {
704 // if this symbol also has a definition, then don't make an undefine
705 // because it is a tentative definition
706 if (_defines.count(it->getKey()) == 0) {
707 NameAndAttributes info = it->getValue();
708 _symbols.push_back(info);
709 }
710 }
711 return false;
712 }
713
714
getSymbolCount()715 uint32_t LTOModule::getSymbolCount() {
716 return _symbols.size();
717 }
718
719
getSymbolAttributes(uint32_t index)720 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
721 if (index < _symbols.size())
722 return _symbols[index].attributes;
723 else
724 return lto_symbol_attributes(0);
725 }
726
getSymbolName(uint32_t index)727 const char *LTOModule::getSymbolName(uint32_t index) {
728 if (index < _symbols.size())
729 return _symbols[index].name;
730 else
731 return NULL;
732 }
733