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