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