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