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