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