• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/TargetRegistry.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/system_error.h"
33 #include "llvm/Target/Mangler.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCParser/MCAsmParser.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/MC/SubtargetFeature.h"
43 #include "llvm/MC/MCTargetAsmParser.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetRegisterInfo.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     InitializeAllTargetMCs();
140     InitializeAllAsmParsers();
141     Initialized = true;
142   }
143 
144   // parse bitcode buffer
145   OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
146                                            &errMsg));
147   if (!m) {
148     delete buffer;
149     return NULL;
150   }
151 
152   std::string Triple = m->getTargetTriple();
153   if (Triple.empty())
154     Triple = sys::getHostTriple();
155 
156   // find machine architecture for this module
157   const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
158   if (!march)
159     return NULL;
160 
161   // construct LTOModule, hand over ownership of module and target
162   SubtargetFeatures Features;
163   Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
164   std::string FeatureStr = Features.getString();
165   std::string CPU;
166   TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
167   LTOModule *Ret = new LTOModule(m.take(), target);
168   bool Err = Ret->ParseSymbols(errMsg);
169   if (Err) {
170     delete Ret;
171     return NULL;
172   }
173   return Ret;
174 }
175 
176 
getTargetTriple()177 const char *LTOModule::getTargetTriple() {
178   return _module->getTargetTriple().c_str();
179 }
180 
setTargetTriple(const char * triple)181 void LTOModule::setTargetTriple(const char *triple) {
182   _module->setTargetTriple(triple);
183 }
184 
addDefinedFunctionSymbol(Function * f,Mangler & mangler)185 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
186   // add to list of defined symbols
187   addDefinedSymbol(f, mangler, true);
188 }
189 
190 // Get string that data pointer points to.
objcClassNameFromExpression(Constant * c,std::string & name)191 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
192   if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
193     Constant *op = ce->getOperand(0);
194     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
195       Constant *cn = gvn->getInitializer();
196       if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
197         if (ca->isCString()) {
198           name = ".objc_class_name_" + ca->getAsCString();
199           return true;
200         }
201       }
202     }
203   }
204   return false;
205 }
206 
207 // Parse i386/ppc ObjC class data structure.
addObjCClass(GlobalVariable * clgv)208 void LTOModule::addObjCClass(GlobalVariable *clgv) {
209   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
210     // second slot in __OBJC,__class is pointer to superclass name
211     std::string superclassName;
212     if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
213       NameAndAttributes info;
214       StringMap<NameAndAttributes>::value_type &entry =
215         _undefines.GetOrCreateValue(superclassName);
216       if (!entry.getValue().name) {
217         const char *symbolName = entry.getKey().data();
218         info.name = symbolName;
219         info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
220         entry.setValue(info);
221       }
222     }
223     // third slot in __OBJC,__class is pointer to class name
224     std::string className;
225     if (objcClassNameFromExpression(c->getOperand(2), className)) {
226       StringSet::value_type &entry =
227         _defines.GetOrCreateValue(className);
228       entry.setValue(1);
229       NameAndAttributes info;
230       info.name = entry.getKey().data();
231       info.attributes = (lto_symbol_attributes)
232         (LTO_SYMBOL_PERMISSIONS_DATA |
233          LTO_SYMBOL_DEFINITION_REGULAR |
234          LTO_SYMBOL_SCOPE_DEFAULT);
235       _symbols.push_back(info);
236     }
237   }
238 }
239 
240 
241 // Parse i386/ppc ObjC category data structure.
addObjCCategory(GlobalVariable * clgv)242 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
243   if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
244     // second slot in __OBJC,__category is pointer to target class name
245     std::string targetclassName;
246     if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
247       NameAndAttributes info;
248 
249       StringMap<NameAndAttributes>::value_type &entry =
250         _undefines.GetOrCreateValue(targetclassName);
251 
252       if (entry.getValue().name)
253         return;
254 
255       const char *symbolName = entry.getKey().data();
256       info.name = symbolName;
257       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
258       entry.setValue(info);
259     }
260   }
261 }
262 
263 
264 // Parse i386/ppc ObjC class list data structure.
addObjCClassRef(GlobalVariable * clgv)265 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
266   std::string targetclassName;
267   if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
268     NameAndAttributes info;
269 
270     StringMap<NameAndAttributes>::value_type &entry =
271       _undefines.GetOrCreateValue(targetclassName);
272     if (entry.getValue().name)
273       return;
274 
275     const char *symbolName = entry.getKey().data();
276     info.name = symbolName;
277     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
278     entry.setValue(info);
279   }
280 }
281 
282 
addDefinedDataSymbol(GlobalValue * v,Mangler & mangler)283 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
284   // Add to list of defined symbols.
285   addDefinedSymbol(v, mangler, false);
286 
287   // Special case i386/ppc ObjC data structures in magic sections:
288   // The issue is that the old ObjC object format did some strange
289   // contortions to avoid real linker symbols.  For instance, the
290   // ObjC class data structure is allocated statically in the executable
291   // that defines that class.  That data structures contains a pointer to
292   // its superclass.  But instead of just initializing that part of the
293   // struct to the address of its superclass, and letting the static and
294   // dynamic linkers do the rest, the runtime works by having that field
295   // instead point to a C-string that is the name of the superclass.
296   // At runtime the objc initialization updates that pointer and sets
297   // it to point to the actual super class.  As far as the linker
298   // knows it is just a pointer to a string.  But then someone wanted the
299   // linker to issue errors at build time if the superclass was not found.
300   // So they figured out a way in mach-o object format to use an absolute
301   // symbols (.objc_class_name_Foo = 0) and a floating reference
302   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
303   // a class was missing.
304   // The following synthesizes the implicit .objc_* symbols for the linker
305   // from the ObjC data structures generated by the front end.
306   if (v->hasSection() /* && isTargetDarwin */) {
307     // special case if this data blob is an ObjC class definition
308     if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
309       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
310         addObjCClass(gv);
311       }
312     }
313 
314     // special case if this data blob is an ObjC category definition
315     else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
316       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
317         addObjCCategory(gv);
318       }
319     }
320 
321     // special case if this data blob is the list of referenced classes
322     else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
323       if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
324         addObjCClassRef(gv);
325       }
326     }
327   }
328 }
329 
330 
addDefinedSymbol(GlobalValue * def,Mangler & mangler,bool isFunction)331 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
332                                  bool isFunction) {
333   // ignore all llvm.* symbols
334   if (def->getName().startswith("llvm."))
335     return;
336 
337   // string is owned by _defines
338   SmallString<64> Buffer;
339   mangler.getNameWithPrefix(Buffer, def, false);
340 
341   // set alignment part log2() can have rounding errors
342   uint32_t align = def->getAlignment();
343   uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
344 
345   // set permissions part
346   if (isFunction)
347     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
348   else {
349     GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
350     if (gv && gv->isConstant())
351       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
352     else
353       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
354   }
355 
356   // set definition part
357   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
358       def->hasLinkerPrivateWeakLinkage() ||
359       def->hasLinkerPrivateWeakDefAutoLinkage())
360     attr |= LTO_SYMBOL_DEFINITION_WEAK;
361   else if (def->hasCommonLinkage())
362     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
363   else
364     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
365 
366   // set scope part
367   if (def->hasHiddenVisibility())
368     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
369   else if (def->hasProtectedVisibility())
370     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
371   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
372            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
373            def->hasLinkerPrivateWeakLinkage())
374     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
375   else if (def->hasLinkerPrivateWeakDefAutoLinkage())
376     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
377   else
378     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
379 
380   // add to table of symbols
381   NameAndAttributes info;
382   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
383   entry.setValue(1);
384 
385   StringRef Name = entry.getKey();
386   info.name = Name.data();
387   assert(info.name[Name.size()] == '\0');
388   info.attributes = (lto_symbol_attributes)attr;
389   _symbols.push_back(info);
390 }
391 
addAsmGlobalSymbol(const char * name,lto_symbol_attributes scope)392 void LTOModule::addAsmGlobalSymbol(const char *name,
393                                    lto_symbol_attributes scope) {
394   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
395 
396   // only add new define if not already defined
397   if (entry.getValue())
398     return;
399 
400   entry.setValue(1);
401   const char *symbolName = entry.getKey().data();
402   uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
403   attr |= scope;
404   NameAndAttributes info;
405   info.name = symbolName;
406   info.attributes = (lto_symbol_attributes)attr;
407   _symbols.push_back(info);
408 }
409 
addAsmGlobalSymbolUndef(const char * name)410 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
411   StringMap<NameAndAttributes>::value_type &entry =
412     _undefines.GetOrCreateValue(name);
413 
414   _asm_undefines.push_back(entry.getKey().data());
415 
416   // we already have the symbol
417   if (entry.getValue().name)
418     return;
419 
420   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
421   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
422   NameAndAttributes info;
423   info.name = entry.getKey().data();
424   info.attributes = (lto_symbol_attributes)attr;
425 
426   entry.setValue(info);
427 }
428 
addPotentialUndefinedSymbol(GlobalValue * decl,Mangler & mangler)429 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
430                                             Mangler &mangler) {
431   // ignore all llvm.* symbols
432   if (decl->getName().startswith("llvm."))
433     return;
434 
435   // ignore all aliases
436   if (isa<GlobalAlias>(decl))
437     return;
438 
439   SmallString<64> name;
440   mangler.getNameWithPrefix(name, decl, false);
441 
442   StringMap<NameAndAttributes>::value_type &entry =
443     _undefines.GetOrCreateValue(name);
444 
445   // we already have the symbol
446   if (entry.getValue().name)
447     return;
448 
449   NameAndAttributes info;
450 
451   info.name = entry.getKey().data();
452   if (decl->hasExternalWeakLinkage())
453     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
454   else
455     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
456 
457   entry.setValue(info);
458 }
459 
460 
461 namespace {
462   class RecordStreamer : public MCStreamer {
463   public:
464     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
465 
466   private:
467     StringMap<State> Symbols;
468 
markDefined(const MCSymbol & Symbol)469     void markDefined(const MCSymbol &Symbol) {
470       State &S = Symbols[Symbol.getName()];
471       switch (S) {
472       case DefinedGlobal:
473       case Global:
474         S = DefinedGlobal;
475         break;
476       case NeverSeen:
477       case Defined:
478       case Used:
479         S = Defined;
480         break;
481       }
482     }
markGlobal(const MCSymbol & Symbol)483     void markGlobal(const MCSymbol &Symbol) {
484       State &S = Symbols[Symbol.getName()];
485       switch (S) {
486       case DefinedGlobal:
487       case Defined:
488         S = DefinedGlobal;
489         break;
490 
491       case NeverSeen:
492       case Global:
493       case Used:
494         S = Global;
495         break;
496       }
497     }
markUsed(const MCSymbol & Symbol)498     void markUsed(const MCSymbol &Symbol) {
499       State &S = Symbols[Symbol.getName()];
500       switch (S) {
501       case DefinedGlobal:
502       case Defined:
503       case Global:
504         break;
505 
506       case NeverSeen:
507       case Used:
508         S = Used;
509         break;
510       }
511     }
512 
513     // FIXME: mostly copied for the obj streamer.
AddValueSymbols(const MCExpr * Value)514     void AddValueSymbols(const MCExpr *Value) {
515       switch (Value->getKind()) {
516       case MCExpr::Target:
517         // FIXME: What should we do in here?
518         break;
519 
520       case MCExpr::Constant:
521         break;
522 
523       case MCExpr::Binary: {
524         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
525         AddValueSymbols(BE->getLHS());
526         AddValueSymbols(BE->getRHS());
527         break;
528       }
529 
530       case MCExpr::SymbolRef:
531         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
532         break;
533 
534       case MCExpr::Unary:
535         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
536         break;
537       }
538     }
539 
540   public:
541     typedef StringMap<State>::const_iterator const_iterator;
542 
begin()543     const_iterator begin() {
544       return Symbols.begin();
545     }
546 
end()547     const_iterator end() {
548       return Symbols.end();
549     }
550 
RecordStreamer(MCContext & Context)551     RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
552 
ChangeSection(const MCSection * Section)553     virtual void ChangeSection(const MCSection *Section) {}
InitSections()554     virtual void InitSections() {}
EmitLabel(MCSymbol * Symbol)555     virtual void EmitLabel(MCSymbol *Symbol) {
556       Symbol->setSection(*getCurrentSection());
557       markDefined(*Symbol);
558     }
EmitAssemblerFlag(MCAssemblerFlag Flag)559     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
EmitThumbFunc(MCSymbol * Func)560     virtual void EmitThumbFunc(MCSymbol *Func) {}
EmitAssignment(MCSymbol * Symbol,const MCExpr * Value)561     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
562       // FIXME: should we handle aliases?
563       markDefined(*Symbol);
564     }
EmitSymbolAttribute(MCSymbol * Symbol,MCSymbolAttr Attribute)565     virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
566       if (Attribute == MCSA_Global)
567         markGlobal(*Symbol);
568     }
EmitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)569     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
EmitWeakReference(MCSymbol * Alias,const MCSymbol * Symbol)570     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
BeginCOFFSymbolDef(const MCSymbol * Symbol)571     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
EmitCOFFSymbolStorageClass(int StorageClass)572     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
EmitZerofill(const MCSection * Section,MCSymbol * Symbol,unsigned Size,unsigned ByteAlignment)573     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
574                               unsigned Size , unsigned ByteAlignment) {
575       markDefined(*Symbol);
576     }
EmitCOFFSymbolType(int Type)577     virtual void EmitCOFFSymbolType(int Type) {}
EndCOFFSymbolDef()578     virtual void EndCOFFSymbolDef() {}
EmitCommonSymbol(MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)579     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
580                                   unsigned ByteAlignment) {
581       markDefined(*Symbol);
582     }
EmitELFSize(MCSymbol * Symbol,const MCExpr * Value)583     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
EmitLocalCommonSymbol(MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)584     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
585                                        unsigned ByteAlignment) {}
EmitTBSSSymbol(const MCSection * Section,MCSymbol * Symbol,uint64_t Size,unsigned ByteAlignment)586     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
587                                 uint64_t Size, unsigned ByteAlignment) {}
EmitBytes(StringRef Data,unsigned AddrSpace)588     virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
EmitValueImpl(const MCExpr * Value,unsigned Size,unsigned AddrSpace)589     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
590                                unsigned AddrSpace) {}
EmitULEB128Value(const MCExpr * Value)591     virtual void EmitULEB128Value(const MCExpr *Value) {}
EmitSLEB128Value(const MCExpr * Value)592     virtual void EmitSLEB128Value(const MCExpr *Value) {}
EmitValueToAlignment(unsigned ByteAlignment,int64_t Value,unsigned ValueSize,unsigned MaxBytesToEmit)593     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
594                                       unsigned ValueSize,
595                                       unsigned MaxBytesToEmit) {}
EmitCodeAlignment(unsigned ByteAlignment,unsigned MaxBytesToEmit)596     virtual void EmitCodeAlignment(unsigned ByteAlignment,
597                                    unsigned MaxBytesToEmit) {}
EmitValueToOffset(const MCExpr * Offset,unsigned char Value)598     virtual void EmitValueToOffset(const MCExpr *Offset,
599                                    unsigned char Value ) {}
EmitFileDirective(StringRef Filename)600     virtual void EmitFileDirective(StringRef Filename) {}
EmitDwarfAdvanceLineAddr(int64_t LineDelta,const MCSymbol * LastLabel,const MCSymbol * Label,unsigned PointerSize)601     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
602                                           const MCSymbol *LastLabel,
603                                           const MCSymbol *Label,
604                                           unsigned PointerSize) {}
605 
EmitInstruction(const MCInst & Inst)606     virtual void EmitInstruction(const MCInst &Inst) {
607       // Scan for values.
608       for (unsigned i = Inst.getNumOperands(); i--; )
609         if (Inst.getOperand(i).isExpr())
610           AddValueSymbols(Inst.getOperand(i).getExpr());
611     }
Finish()612     virtual void Finish() {}
613   };
614 }
615 
addAsmGlobalSymbols(MCContext & Context,std::string & errMsg)616 bool LTOModule::addAsmGlobalSymbols(MCContext &Context, std::string &errMsg) {
617   const std::string &inlineAsm = _module->getModuleInlineAsm();
618   if (inlineAsm.empty())
619     return false;
620 
621   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
622   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
623   SourceMgr SrcMgr;
624   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
625   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
626                                                   Context, *Streamer,
627                                                   *_target->getMCAsmInfo()));
628   OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
629                       createMCSubtargetInfo(_target->getTargetTriple(),
630                                             _target->getTargetCPU(),
631                                             _target->getTargetFeatureString()));
632   OwningPtr<MCTargetAsmParser>
633     TAP(_target->getTarget().createMCAsmParser(*STI, *Parser.get()));
634   if (!TAP) {
635     errMsg = "target " + std::string(_target->getTarget().getName()) +
636         " does not define AsmParser.";
637     return true;
638   }
639 
640   Parser->setTargetParser(*TAP);
641   int Res = Parser->Run(false);
642   if (Res)
643     return true;
644 
645   for (RecordStreamer::const_iterator i = Streamer->begin(),
646          e = Streamer->end(); i != e; ++i) {
647     StringRef Key = i->first();
648     RecordStreamer::State Value = i->second;
649     if (Value == RecordStreamer::DefinedGlobal)
650       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
651     else if (Value == RecordStreamer::Defined)
652       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
653     else if (Value == RecordStreamer::Global ||
654              Value == RecordStreamer::Used)
655       addAsmGlobalSymbolUndef(Key.data());
656   }
657   return false;
658 }
659 
isDeclaration(const GlobalValue & V)660 static bool isDeclaration(const GlobalValue &V) {
661   if (V.hasAvailableExternallyLinkage())
662     return true;
663   if (V.isMaterializable())
664     return false;
665   return V.isDeclaration();
666 }
667 
isAliasToDeclaration(const GlobalAlias & V)668 static bool isAliasToDeclaration(const GlobalAlias &V) {
669   return isDeclaration(*V.getAliasedGlobal());
670 }
671 
ParseSymbols(std::string & errMsg)672 bool LTOModule::ParseSymbols(std::string &errMsg) {
673   // Use mangler to add GlobalPrefix to names to match linker names.
674   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
675   Mangler mangler(Context, *_target->getTargetData());
676 
677   // add functions
678   for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
679     if (isDeclaration(*f))
680       addPotentialUndefinedSymbol(f, mangler);
681     else
682       addDefinedFunctionSymbol(f, mangler);
683   }
684 
685   // add data
686   for (Module::global_iterator v = _module->global_begin(),
687          e = _module->global_end(); v !=  e; ++v) {
688     if (isDeclaration(*v))
689       addPotentialUndefinedSymbol(v, mangler);
690     else
691       addDefinedDataSymbol(v, mangler);
692   }
693 
694   // add asm globals
695   if (addAsmGlobalSymbols(Context, errMsg))
696     return true;
697 
698   // add aliases
699   for (Module::alias_iterator i = _module->alias_begin(),
700          e = _module->alias_end(); i != e; ++i) {
701     if (isAliasToDeclaration(*i))
702       addPotentialUndefinedSymbol(i, mangler);
703     else
704       addDefinedDataSymbol(i, mangler);
705   }
706 
707   // make symbols for all undefines
708   for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
709        it != _undefines.end(); ++it) {
710     // if this symbol also has a definition, then don't make an undefine
711     // because it is a tentative definition
712     if (_defines.count(it->getKey()) == 0) {
713       NameAndAttributes info = it->getValue();
714       _symbols.push_back(info);
715     }
716   }
717   return false;
718 }
719 
720 
getSymbolCount()721 uint32_t LTOModule::getSymbolCount() {
722   return _symbols.size();
723 }
724 
725 
getSymbolAttributes(uint32_t index)726 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
727   if (index < _symbols.size())
728     return _symbols[index].attributes;
729   else
730     return lto_symbol_attributes(0);
731 }
732 
getSymbolName(uint32_t index)733 const char *LTOModule::getSymbolName(uint32_t index) {
734   if (index < _symbols.size())
735     return _symbols[index].name;
736   else
737     return NULL;
738 }
739