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