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