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/Analysis/ObjectUtils.h"
18 #include "llvm/Bitcode/BitcodeReader.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/FileSystem.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetLoweringObjectFile.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Target/TargetSubtargetInfo.h"
47 #include "llvm/Transforms/Utils/GlobalStatus.h"
48 #include <system_error>
49 using namespace llvm;
50 using namespace llvm::object;
51 
52 LTOModule::LTOModule(std::unique_ptr<Module> M, MemoryBufferRef MBRef,
53                      llvm::TargetMachine *TM)
54     : Mod(std::move(M)), MBRef(MBRef), _target(TM) {
55   SymTab.addModule(Mod.get());
56 }
57 
58 LTOModule::~LTOModule() {}
59 
60 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
61 /// bitcode.
62 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
63   Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
64       MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
65   if (!BCData) {
66     consumeError(BCData.takeError());
67     return false;
68   }
69   return true;
70 }
71 
72 bool LTOModule::isBitcodeFile(StringRef Path) {
73   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
74       MemoryBuffer::getFile(Path);
75   if (!BufferOrErr)
76     return false;
77 
78   Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
79       BufferOrErr.get()->getMemBufferRef());
80   if (!BCData) {
81     consumeError(BCData.takeError());
82     return false;
83   }
84   return true;
85 }
86 
87 bool LTOModule::isThinLTO() {
88   Expected<BitcodeLTOInfo> Result = getBitcodeLTOInfo(MBRef);
89   if (!Result) {
90     logAllUnhandledErrors(Result.takeError(), errs(), "");
91     return false;
92   }
93   return Result->IsThinLTO;
94 }
95 
96 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
97                                    StringRef TriplePrefix) {
98   Expected<MemoryBufferRef> BCOrErr =
99       IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
100   if (!BCOrErr) {
101     consumeError(BCOrErr.takeError());
102     return false;
103   }
104   LLVMContext Context;
105   ErrorOr<std::string> TripleOrErr =
106       expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(*BCOrErr));
107   if (!TripleOrErr)
108     return false;
109   return StringRef(*TripleOrErr).startswith(TriplePrefix);
110 }
111 
112 std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {
113   Expected<MemoryBufferRef> BCOrErr =
114       IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
115   if (!BCOrErr) {
116     consumeError(BCOrErr.takeError());
117     return "";
118   }
119   LLVMContext Context;
120   ErrorOr<std::string> ProducerOrErr = expectedToErrorOrAndEmitErrors(
121       Context, getBitcodeProducerString(*BCOrErr));
122   if (!ProducerOrErr)
123     return "";
124   return *ProducerOrErr;
125 }
126 
127 ErrorOr<std::unique_ptr<LTOModule>>
128 LTOModule::createFromFile(LLVMContext &Context, StringRef path,
129                           const TargetOptions &options) {
130   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
131       MemoryBuffer::getFile(path);
132   if (std::error_code EC = BufferOrErr.getError()) {
133     Context.emitError(EC.message());
134     return EC;
135   }
136   std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
137   return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
138                        /* ShouldBeLazy*/ false);
139 }
140 
141 ErrorOr<std::unique_ptr<LTOModule>>
142 LTOModule::createFromOpenFile(LLVMContext &Context, int fd, StringRef path,
143                               size_t size, const TargetOptions &options) {
144   return createFromOpenFileSlice(Context, fd, path, size, 0, options);
145 }
146 
147 ErrorOr<std::unique_ptr<LTOModule>>
148 LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path,
149                                    size_t map_size, off_t offset,
150                                    const TargetOptions &options) {
151   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
152       MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
153   if (std::error_code EC = BufferOrErr.getError()) {
154     Context.emitError(EC.message());
155     return EC;
156   }
157   std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
158   return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
159                        /* ShouldBeLazy */ false);
160 }
161 
162 ErrorOr<std::unique_ptr<LTOModule>>
163 LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,
164                             size_t length, const TargetOptions &options,
165                             StringRef path) {
166   StringRef Data((const char *)mem, length);
167   MemoryBufferRef Buffer(Data, path);
168   return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);
169 }
170 
171 ErrorOr<std::unique_ptr<LTOModule>>
172 LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,
173                                 const void *mem, size_t length,
174                                 const TargetOptions &options, StringRef path) {
175   StringRef Data((const char *)mem, length);
176   MemoryBufferRef Buffer(Data, path);
177   // If we own a context, we know this is being used only for symbol extraction,
178   // not linking.  Be lazy in that case.
179   ErrorOr<std::unique_ptr<LTOModule>> Ret =
180       makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);
181   if (Ret)
182     (*Ret)->OwnedContext = std::move(Context);
183   return Ret;
184 }
185 
186 static ErrorOr<std::unique_ptr<Module>>
187 parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context,
188                      bool ShouldBeLazy) {
189   // Find the buffer.
190   Expected<MemoryBufferRef> MBOrErr =
191       IRObjectFile::findBitcodeInMemBuffer(Buffer);
192   if (Error E = MBOrErr.takeError()) {
193     std::error_code EC = errorToErrorCode(std::move(E));
194     Context.emitError(EC.message());
195     return EC;
196   }
197 
198   if (!ShouldBeLazy) {
199     // Parse the full file.
200     return expectedToErrorOrAndEmitErrors(Context,
201                                           parseBitcodeFile(*MBOrErr, Context));
202   }
203 
204   // Parse lazily.
205   return expectedToErrorOrAndEmitErrors(
206       Context,
207       getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/));
208 }
209 
210 ErrorOr<std::unique_ptr<LTOModule>>
211 LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
212                          LLVMContext &Context, bool ShouldBeLazy) {
213   ErrorOr<std::unique_ptr<Module>> MOrErr =
214       parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);
215   if (std::error_code EC = MOrErr.getError())
216     return EC;
217   std::unique_ptr<Module> &M = *MOrErr;
218 
219   std::string TripleStr = M->getTargetTriple();
220   if (TripleStr.empty())
221     TripleStr = sys::getDefaultTargetTriple();
222   llvm::Triple Triple(TripleStr);
223 
224   // find machine architecture for this module
225   std::string errMsg;
226   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
227   if (!march)
228     return std::unique_ptr<LTOModule>(nullptr);
229 
230   // construct LTOModule, hand over ownership of module and target
231   SubtargetFeatures Features;
232   Features.getDefaultSubtargetFeatures(Triple);
233   std::string FeatureStr = Features.getString();
234   // Set a default CPU for Darwin triples.
235   std::string CPU;
236   if (Triple.isOSDarwin()) {
237     if (Triple.getArch() == llvm::Triple::x86_64)
238       CPU = "core2";
239     else if (Triple.getArch() == llvm::Triple::x86)
240       CPU = "yonah";
241     else if (Triple.getArch() == llvm::Triple::aarch64)
242       CPU = "cyclone";
243   }
244 
245   TargetMachine *target =
246       march->createTargetMachine(TripleStr, CPU, FeatureStr, options, None);
247 
248   std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));
249   Ret->parseSymbols();
250   Ret->parseMetadata();
251 
252   return std::move(Ret);
253 }
254 
255 /// Create a MemoryBuffer from a memory range with an optional name.
256 std::unique_ptr<MemoryBuffer>
257 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
258   const char *startPtr = (const char*)mem;
259   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
260 }
261 
262 /// objcClassNameFromExpression - Get string that the data pointer points to.
263 bool
264 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
265   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
266     Constant *op = ce->getOperand(0);
267     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
268       Constant *cn = gvn->getInitializer();
269       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
270         if (ca->isCString()) {
271           name = (".objc_class_name_" + ca->getAsCString()).str();
272           return true;
273         }
274       }
275     }
276   }
277   return false;
278 }
279 
280 /// addObjCClass - Parse i386/ppc ObjC class data structure.
281 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
282   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
283   if (!c) return;
284 
285   // second slot in __OBJC,__class is pointer to superclass name
286   std::string superclassName;
287   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
288     auto IterBool =
289         _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
290     if (IterBool.second) {
291       NameAndAttributes &info = IterBool.first->second;
292       info.name = IterBool.first->first();
293       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
294       info.isFunction = false;
295       info.symbol = clgv;
296     }
297   }
298 
299   // third slot in __OBJC,__class is pointer to class name
300   std::string className;
301   if (objcClassNameFromExpression(c->getOperand(2), className)) {
302     auto Iter = _defines.insert(className).first;
303 
304     NameAndAttributes info;
305     info.name = Iter->first();
306     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
307       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
308     info.isFunction = false;
309     info.symbol = clgv;
310     _symbols.push_back(info);
311   }
312 }
313 
314 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
315 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
316   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
317   if (!c) return;
318 
319   // second slot in __OBJC,__category is pointer to target class name
320   std::string targetclassName;
321   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
322     return;
323 
324   auto IterBool =
325       _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
326 
327   if (!IterBool.second)
328     return;
329 
330   NameAndAttributes &info = IterBool.first->second;
331   info.name = IterBool.first->first();
332   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
333   info.isFunction = false;
334   info.symbol = clgv;
335 }
336 
337 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
338 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
339   std::string targetclassName;
340   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
341     return;
342 
343   auto IterBool =
344       _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
345 
346   if (!IterBool.second)
347     return;
348 
349   NameAndAttributes &info = IterBool.first->second;
350   info.name = IterBool.first->first();
351   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
352   info.isFunction = false;
353   info.symbol = clgv;
354 }
355 
356 void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) {
357   SmallString<64> Buffer;
358   {
359     raw_svector_ostream OS(Buffer);
360     SymTab.printSymbolName(OS, Sym);
361     Buffer.c_str();
362   }
363 
364   const GlobalValue *V = Sym.get<GlobalValue *>();
365   addDefinedDataSymbol(Buffer, V);
366 }
367 
368 void LTOModule::addDefinedDataSymbol(StringRef 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(ModuleSymbolTable::Symbol Sym) {
419   SmallString<64> Buffer;
420   {
421     raw_svector_ostream OS(Buffer);
422     SymTab.printSymbolName(OS, Sym);
423     Buffer.c_str();
424   }
425 
426   const Function *F = cast<Function>(Sym.get<GlobalValue *>());
427   addDefinedFunctionSymbol(Buffer, F);
428 }
429 
430 void LTOModule::addDefinedFunctionSymbol(StringRef Name, const Function *F) {
431   // add to list of defined symbols
432   addDefinedSymbol(Name, F, true);
433 }
434 
435 void LTOModule::addDefinedSymbol(StringRef 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;
485   assert(NameRef.data()[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(StringRef 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()];
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();
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(StringRef name) {
539   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
540 
541   _asm_undefines.push_back(IterBool.first->first());
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();
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(ModuleSymbolTable::Symbol Sym,
558                                             bool isFunc) {
559   SmallString<64> name;
560   {
561     raw_svector_ostream OS(name);
562     SymTab.printSymbolName(OS, Sym);
563     name.c_str();
564   }
565 
566   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
567 
568   // we already have the symbol
569   if (!IterBool.second)
570     return;
571 
572   NameAndAttributes &info = IterBool.first->second;
573 
574   info.name = IterBool.first->first();
575 
576   const GlobalValue *decl = Sym.dyn_cast<GlobalValue *>();
577 
578   if (decl->hasExternalWeakLinkage())
579     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
580   else
581     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
582 
583   info.isFunction = isFunc;
584   info.symbol = decl;
585 }
586 
587 void LTOModule::parseSymbols() {
588   for (auto Sym : SymTab.symbols()) {
589     auto *GV = Sym.dyn_cast<GlobalValue *>();
590     uint32_t Flags = SymTab.getSymbolFlags(Sym);
591     if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
592       continue;
593 
594     bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
595 
596     if (!GV) {
597       SmallString<64> Buffer;
598       {
599         raw_svector_ostream OS(Buffer);
600         SymTab.printSymbolName(OS, Sym);
601         Buffer.c_str();
602       }
603       StringRef Name(Buffer);
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 
645 /// parseMetadata - Parse metadata from the module
646 void LTOModule::parseMetadata() {
647   raw_string_ostream OS(LinkerOpts);
648 
649   // Linker Options
650   if (NamedMDNode *LinkerOptions =
651           getModule().getNamedMetadata("llvm.linker.options")) {
652     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
653       MDNode *MDOptions = LinkerOptions->getOperand(i);
654       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
655         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
656         OS << " " << MDOption->getString();
657       }
658     }
659   }
660 
661   // Globals - we only need to do this for COFF.
662   const Triple TT(_target->getTargetTriple());
663   if (!TT.isOSBinFormatCOFF())
664     return;
665   Mangler M;
666   for (const NameAndAttributes &Sym : _symbols) {
667     if (!Sym.symbol)
668       continue;
669     emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
670   }
671 
672   // Add other interesting metadata here.
673 }
674