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