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