Fix PR18743.
[oota-llvm.git] / lib / 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 "llvm/LTO/LTOModule.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Transforms/Utils/GlobalStatus.h"
46 using namespace llvm;
47
48 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
49   : _module(m), _target(t),
50     _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), &ObjFileInfo),
51     _mangler(t->getDataLayout()) {
52   ObjFileInfo.InitMCObjectFileInfo(t->getTargetTriple(),
53                                    t->getRelocationModel(), t->getCodeModel(),
54                                    _context);
55 }
56
57 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
58 /// bitcode.
59 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
60   return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
61          sys::fs::file_magic::bitcode;
62 }
63
64 bool LTOModule::isBitcodeFile(const char *path) {
65   sys::fs::file_magic type;
66   if (sys::fs::identify_magic(path, type))
67     return false;
68   return type == sys::fs::file_magic::bitcode;
69 }
70
71 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
72 /// LLVM bitcode for the specified triple.
73 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
74                                        const char *triplePrefix) {
75   MemoryBuffer *buffer = makeBuffer(mem, length);
76   if (!buffer)
77     return false;
78   return isTargetMatch(buffer, triplePrefix);
79 }
80
81 bool LTOModule::isBitcodeFileForTarget(const char *path,
82                                        const char *triplePrefix) {
83   OwningPtr<MemoryBuffer> buffer;
84   if (MemoryBuffer::getFile(path, buffer))
85     return false;
86   return isTargetMatch(buffer.take(), triplePrefix);
87 }
88
89 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
90 /// target triple.
91 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
92   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
93   delete buffer;
94   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
95 }
96
97 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
98 /// the buffer.
99 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
100                                     std::string &errMsg) {
101   OwningPtr<MemoryBuffer> buffer;
102   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
103     errMsg = ec.message();
104     return NULL;
105   }
106   return makeLTOModule(buffer.take(), options, errMsg);
107 }
108
109 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
110                                     size_t size, TargetOptions options,
111                                     std::string &errMsg) {
112   return makeLTOModule(fd, path, size, 0, options, errMsg);
113 }
114
115 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
116                                     size_t map_size,
117                                     off_t offset,
118                                     TargetOptions options,
119                                     std::string &errMsg) {
120   OwningPtr<MemoryBuffer> buffer;
121   if (error_code ec =
122           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
123     errMsg = ec.message();
124     return NULL;
125   }
126   return makeLTOModule(buffer.take(), options, errMsg);
127 }
128
129 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
130                                     TargetOptions options,
131                                     std::string &errMsg, StringRef path) {
132   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
133   if (!buffer)
134     return NULL;
135   return makeLTOModule(buffer.take(), options, errMsg);
136 }
137
138 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
139                                     TargetOptions options,
140                                     std::string &errMsg) {
141   // parse bitcode buffer
142   ErrorOr<Module *> ModuleOrErr =
143       getLazyBitcodeModule(buffer, getGlobalContext());
144   if (error_code EC = ModuleOrErr.getError()) {
145     errMsg = EC.message();
146     delete buffer;
147     return NULL;
148   }
149   OwningPtr<Module> m(ModuleOrErr.get());
150
151   std::string TripleStr = m->getTargetTriple();
152   if (TripleStr.empty())
153     TripleStr = sys::getDefaultTargetTriple();
154   llvm::Triple Triple(TripleStr);
155
156   // find machine architecture for this module
157   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
158   if (!march)
159     return NULL;
160
161   // construct LTOModule, hand over ownership of module and target
162   SubtargetFeatures Features;
163   Features.getDefaultSubtargetFeatures(Triple);
164   std::string FeatureStr = Features.getString();
165   // Set a default CPU for Darwin triples.
166   std::string CPU;
167   if (Triple.isOSDarwin()) {
168     if (Triple.getArch() == llvm::Triple::x86_64)
169       CPU = "core2";
170     else if (Triple.getArch() == llvm::Triple::x86)
171       CPU = "yonah";
172   }
173
174   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
175                                                      options);
176   m->materializeAllPermanently();
177
178   LTOModule *Ret = new LTOModule(m.take(), target);
179   if (Ret->parseSymbols(errMsg)) {
180     delete Ret;
181     return NULL;
182   }
183
184   Ret->parseMetadata();
185
186   return Ret;
187 }
188
189 /// Create a MemoryBuffer from a memory range with an optional name.
190 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
191                                     StringRef name) {
192   const char *startPtr = (const char*)mem;
193   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
194 }
195
196 /// objcClassNameFromExpression - Get string that the data pointer points to.
197 bool
198 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
199   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
200     Constant *op = ce->getOperand(0);
201     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
202       Constant *cn = gvn->getInitializer();
203       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
204         if (ca->isCString()) {
205           name = ".objc_class_name_" + ca->getAsCString().str();
206           return true;
207         }
208       }
209     }
210   }
211   return false;
212 }
213
214 /// addObjCClass - Parse i386/ppc ObjC class data structure.
215 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
216   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
217   if (!c) return;
218
219   // second slot in __OBJC,__class is pointer to superclass name
220   std::string superclassName;
221   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
222     NameAndAttributes info;
223     StringMap<NameAndAttributes>::value_type &entry =
224       _undefines.GetOrCreateValue(superclassName);
225     if (!entry.getValue().name) {
226       const char *symbolName = entry.getKey().data();
227       info.name = symbolName;
228       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
229       info.isFunction = false;
230       info.symbol = clgv;
231       entry.setValue(info);
232     }
233   }
234
235   // third slot in __OBJC,__class is pointer to class name
236   std::string className;
237   if (objcClassNameFromExpression(c->getOperand(2), className)) {
238     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
239     entry.setValue(1);
240
241     NameAndAttributes info;
242     info.name = entry.getKey().data();
243     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
244       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
245     info.isFunction = false;
246     info.symbol = clgv;
247     _symbols.push_back(info);
248   }
249 }
250
251 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
252 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
253   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
254   if (!c) return;
255
256   // second slot in __OBJC,__category is pointer to target class name
257   std::string targetclassName;
258   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
259     return;
260
261   NameAndAttributes info;
262   StringMap<NameAndAttributes>::value_type &entry =
263     _undefines.GetOrCreateValue(targetclassName);
264
265   if (entry.getValue().name)
266     return;
267
268   const char *symbolName = entry.getKey().data();
269   info.name = symbolName;
270   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
271   info.isFunction = false;
272   info.symbol = clgv;
273   entry.setValue(info);
274 }
275
276 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
277 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
278   std::string targetclassName;
279   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
280     return;
281
282   NameAndAttributes info;
283   StringMap<NameAndAttributes>::value_type &entry =
284     _undefines.GetOrCreateValue(targetclassName);
285   if (entry.getValue().name)
286     return;
287
288   const char *symbolName = entry.getKey().data();
289   info.name = symbolName;
290   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
291   info.isFunction = false;
292   info.symbol = clgv;
293   entry.setValue(info);
294 }
295
296 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
297 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
298   // Add to list of defined symbols.
299   addDefinedSymbol(v, false);
300
301   if (!v->hasSection() /* || !isTargetDarwin */)
302     return;
303
304   // Special case i386/ppc ObjC data structures in magic sections:
305   // The issue is that the old ObjC object format did some strange
306   // contortions to avoid real linker symbols.  For instance, the
307   // ObjC class data structure is allocated statically in the executable
308   // that defines that class.  That data structures contains a pointer to
309   // its superclass.  But instead of just initializing that part of the
310   // struct to the address of its superclass, and letting the static and
311   // dynamic linkers do the rest, the runtime works by having that field
312   // instead point to a C-string that is the name of the superclass.
313   // At runtime the objc initialization updates that pointer and sets
314   // it to point to the actual super class.  As far as the linker
315   // knows it is just a pointer to a string.  But then someone wanted the
316   // linker to issue errors at build time if the superclass was not found.
317   // So they figured out a way in mach-o object format to use an absolute
318   // symbols (.objc_class_name_Foo = 0) and a floating reference
319   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
320   // a class was missing.
321   // The following synthesizes the implicit .objc_* symbols for the linker
322   // from the ObjC data structures generated by the front end.
323
324   // special case if this data blob is an ObjC class definition
325   if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
326     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
327       addObjCClass(gv);
328     }
329   }
330
331   // special case if this data blob is an ObjC category definition
332   else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
333     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
334       addObjCCategory(gv);
335     }
336   }
337
338   // special case if this data blob is the list of referenced classes
339   else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
340     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
341       addObjCClassRef(gv);
342     }
343   }
344 }
345
346 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
347 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
348   // add to list of defined symbols
349   addDefinedSymbol(f, true);
350 }
351
352 static bool canBeHidden(const GlobalValue *GV) {
353   // FIXME: this is duplicated with another static function in AsmPrinter.cpp
354   GlobalValue::LinkageTypes L = GV->getLinkage();
355
356   if (L != GlobalValue::LinkOnceODRLinkage)
357     return false;
358
359   if (GV->hasUnnamedAddr())
360     return true;
361
362   // If it is a non constant variable, it needs to be uniqued across shared
363   // objects.
364   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
365     if (!Var->isConstant())
366       return false;
367   }
368
369   GlobalStatus GS;
370   if (GlobalStatus::analyzeGlobal(GV, GS))
371     return false;
372
373   return !GS.IsCompared;
374 }
375
376 /// addDefinedSymbol - Add a defined symbol to the list.
377 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
378   // ignore all llvm.* symbols
379   if (def->getName().startswith("llvm."))
380     return;
381
382   // string is owned by _defines
383   SmallString<64> Buffer;
384   _target->getTargetLowering()->getNameWithPrefix(Buffer, def, _mangler);
385
386   // set alignment part log2() can have rounding errors
387   uint32_t align = def->getAlignment();
388   uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
389
390   // set permissions part
391   if (isFunction) {
392     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
393   } else {
394     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
395     if (gv && gv->isConstant())
396       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
397     else
398       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
399   }
400
401   // set definition part
402   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
403       def->hasLinkerPrivateWeakLinkage())
404     attr |= LTO_SYMBOL_DEFINITION_WEAK;
405   else if (def->hasCommonLinkage())
406     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
407   else
408     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
409
410   // set scope part
411   if (def->hasHiddenVisibility())
412     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
413   else if (def->hasProtectedVisibility())
414     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
415   else if (canBeHidden(def))
416     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
417   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
418            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
419            def->hasLinkerPrivateWeakLinkage())
420     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
421   else
422     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
423
424   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
425   entry.setValue(1);
426
427   // fill information structure
428   NameAndAttributes info;
429   StringRef Name = entry.getKey();
430   info.name = Name.data();
431   assert(info.name[Name.size()] == '\0');
432   info.attributes = attr;
433   info.isFunction = isFunction;
434   info.symbol = def;
435
436   // add to table of symbols
437   _symbols.push_back(info);
438 }
439
440 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
441 /// defined list.
442 void LTOModule::addAsmGlobalSymbol(const char *name,
443                                    lto_symbol_attributes scope) {
444   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
445
446   // only add new define if not already defined
447   if (entry.getValue())
448     return;
449
450   entry.setValue(1);
451
452   NameAndAttributes &info = _undefines[entry.getKey().data()];
453
454   if (info.symbol == 0) {
455     // FIXME: This is trying to take care of module ASM like this:
456     //
457     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
458     //
459     // but is gross and its mother dresses it funny. Have the ASM parser give us
460     // more details for this type of situation so that we're not guessing so
461     // much.
462
463     // fill information structure
464     info.name = entry.getKey().data();
465     info.attributes =
466       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
467     info.isFunction = false;
468     info.symbol = 0;
469
470     // add to table of symbols
471     _symbols.push_back(info);
472     return;
473   }
474
475   if (info.isFunction)
476     addDefinedFunctionSymbol(cast<Function>(info.symbol));
477   else
478     addDefinedDataSymbol(info.symbol);
479
480   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
481   _symbols.back().attributes |= scope;
482 }
483
484 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
485 /// undefined list.
486 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
487   StringMap<NameAndAttributes>::value_type &entry =
488     _undefines.GetOrCreateValue(name);
489
490   _asm_undefines.push_back(entry.getKey().data());
491
492   // we already have the symbol
493   if (entry.getValue().name)
494     return;
495
496   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
497   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
498   NameAndAttributes info;
499   info.name = entry.getKey().data();
500   info.attributes = attr;
501   info.isFunction = false;
502   info.symbol = 0;
503
504   entry.setValue(info);
505 }
506
507 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
508 /// list to be resolved later.
509 void
510 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
511   // ignore all llvm.* symbols
512   if (decl->getName().startswith("llvm."))
513     return;
514
515   // ignore all aliases
516   if (isa<GlobalAlias>(decl))
517     return;
518
519   SmallString<64> name;
520   _target->getTargetLowering()->getNameWithPrefix(name, decl, _mangler);
521
522   StringMap<NameAndAttributes>::value_type &entry =
523     _undefines.GetOrCreateValue(name);
524
525   // we already have the symbol
526   if (entry.getValue().name)
527     return;
528
529   NameAndAttributes info;
530
531   info.name = entry.getKey().data();
532
533   if (decl->hasExternalWeakLinkage())
534     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
535   else
536     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
537
538   info.isFunction = isFunc;
539   info.symbol = decl;
540
541   entry.setValue(info);
542 }
543
544 namespace {
545
546   class RecordStreamer : public MCStreamer {
547   public:
548     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
549
550   private:
551     StringMap<State> Symbols;
552
553     void markDefined(const MCSymbol &Symbol) {
554       State &S = Symbols[Symbol.getName()];
555       switch (S) {
556       case DefinedGlobal:
557       case Global:
558         S = DefinedGlobal;
559         break;
560       case NeverSeen:
561       case Defined:
562       case Used:
563         S = Defined;
564         break;
565       }
566     }
567     void markGlobal(const MCSymbol &Symbol) {
568       State &S = Symbols[Symbol.getName()];
569       switch (S) {
570       case DefinedGlobal:
571       case Defined:
572         S = DefinedGlobal;
573         break;
574
575       case NeverSeen:
576       case Global:
577       case Used:
578         S = Global;
579         break;
580       }
581     }
582     void markUsed(const MCSymbol &Symbol) {
583       State &S = Symbols[Symbol.getName()];
584       switch (S) {
585       case DefinedGlobal:
586       case Defined:
587       case Global:
588         break;
589
590       case NeverSeen:
591       case Used:
592         S = Used;
593         break;
594       }
595     }
596
597     // FIXME: mostly copied for the obj streamer.
598     void AddValueSymbols(const MCExpr *Value) {
599       switch (Value->getKind()) {
600       case MCExpr::Target:
601         // FIXME: What should we do in here?
602         break;
603
604       case MCExpr::Constant:
605         break;
606
607       case MCExpr::Binary: {
608         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
609         AddValueSymbols(BE->getLHS());
610         AddValueSymbols(BE->getRHS());
611         break;
612       }
613
614       case MCExpr::SymbolRef:
615         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
616         break;
617
618       case MCExpr::Unary:
619         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
620         break;
621       }
622     }
623
624   public:
625     typedef StringMap<State>::const_iterator const_iterator;
626
627     const_iterator begin() {
628       return Symbols.begin();
629     }
630
631     const_iterator end() {
632       return Symbols.end();
633     }
634
635     RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
636
637     virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) {
638       // Scan for values.
639       for (unsigned i = Inst.getNumOperands(); i--; )
640         if (Inst.getOperand(i).isExpr())
641           AddValueSymbols(Inst.getOperand(i).getExpr());
642     }
643     virtual void EmitLabel(MCSymbol *Symbol) {
644       Symbol->setSection(*getCurrentSection().first);
645       markDefined(*Symbol);
646     }
647     virtual void EmitDebugLabel(MCSymbol *Symbol) {
648       EmitLabel(Symbol);
649     }
650     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
651       // FIXME: should we handle aliases?
652       markDefined(*Symbol);
653     }
654     virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
655       if (Attribute == MCSA_Global)
656         markGlobal(*Symbol);
657       return true;
658     }
659     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
660                               uint64_t Size , unsigned ByteAlignment) {
661       markDefined(*Symbol);
662     }
663     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
664                                   unsigned ByteAlignment) {
665       markDefined(*Symbol);
666     }
667
668     virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
669     virtual void EmitBundleLock(bool AlignToEnd) {}
670     virtual void EmitBundleUnlock() {}
671
672     // Noop calls.
673     virtual void ChangeSection(const MCSection *Section,
674                                const MCExpr *Subsection) {}
675     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
676     virtual void EmitThumbFunc(MCSymbol *Func) {}
677     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
678     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
679     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
680     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
681     virtual void EmitCOFFSymbolType(int Type) {}
682     virtual void EndCOFFSymbolDef() {}
683     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
684     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
685                                        unsigned ByteAlignment) {}
686     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
687                                 uint64_t Size, unsigned ByteAlignment) {}
688     virtual void EmitBytes(StringRef Data) {}
689     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
690     virtual void EmitULEB128Value(const MCExpr *Value) {}
691     virtual void EmitSLEB128Value(const MCExpr *Value) {}
692     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
693                                       unsigned ValueSize,
694                                       unsigned MaxBytesToEmit) {}
695     virtual void EmitCodeAlignment(unsigned ByteAlignment,
696                                    unsigned MaxBytesToEmit) {}
697     virtual bool EmitValueToOffset(const MCExpr *Offset,
698                                    unsigned char Value ) { return false; }
699     virtual void EmitFileDirective(StringRef Filename) {}
700     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
701                                           const MCSymbol *LastLabel,
702                                           const MCSymbol *Label,
703                                           unsigned PointerSize) {}
704     virtual void FinishImpl() {}
705     virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
706       RecordProcEnd(Frame);
707     }
708   };
709 } // end anonymous namespace
710
711 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
712 /// defined or undefined lists.
713 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
714   const std::string &inlineAsm = _module->getModuleInlineAsm();
715   if (inlineAsm.empty())
716     return false;
717
718   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
719   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
720   SourceMgr SrcMgr;
721   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
722   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
723                                                   _context, *Streamer,
724                                                   *_target->getMCAsmInfo()));
725   const Target &T = _target->getTarget();
726   OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo());
727   OwningPtr<MCSubtargetInfo>
728     STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
729                                 _target->getTargetCPU(),
730                                 _target->getTargetFeatureString()));
731   OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
732   if (!TAP) {
733     errMsg = "target " + std::string(T.getName()) +
734       " does not define AsmParser.";
735     return true;
736   }
737
738   Parser->setTargetParser(*TAP);
739   if (Parser->Run(false))
740     return true;
741
742   for (RecordStreamer::const_iterator i = Streamer->begin(),
743          e = Streamer->end(); i != e; ++i) {
744     StringRef Key = i->first();
745     RecordStreamer::State Value = i->second;
746     if (Value == RecordStreamer::DefinedGlobal)
747       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
748     else if (Value == RecordStreamer::Defined)
749       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
750     else if (Value == RecordStreamer::Global ||
751              Value == RecordStreamer::Used)
752       addAsmGlobalSymbolUndef(Key.data());
753   }
754
755   return false;
756 }
757
758 /// isDeclaration - Return 'true' if the global value is a declaration.
759 static bool isDeclaration(const GlobalValue &V) {
760   if (V.hasAvailableExternallyLinkage())
761     return true;
762
763   if (V.isMaterializable())
764     return false;
765
766   return V.isDeclaration();
767 }
768
769 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
770 /// them to either the defined or undefined lists.
771 bool LTOModule::parseSymbols(std::string &errMsg) {
772   // add functions
773   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
774     if (isDeclaration(*f))
775       addPotentialUndefinedSymbol(f, true);
776     else
777       addDefinedFunctionSymbol(f);
778   }
779
780   // add data
781   for (Module::global_iterator v = _module->global_begin(),
782          e = _module->global_end(); v !=  e; ++v) {
783     if (isDeclaration(*v))
784       addPotentialUndefinedSymbol(v, false);
785     else
786       addDefinedDataSymbol(v);
787   }
788
789   // add asm globals
790   if (addAsmGlobalSymbols(errMsg))
791     return true;
792
793   // add aliases
794   for (Module::alias_iterator a = _module->alias_begin(),
795          e = _module->alias_end(); a != e; ++a) {
796     if (isDeclaration(*a->getAliasedGlobal()))
797       // Is an alias to a declaration.
798       addPotentialUndefinedSymbol(a, false);
799     else
800       addDefinedDataSymbol(a);
801   }
802
803   // make symbols for all undefines
804   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
805          e = _undefines.end(); u != e; ++u) {
806     // If this symbol also has a definition, then don't make an undefine because
807     // it is a tentative definition.
808     if (_defines.count(u->getKey())) continue;
809     NameAndAttributes info = u->getValue();
810     _symbols.push_back(info);
811   }
812
813   return false;
814 }
815
816 /// parseMetadata - Parse metadata from the module
817 void LTOModule::parseMetadata() {
818   // Linker Options
819   if (Value *Val = _module->getModuleFlag("Linker Options")) {
820     MDNode *LinkerOptions = cast<MDNode>(Val);
821     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
822       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
823       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
824         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
825         StringRef Op = _linkeropt_strings.
826             GetOrCreateValue(MDOption->getString()).getKey();
827         StringRef DepLibName = _target->getTargetLowering()->
828             getObjFileLowering().getDepLibFromLinkerOpt(Op);
829         if (!DepLibName.empty())
830           _deplibs.push_back(DepLibName.data());
831         else if (!Op.empty())
832           _linkeropts.push_back(Op.data());
833       }
834     }
835   }
836
837   // Add other interesting metadata here.
838 }