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   // set alignment part log2() can have rounding errors
418   uint32_t align = def->getAlignment();
419   uint32_t attr = align ? countTrailingZeros(align) : 0;
420 
421   // set permissions part
422   if (isFunction) {
423     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
424   } else {
425     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
426     if (gv && gv->isConstant())
427       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
428     else
429       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
430   }
431 
432   // set definition part
433   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
434     attr |= LTO_SYMBOL_DEFINITION_WEAK;
435   else if (def->hasCommonLinkage())
436     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
437   else
438     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
439 
440   // set scope part
441   if (def->hasLocalLinkage())
442     // Ignore visibility if linkage is local.
443     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
444   else if (def->hasHiddenVisibility())
445     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
446   else if (def->hasProtectedVisibility())
447     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
448   else if (def->canBeOmittedFromSymbolTable())
449     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
450   else
451     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
452 
453   if (def->hasComdat())
454     attr |= LTO_SYMBOL_COMDAT;
455 
456   if (isa<GlobalAlias>(def))
457     attr |= LTO_SYMBOL_ALIAS;
458 
459   auto Iter = _defines.insert(Name).first;
460 
461   // fill information structure
462   NameAndAttributes info;
463   StringRef NameRef = Iter->first();
464   info.name = NameRef;
465   assert(NameRef.data()[NameRef.size()] == '\0');
466   info.attributes = attr;
467   info.isFunction = isFunction;
468   info.symbol = def;
469 
470   // add to table of symbols
471   _symbols.push_back(info);
472 }
473 
474 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
475 /// defined list.
476 void LTOModule::addAsmGlobalSymbol(StringRef name,
477                                    lto_symbol_attributes scope) {
478   auto IterBool = _defines.insert(name);
479 
480   // only add new define if not already defined
481   if (!IterBool.second)
482     return;
483 
484   NameAndAttributes &info = _undefines[IterBool.first->first()];
485 
486   if (info.symbol == nullptr) {
487     // FIXME: This is trying to take care of module ASM like this:
488     //
489     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
490     //
491     // but is gross and its mother dresses it funny. Have the ASM parser give us
492     // more details for this type of situation so that we're not guessing so
493     // much.
494 
495     // fill information structure
496     info.name = IterBool.first->first();
497     info.attributes =
498       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
499     info.isFunction = false;
500     info.symbol = nullptr;
501 
502     // add to table of symbols
503     _symbols.push_back(info);
504     return;
505   }
506 
507   if (info.isFunction)
508     addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
509   else
510     addDefinedDataSymbol(info.name, info.symbol);
511 
512   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
513   _symbols.back().attributes |= scope;
514 }
515 
516 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
517 /// undefined list.
518 void LTOModule::addAsmGlobalSymbolUndef(StringRef name) {
519   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
520 
521   _asm_undefines.push_back(IterBool.first->first());
522 
523   // we already have the symbol
524   if (!IterBool.second)
525     return;
526 
527   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
528   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
529   NameAndAttributes &info = IterBool.first->second;
530   info.name = IterBool.first->first();
531   info.attributes = attr;
532   info.isFunction = false;
533   info.symbol = nullptr;
534 }
535 
536 /// Add a symbol which isn't defined just yet to a list to be resolved later.
537 void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym,
538                                             bool isFunc) {
539   SmallString<64> name;
540   {
541     raw_svector_ostream OS(name);
542     SymTab.printSymbolName(OS, Sym);
543     name.c_str();
544   }
545 
546   auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
547 
548   // we already have the symbol
549   if (!IterBool.second)
550     return;
551 
552   NameAndAttributes &info = IterBool.first->second;
553 
554   info.name = IterBool.first->first();
555 
556   const GlobalValue *decl = Sym.dyn_cast<GlobalValue *>();
557 
558   if (decl->hasExternalWeakLinkage())
559     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
560   else
561     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
562 
563   info.isFunction = isFunc;
564   info.symbol = decl;
565 }
566 
567 void LTOModule::parseSymbols() {
568   for (auto Sym : SymTab.symbols()) {
569     auto *GV = Sym.dyn_cast<GlobalValue *>();
570     uint32_t Flags = SymTab.getSymbolFlags(Sym);
571     if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
572       continue;
573 
574     bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
575 
576     if (!GV) {
577       SmallString<64> Buffer;
578       {
579         raw_svector_ostream OS(Buffer);
580         SymTab.printSymbolName(OS, Sym);
581         Buffer.c_str();
582       }
583       StringRef Name(Buffer);
584 
585       if (IsUndefined)
586         addAsmGlobalSymbolUndef(Name);
587       else if (Flags & object::BasicSymbolRef::SF_Global)
588         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
589       else
590         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
591       continue;
592     }
593 
594     auto *F = dyn_cast<Function>(GV);
595     if (IsUndefined) {
596       addPotentialUndefinedSymbol(Sym, F != nullptr);
597       continue;
598     }
599 
600     if (F) {
601       addDefinedFunctionSymbol(Sym);
602       continue;
603     }
604 
605     if (isa<GlobalVariable>(GV)) {
606       addDefinedDataSymbol(Sym);
607       continue;
608     }
609 
610     assert(isa<GlobalAlias>(GV));
611     addDefinedDataSymbol(Sym);
612   }
613 
614   // make symbols for all undefines
615   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
616          e = _undefines.end(); u != e; ++u) {
617     // If this symbol also has a definition, then don't make an undefine because
618     // it is a tentative definition.
619     if (_defines.count(u->getKey())) continue;
620     NameAndAttributes info = u->getValue();
621     _symbols.push_back(info);
622   }
623 }
624 
625 /// parseMetadata - Parse metadata from the module
626 void LTOModule::parseMetadata() {
627   raw_string_ostream OS(LinkerOpts);
628 
629   // Linker Options
630   if (NamedMDNode *LinkerOptions =
631           getModule().getNamedMetadata("llvm.linker.options")) {
632     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
633       MDNode *MDOptions = LinkerOptions->getOperand(i);
634       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
635         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
636         OS << " " << MDOption->getString();
637       }
638     }
639   }
640 
641   // Globals - we only need to do this for COFF.
642   const Triple TT(_target->getTargetTriple());
643   if (!TT.isOSBinFormatCOFF())
644     return;
645   Mangler M;
646   for (const NameAndAttributes &Sym : _symbols) {
647     if (!Sym.symbol)
648       continue;
649     emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
650   }
651 }
652 
653 lto::InputFile *LTOModule::createInputFile(const void *buffer,
654                                            size_t buffer_size, const char *path,
655                                            std::string &outErr) {
656   StringRef Data((const char *)buffer, buffer_size);
657   MemoryBufferRef BufferRef(Data, path);
658 
659   Expected<std::unique_ptr<lto::InputFile>> ObjOrErr =
660       lto::InputFile::create(BufferRef);
661 
662   if (ObjOrErr)
663     return ObjOrErr->release();
664 
665   outErr = std::string(path) +
666            ": Could not read LTO input file: " + toString(ObjOrErr.takeError());
667   return nullptr;
668 }
669 
670 size_t LTOModule::getDependentLibraryCount(lto::InputFile *input) {
671   return input->getDependentLibraries().size();
672 }
673 
674 const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,
675                                            size_t *size) {
676   StringRef S = input->getDependentLibraries()[index];
677   *size = S.size();
678   return S.data();
679 }
680 
681 Expected<uint32_t> LTOModule::getMachOCPUType() const {
682   return MachO::getCPUType(Triple(Mod->getTargetTriple()));
683 }
684 
685 Expected<uint32_t> LTOModule::getMachOCPUSubType() const {
686   return MachO::getCPUSubType(Triple(Mod->getTargetTriple()));
687 }
688