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