Remove access to the DataLayout in the TargetMachine
[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/CodeGen/Analysis.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/IRObjectFile.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 #include "llvm/Transforms/Utils/GlobalStatus.h"
49 #include <system_error>
50 using namespace llvm;
51 using namespace llvm::object;
52
53 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
54                      llvm::TargetMachine *TM)
55     : IRFile(std::move(Obj)), _target(TM) {}
56
57 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
58                      llvm::TargetMachine *TM,
59                      std::unique_ptr<LLVMContext> Context)
60     : OwnedContext(std::move(Context)), IRFile(std::move(Obj)), _target(TM) {}
61
62 LTOModule::~LTOModule() {}
63
64 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
65 /// bitcode.
66 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
67   ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
68       MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
69   return bool(BCData);
70 }
71
72 bool LTOModule::isBitcodeFile(const char *Path) {
73   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
74       MemoryBuffer::getFile(Path);
75   if (!BufferOrErr)
76     return false;
77
78   ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
79       BufferOrErr.get()->getMemBufferRef());
80   return bool(BCData);
81 }
82
83 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
84                                    StringRef TriplePrefix) {
85   ErrorOr<MemoryBufferRef> BCOrErr =
86       IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
87   if (!BCOrErr)
88     return false;
89   LLVMContext Context;
90   std::string Triple = getBitcodeTargetTriple(*BCOrErr, Context);
91   return StringRef(Triple).startswith(TriplePrefix);
92 }
93
94 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
95                                      std::string &errMsg) {
96   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
97       MemoryBuffer::getFile(path);
98   if (std::error_code EC = BufferOrErr.getError()) {
99     errMsg = EC.message();
100     return nullptr;
101   }
102   std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
103   return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
104                        &getGlobalContext());
105 }
106
107 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
108                                          TargetOptions options,
109                                          std::string &errMsg) {
110   return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
111 }
112
113 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
114                                               size_t map_size, off_t offset,
115                                               TargetOptions options,
116                                               std::string &errMsg) {
117   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
118       MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
119   if (std::error_code EC = BufferOrErr.getError()) {
120     errMsg = EC.message();
121     return nullptr;
122   }
123   std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
124   return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
125                        &getGlobalContext());
126 }
127
128 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
129                                        TargetOptions options,
130                                        std::string &errMsg, StringRef path) {
131   return createInContext(mem, length, options, errMsg, path,
132                          &getGlobalContext());
133 }
134
135 LTOModule *LTOModule::createInLocalContext(const void *mem, size_t length,
136                                            TargetOptions options,
137                                            std::string &errMsg,
138                                            StringRef path) {
139   return createInContext(mem, length, options, errMsg, path, nullptr);
140 }
141
142 LTOModule *LTOModule::createInContext(const void *mem, size_t length,
143                                       TargetOptions options,
144                                       std::string &errMsg, StringRef path,
145                                       LLVMContext *Context) {
146   StringRef Data((const char *)mem, length);
147   MemoryBufferRef Buffer(Data, path);
148   return makeLTOModule(Buffer, options, errMsg, Context);
149 }
150
151 static std::unique_ptr<Module> parseBitcodeFileImpl(MemoryBufferRef Buffer,
152                                                     LLVMContext &Context,
153                                                     bool ShouldBeLazy,
154                                                     std::string &ErrMsg) {
155
156   // Find the buffer.
157   ErrorOr<MemoryBufferRef> MBOrErr =
158       IRObjectFile::findBitcodeInMemBuffer(Buffer);
159   if (std::error_code EC = MBOrErr.getError()) {
160     ErrMsg = EC.message();
161     return nullptr;
162   }
163
164   std::function<void(const DiagnosticInfo &)> DiagnosticHandler =
165       [&ErrMsg](const DiagnosticInfo &DI) {
166         raw_string_ostream Stream(ErrMsg);
167         DiagnosticPrinterRawOStream DP(Stream);
168         DI.print(DP);
169       };
170
171   if (!ShouldBeLazy) {
172     // Parse the full file.
173     ErrorOr<std::unique_ptr<Module>> M =
174         parseBitcodeFile(*MBOrErr, Context, DiagnosticHandler);
175     if (!M)
176       return nullptr;
177     return std::move(*M);
178   }
179
180   // Parse lazily.
181   std::unique_ptr<MemoryBuffer> LightweightBuf =
182       MemoryBuffer::getMemBuffer(*MBOrErr, false);
183   ErrorOr<std::unique_ptr<Module>> M =
184       getLazyBitcodeModule(std::move(LightweightBuf), Context,
185                            DiagnosticHandler, true /*ShouldLazyLoadMetadata*/);
186   if (!M)
187     return nullptr;
188   return std::move(*M);
189 }
190
191 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
192                                     TargetOptions options, std::string &errMsg,
193                                     LLVMContext *Context) {
194   std::unique_ptr<LLVMContext> OwnedContext;
195   if (!Context) {
196     OwnedContext = llvm::make_unique<LLVMContext>();
197     Context = OwnedContext.get();
198   }
199
200   // If we own a context, we know this is being used only for symbol
201   // extraction, not linking.  Be lazy in that case.
202   std::unique_ptr<Module> M = parseBitcodeFileImpl(
203       Buffer, *Context,
204       /* ShouldBeLazy */ static_cast<bool>(OwnedContext), errMsg);
205   if (!M)
206     return nullptr;
207
208   std::string TripleStr = M->getTargetTriple();
209   if (TripleStr.empty())
210     TripleStr = sys::getDefaultTargetTriple();
211   llvm::Triple Triple(TripleStr);
212
213   // find machine architecture for this module
214   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
215   if (!march)
216     return nullptr;
217
218   // construct LTOModule, hand over ownership of module and target
219   SubtargetFeatures Features;
220   Features.getDefaultSubtargetFeatures(Triple);
221   std::string FeatureStr = Features.getString();
222   // Set a default CPU for Darwin triples.
223   std::string CPU;
224   if (Triple.isOSDarwin()) {
225     if (Triple.getArch() == llvm::Triple::x86_64)
226       CPU = "core2";
227     else if (Triple.getArch() == llvm::Triple::x86)
228       CPU = "yonah";
229     else if (Triple.getArch() == llvm::Triple::aarch64)
230       CPU = "cyclone";
231   }
232
233   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
234                                                      options);
235   M->setDataLayout(target->createDataLayout());
236
237   std::unique_ptr<object::IRObjectFile> IRObj(
238       new object::IRObjectFile(Buffer, std::move(M)));
239
240   LTOModule *Ret;
241   if (OwnedContext)
242     Ret = new LTOModule(std::move(IRObj), target, std::move(OwnedContext));
243   else
244     Ret = new LTOModule(std::move(IRObj), target);
245
246   if (Ret->parseSymbols(errMsg)) {
247     delete Ret;
248     return nullptr;
249   }
250
251   Ret->parseMetadata();
252
253   return Ret;
254 }
255
256 /// Create a MemoryBuffer from a memory range with an optional name.
257 std::unique_ptr<MemoryBuffer>
258 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
259   const char *startPtr = (const char*)mem;
260   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
261 }
262
263 /// objcClassNameFromExpression - Get string that the data pointer points to.
264 bool
265 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
266   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
267     Constant *op = ce->getOperand(0);
268     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
269       Constant *cn = gvn->getInitializer();
270       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
271         if (ca->isCString()) {
272           name = (".objc_class_name_" + ca->getAsCString()).str();
273           return true;
274         }
275       }
276     }
277   }
278   return false;
279 }
280
281 /// addObjCClass - Parse i386/ppc ObjC class data structure.
282 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
283   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
284   if (!c) return;
285
286   // second slot in __OBJC,__class is pointer to superclass name
287   std::string superclassName;
288   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
289     auto IterBool =
290         _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
291     if (IterBool.second) {
292       NameAndAttributes &info = IterBool.first->second;
293       info.name = IterBool.first->first().data();
294       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
295       info.isFunction = false;
296       info.symbol = clgv;
297     }
298   }
299
300   // third slot in __OBJC,__class is pointer to class name
301   std::string className;
302   if (objcClassNameFromExpression(c->getOperand(2), className)) {
303     auto Iter = _defines.insert(className).first;
304
305     NameAndAttributes info;
306     info.name = Iter->first().data();
307     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
308       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
309     info.isFunction = false;
310     info.symbol = clgv;
311     _symbols.push_back(info);
312   }
313 }
314
315 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
316 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
317   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
318   if (!c) return;
319
320   // second slot in __OBJC,__category is pointer to target class name
321   std::string targetclassName;
322   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
323     return;
324
325   auto IterBool =
326       _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
327
328   if (!IterBool.second)
329     return;
330
331   NameAndAttributes &info = IterBool.first->second;
332   info.name = IterBool.first->first().data();
333   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
334   info.isFunction = false;
335   info.symbol = clgv;
336 }
337
338 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
339 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
340   std::string targetclassName;
341   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
342     return;
343
344   auto IterBool =
345       _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
346
347   if (!IterBool.second)
348     return;
349
350   NameAndAttributes &info = IterBool.first->second;
351   info.name = IterBool.first->first().data();
352   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
353   info.isFunction = false;
354   info.symbol = clgv;
355 }
356
357 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
358   SmallString<64> Buffer;
359   {
360     raw_svector_ostream OS(Buffer);
361     Sym.printName(OS);
362   }
363
364   const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
365   addDefinedDataSymbol(Buffer.c_str(), V);
366 }
367
368 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
369   // Add to list of defined symbols.
370   addDefinedSymbol(Name, v, false);
371
372   if (!v->hasSection() /* || !isTargetDarwin */)
373     return;
374
375   // Special case i386/ppc ObjC data structures in magic sections:
376   // The issue is that the old ObjC object format did some strange
377   // contortions to avoid real linker symbols.  For instance, the
378   // ObjC class data structure is allocated statically in the executable
379   // that defines that class.  That data structures contains a pointer to
380   // its superclass.  But instead of just initializing that part of the
381   // struct to the address of its superclass, and letting the static and
382   // dynamic linkers do the rest, the runtime works by having that field
383   // instead point to a C-string that is the name of the superclass.
384   // At runtime the objc initialization updates that pointer and sets
385   // it to point to the actual super class.  As far as the linker
386   // knows it is just a pointer to a string.  But then someone wanted the
387   // linker to issue errors at build time if the superclass was not found.
388   // So they figured out a way in mach-o object format to use an absolute
389   // symbols (.objc_class_name_Foo = 0) and a floating reference
390   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
391   // a class was missing.
392   // The following synthesizes the implicit .objc_* symbols for the linker
393   // from the ObjC data structures generated by the front end.
394
395   // special case if this data blob is an ObjC class definition
396   std::string Section = v->getSection();
397   if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
398     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
399       addObjCClass(gv);
400     }
401   }
402
403   // special case if this data blob is an ObjC category definition
404   else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
405     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
406       addObjCCategory(gv);
407     }
408   }
409
410   // special case if this data blob is the list of referenced classes
411   else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
412     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
413       addObjCClassRef(gv);
414     }
415   }
416 }
417
418 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
419   SmallString<64> Buffer;
420   {
421     raw_svector_ostream OS(Buffer);
422     Sym.printName(OS);
423   }
424
425   const Function *F =
426       cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
427   addDefinedFunctionSymbol(Buffer.c_str(), F);
428 }
429
430 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
431   // add to list of defined symbols
432   addDefinedSymbol(Name, F, true);
433 }
434
435 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
436                                  bool isFunction) {
437   // set alignment part log2() can have rounding errors
438   uint32_t align = def->getAlignment();
439   uint32_t attr = align ? countTrailingZeros(align) : 0;
440
441   // set permissions part
442   if (isFunction) {
443     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
444   } else {
445     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
446     if (gv && gv->isConstant())
447       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
448     else
449       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
450   }
451
452   // set definition part
453   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
454     attr |= LTO_SYMBOL_DEFINITION_WEAK;
455   else if (def->hasCommonLinkage())
456     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
457   else
458     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
459
460   // set scope part
461   if (def->hasLocalLinkage())
462     // Ignore visibility if linkage is local.
463     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
464   else if (def->hasHiddenVisibility())
465     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
466   else if (def->hasProtectedVisibility())
467     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
468   else if (canBeOmittedFromSymbolTable(def))
469     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
470   else
471     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
472
473   if (def->hasComdat())
474     attr |= LTO_SYMBOL_COMDAT;
475
476   if (isa<GlobalAlias>(def))
477     attr |= LTO_SYMBOL_ALIAS;
478
479   auto Iter = _defines.insert(Name).first;
480
481   // fill information structure
482   NameAndAttributes info;
483   StringRef NameRef = Iter->first();
484   info.name = NameRef.data();
485   assert(info.name[NameRef.size()] == '\0');
486   info.attributes = attr;
487   info.isFunction = isFunction;
488   info.symbol = def;
489
490   // add to table of symbols
491   _symbols.push_back(info);
492 }
493
494 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
495 /// defined list.
496 void LTOModule::addAsmGlobalSymbol(const char *name,
497                                    lto_symbol_attributes scope) {
498   auto IterBool = _defines.insert(name);
499
500   // only add new define if not already defined
501   if (!IterBool.second)
502     return;
503
504   NameAndAttributes &info = _undefines[IterBool.first->first().data()];
505
506   if (info.symbol == nullptr) {
507     // FIXME: This is trying to take care of module ASM like this:
508     //
509     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
510     //
511     // but is gross and its mother dresses it funny. Have the ASM parser give us
512     // more details for this type of situation so that we're not guessing so
513     // much.
514
515     // fill information structure
516     info.name = IterBool.first->first().data();
517     info.attributes =
518       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
519     info.isFunction = false;
520     info.symbol = nullptr;
521
522     // add to table of symbols
523     _symbols.push_back(info);
524     return;
525   }
526
527   if (info.isFunction)
528     addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
529   else
530     addDefinedDataSymbol(info.name, info.symbol);
531
532   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
533   _symbols.back().attributes |= scope;
534 }
535
536 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
537 /// undefined list.
538 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
539   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
540
541   _asm_undefines.push_back(IterBool.first->first().data());
542
543   // we already have the symbol
544   if (!IterBool.second)
545     return;
546
547   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
548   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
549   NameAndAttributes &info = IterBool.first->second;
550   info.name = IterBool.first->first().data();
551   info.attributes = attr;
552   info.isFunction = false;
553   info.symbol = nullptr;
554 }
555
556 /// Add a symbol which isn't defined just yet to a list to be resolved later.
557 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
558                                             bool isFunc) {
559   SmallString<64> name;
560   {
561     raw_svector_ostream OS(name);
562     Sym.printName(OS);
563   }
564
565   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
566
567   // we already have the symbol
568   if (!IterBool.second)
569     return;
570
571   NameAndAttributes &info = IterBool.first->second;
572
573   info.name = IterBool.first->first().data();
574
575   const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
576
577   if (decl->hasExternalWeakLinkage())
578     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
579   else
580     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
581
582   info.isFunction = isFunc;
583   info.symbol = decl;
584 }
585
586 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
587 /// them to either the defined or undefined lists.
588 bool LTOModule::parseSymbols(std::string &errMsg) {
589   for (auto &Sym : IRFile->symbols()) {
590     const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
591     uint32_t Flags = Sym.getFlags();
592     if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
593       continue;
594
595     bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
596
597     if (!GV) {
598       SmallString<64> Buffer;
599       {
600         raw_svector_ostream OS(Buffer);
601         Sym.printName(OS);
602       }
603       const char *Name = Buffer.c_str();
604
605       if (IsUndefined)
606         addAsmGlobalSymbolUndef(Name);
607       else if (Flags & object::BasicSymbolRef::SF_Global)
608         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
609       else
610         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
611       continue;
612     }
613
614     auto *F = dyn_cast<Function>(GV);
615     if (IsUndefined) {
616       addPotentialUndefinedSymbol(Sym, F != nullptr);
617       continue;
618     }
619
620     if (F) {
621       addDefinedFunctionSymbol(Sym);
622       continue;
623     }
624
625     if (isa<GlobalVariable>(GV)) {
626       addDefinedDataSymbol(Sym);
627       continue;
628     }
629
630     assert(isa<GlobalAlias>(GV));
631     addDefinedDataSymbol(Sym);
632   }
633
634   // make symbols for all undefines
635   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
636          e = _undefines.end(); u != e; ++u) {
637     // If this symbol also has a definition, then don't make an undefine because
638     // it is a tentative definition.
639     if (_defines.count(u->getKey())) continue;
640     NameAndAttributes info = u->getValue();
641     _symbols.push_back(info);
642   }
643
644   return false;
645 }
646
647 /// parseMetadata - Parse metadata from the module
648 void LTOModule::parseMetadata() {
649   raw_string_ostream OS(LinkerOpts);
650
651   // Linker Options
652   if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
653     MDNode *LinkerOptions = cast<MDNode>(Val);
654     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
655       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
656       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
657         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
658         OS << " " << MDOption->getString();
659       }
660     }
661   }
662
663   // Globals
664   Mangler Mang;
665   for (const NameAndAttributes &Sym : _symbols) {
666     if (!Sym.symbol)
667       continue;
668     _target->getObjFileLowering()->emitLinkerFlagsForGlobal(OS, Sym.symbol,
669                                                             Mang);
670   }
671
672   // Add other interesting metadata here.
673 }