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