Combine all MC initialization routines into one. e.g. InitializeX86MCAsmInfo,
[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/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Target/TargetSelect.h"
46
47 using namespace llvm;
48
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
54 bool LTOModule::isBitcodeFile(const char *path) {
55   return llvm::sys::Path(path).isBitcodeFile();
56 }
57
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
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.
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
84 LTOModule::LTOModule(Module *m, TargetMachine *t)
85   : _module(m), _target(t)
86 {
87 }
88
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
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
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.
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
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
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();
169   if (Err) {
170     delete Ret;
171     return NULL;
172   }
173   return Ret;
174 }
175
176
177 const char *LTOModule::getTargetTriple() {
178   return _module->getTargetTriple().c_str();
179 }
180
181 void LTOModule::setTargetTriple(const char *triple) {
182   _module->setTargetTriple(triple);
183 }
184
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.
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.
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.
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.
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
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
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
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
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
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
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     }
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     }
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.
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
543     const_iterator begin() {
544       return Symbols.begin();
545     }
546
547     const_iterator end() {
548       return Symbols.end();
549     }
550
551     RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
552
553     virtual void ChangeSection(const MCSection *Section) {}
554     virtual void InitSections() {}
555     virtual void EmitLabel(MCSymbol *Symbol) {
556       Symbol->setSection(*getCurrentSection());
557       markDefined(*Symbol);
558     }
559     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
560     virtual void EmitThumbFunc(MCSymbol *Func) {}
561     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
562       // FIXME: should we handle aliases?
563       markDefined(*Symbol);
564     }
565     virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
566       if (Attribute == MCSA_Global)
567         markGlobal(*Symbol);
568     }
569     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
570     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
571     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
572     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
573     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
574                               unsigned Size , unsigned ByteAlignment) {
575       markDefined(*Symbol);
576     }
577     virtual void EmitCOFFSymbolType(int Type) {}
578     virtual void EndCOFFSymbolDef() {}
579     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
580                                   unsigned ByteAlignment) {
581       markDefined(*Symbol);
582     }
583     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
584     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
585     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
586                                 uint64_t Size, unsigned ByteAlignment) {}
587     virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
588     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
589                                unsigned AddrSpace) {}
590     virtual void EmitULEB128Value(const MCExpr *Value) {}
591     virtual void EmitSLEB128Value(const MCExpr *Value) {}
592     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
593                                       unsigned ValueSize,
594                                       unsigned MaxBytesToEmit) {}
595     virtual void EmitCodeAlignment(unsigned ByteAlignment,
596                                    unsigned MaxBytesToEmit) {}
597     virtual void EmitValueToOffset(const MCExpr *Offset,
598                                    unsigned char Value ) {}
599     virtual void EmitFileDirective(StringRef Filename) {}
600     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
601                                           const MCSymbol *LastLabel,
602                                           const MCSymbol *Label,
603                                           unsigned PointerSize) {}
604
605     virtual void EmitInstruction(const MCInst &Inst) {
606       // Scan for values.
607       for (unsigned i = Inst.getNumOperands(); i--; )
608         if (Inst.getOperand(i).isExpr())
609           AddValueSymbols(Inst.getOperand(i).getExpr());
610     }
611     virtual void Finish() {}
612   };
613 }
614
615 bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
616   const std::string &inlineAsm = _module->getModuleInlineAsm();
617
618   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
619   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
620   SourceMgr SrcMgr;
621   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
622   OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
623                                                   Context, *Streamer,
624                                                   *_target->getMCAsmInfo()));
625   OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
626                       createMCSubtargetInfo(_target->getTargetTriple(),
627                                             _target->getTargetCPU(),
628                                             _target->getTargetFeatureString()));
629   OwningPtr<TargetAsmParser>
630     TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
631   Parser->setTargetParser(*TAP);
632   int Res = Parser->Run(false);
633   if (Res)
634     return true;
635
636   for (RecordStreamer::const_iterator i = Streamer->begin(),
637          e = Streamer->end(); i != e; ++i) {
638     StringRef Key = i->first();
639     RecordStreamer::State Value = i->second;
640     if (Value == RecordStreamer::DefinedGlobal)
641       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
642     else if (Value == RecordStreamer::Defined)
643       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
644     else if (Value == RecordStreamer::Global ||
645              Value == RecordStreamer::Used)
646       addAsmGlobalSymbolUndef(Key.data());
647   }
648   return false;
649 }
650
651 static bool isDeclaration(const GlobalValue &V) {
652   if (V.hasAvailableExternallyLinkage())
653     return true;
654   if (V.isMaterializable())
655     return false;
656   return V.isDeclaration();
657 }
658
659 static bool isAliasToDeclaration(const GlobalAlias &V) {
660   return isDeclaration(*V.getAliasedGlobal());
661 }
662
663 bool LTOModule::ParseSymbols() {
664   // Use mangler to add GlobalPrefix to names to match linker names.
665   MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
666   Mangler mangler(Context, *_target->getTargetData());
667
668   // add functions
669   for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
670     if (isDeclaration(*f))
671       addPotentialUndefinedSymbol(f, mangler);
672     else
673       addDefinedFunctionSymbol(f, mangler);
674   }
675
676   // add data
677   for (Module::global_iterator v = _module->global_begin(),
678          e = _module->global_end(); v !=  e; ++v) {
679     if (isDeclaration(*v))
680       addPotentialUndefinedSymbol(v, mangler);
681     else
682       addDefinedDataSymbol(v, mangler);
683   }
684
685   // add asm globals
686   if (addAsmGlobalSymbols(Context))
687     return true;
688
689   // add aliases
690   for (Module::alias_iterator i = _module->alias_begin(),
691          e = _module->alias_end(); i != e; ++i) {
692     if (isAliasToDeclaration(*i))
693       addPotentialUndefinedSymbol(i, mangler);
694     else
695       addDefinedDataSymbol(i, mangler);
696   }
697
698   // make symbols for all undefines
699   for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
700        it != _undefines.end(); ++it) {
701     // if this symbol also has a definition, then don't make an undefine
702     // because it is a tentative definition
703     if (_defines.count(it->getKey()) == 0) {
704       NameAndAttributes info = it->getValue();
705       _symbols.push_back(info);
706     }
707   }
708   return false;
709 }
710
711
712 uint32_t LTOModule::getSymbolCount() {
713   return _symbols.size();
714 }
715
716
717 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
718   if (index < _symbols.size())
719     return _symbols[index].attributes;
720   else
721     return lto_symbol_attributes(0);
722 }
723
724 const char *LTOModule::getSymbolName(uint32_t index) {
725   if (index < _symbols.size())
726     return _symbols[index].name;
727   else
728     return NULL;
729 }