LTO: rename the various makeLTOModule overloads.
[oota-llvm.git] / lib / LTO / LTOModule.cpp
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/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.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/MCTargetAsmParser.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Object/RecordStreamer.h"
32 #include "llvm/Support/CommandLine.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/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include <system_error>
45 using namespace llvm;
46
47 LTOModule::LTOModule(std::unique_ptr<Module> M, TargetMachine *TM)
48     : _module(std::move(M)), _target(TM),
49       _context(_target->getMCAsmInfo(), _target->getRegisterInfo(),
50                &ObjFileInfo),
51       _mangler(TM->getDataLayout()) {
52   ObjFileInfo.InitMCObjectFileInfo(TM->getTargetTriple(),
53                                    TM->getRelocationModel(), TM->getCodeModel(),
54                                    _context);
55 }
56
57 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
58 /// bitcode.
59 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
60   return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
61          sys::fs::file_magic::bitcode;
62 }
63
64 bool LTOModule::isBitcodeFile(const char *path) {
65   sys::fs::file_magic type;
66   if (sys::fs::identify_magic(path, type))
67     return false;
68   return type == sys::fs::file_magic::bitcode;
69 }
70
71 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
72 /// LLVM bitcode for the specified triple.
73 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
74                                        const char *triplePrefix) {
75   MemoryBuffer *buffer = makeBuffer(mem, length);
76   if (!buffer)
77     return false;
78   return isTargetMatch(buffer, triplePrefix);
79 }
80
81 bool LTOModule::isBitcodeFileForTarget(const char *path,
82                                        const char *triplePrefix) {
83   std::unique_ptr<MemoryBuffer> buffer;
84   if (MemoryBuffer::getFile(path, buffer))
85     return false;
86   return isTargetMatch(buffer.release(), triplePrefix);
87 }
88
89 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
90 /// target triple.
91 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
92   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
93   delete buffer;
94   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
95 }
96
97 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
98                                      std::string &errMsg) {
99   std::unique_ptr<MemoryBuffer> buffer;
100   if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
101     errMsg = ec.message();
102     return nullptr;
103   }
104   return makeLTOModule(std::move(buffer), options, errMsg);
105 }
106
107 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
108                                          TargetOptions options,
109                                          std::string &errMsg) {
110   return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
111 }
112
113 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
114                                               size_t map_size, off_t offset,
115                                               TargetOptions options,
116                                               std::string &errMsg) {
117   std::unique_ptr<MemoryBuffer> buffer;
118   if (std::error_code ec =
119           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
120     errMsg = ec.message();
121     return nullptr;
122   }
123   return makeLTOModule(std::move(buffer), options, errMsg);
124 }
125
126 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
127                                        TargetOptions options,
128                                        std::string &errMsg, StringRef path) {
129   std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
130   if (!buffer)
131     return nullptr;
132   return makeLTOModule(std::move(buffer), options, errMsg);
133 }
134
135 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
136                                     TargetOptions options,
137                                     std::string &errMsg) {
138   // parse bitcode buffer
139   ErrorOr<Module *> ModuleOrErr =
140       getLazyBitcodeModule(Buffer.get(), getGlobalContext());
141   if (std::error_code EC = ModuleOrErr.getError()) {
142     errMsg = EC.message();
143     return nullptr;
144   }
145   Buffer.release();
146   std::unique_ptr<Module> m(ModuleOrErr.get());
147
148   std::string TripleStr = m->getTargetTriple();
149   if (TripleStr.empty())
150     TripleStr = sys::getDefaultTargetTriple();
151   llvm::Triple Triple(TripleStr);
152
153   // find machine architecture for this module
154   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
155   if (!march)
156     return nullptr;
157
158   // construct LTOModule, hand over ownership of module and target
159   SubtargetFeatures Features;
160   Features.getDefaultSubtargetFeatures(Triple);
161   std::string FeatureStr = Features.getString();
162   // Set a default CPU for Darwin triples.
163   std::string CPU;
164   if (Triple.isOSDarwin()) {
165     if (Triple.getArch() == llvm::Triple::x86_64)
166       CPU = "core2";
167     else if (Triple.getArch() == llvm::Triple::x86)
168       CPU = "yonah";
169     else if (Triple.getArch() == llvm::Triple::arm64 ||
170              Triple.getArch() == llvm::Triple::aarch64)
171       CPU = "cyclone";
172   }
173
174   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
175                                                      options);
176   m->materializeAllPermanently();
177
178   LTOModule *Ret = new LTOModule(std::move(m), target);
179
180   // We need a MCContext set up in order to get mangled names of private
181   // symbols. It is a bit odd that we need to report uses and definitions
182   // of private symbols, but it does look like ld64 expects to be informed
183   // of at least the ones with an 'l' prefix.
184   MCContext &Context = Ret->_context;
185   const TargetLoweringObjectFile &TLOF =
186       target->getTargetLowering()->getObjFileLowering();
187   const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
188
189   if (Ret->parseSymbols(errMsg)) {
190     delete Ret;
191     return nullptr;
192   }
193
194   Ret->parseMetadata();
195
196   return Ret;
197 }
198
199 /// Create a MemoryBuffer from a memory range with an optional name.
200 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
201                                     StringRef name) {
202   const char *startPtr = (const char*)mem;
203   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
204 }
205
206 /// objcClassNameFromExpression - Get string that the data pointer points to.
207 bool
208 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
209   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
210     Constant *op = ce->getOperand(0);
211     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
212       Constant *cn = gvn->getInitializer();
213       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
214         if (ca->isCString()) {
215           name = ".objc_class_name_" + ca->getAsCString().str();
216           return true;
217         }
218       }
219     }
220   }
221   return false;
222 }
223
224 /// addObjCClass - Parse i386/ppc ObjC class data structure.
225 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
226   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
227   if (!c) return;
228
229   // second slot in __OBJC,__class is pointer to superclass name
230   std::string superclassName;
231   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
232     NameAndAttributes info;
233     StringMap<NameAndAttributes>::value_type &entry =
234       _undefines.GetOrCreateValue(superclassName);
235     if (!entry.getValue().name) {
236       const char *symbolName = entry.getKey().data();
237       info.name = symbolName;
238       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
239       info.isFunction = false;
240       info.symbol = clgv;
241       entry.setValue(info);
242     }
243   }
244
245   // third slot in __OBJC,__class is pointer to class name
246   std::string className;
247   if (objcClassNameFromExpression(c->getOperand(2), className)) {
248     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
249     entry.setValue(1);
250
251     NameAndAttributes info;
252     info.name = entry.getKey().data();
253     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
254       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
255     info.isFunction = false;
256     info.symbol = clgv;
257     _symbols.push_back(info);
258   }
259 }
260
261 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
262 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
263   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
264   if (!c) return;
265
266   // second slot in __OBJC,__category is pointer to target class name
267   std::string targetclassName;
268   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
269     return;
270
271   NameAndAttributes info;
272   StringMap<NameAndAttributes>::value_type &entry =
273     _undefines.GetOrCreateValue(targetclassName);
274
275   if (entry.getValue().name)
276     return;
277
278   const char *symbolName = entry.getKey().data();
279   info.name = symbolName;
280   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
281   info.isFunction = false;
282   info.symbol = clgv;
283   entry.setValue(info);
284 }
285
286 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
287 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
288   std::string targetclassName;
289   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
290     return;
291
292   NameAndAttributes info;
293   StringMap<NameAndAttributes>::value_type &entry =
294     _undefines.GetOrCreateValue(targetclassName);
295   if (entry.getValue().name)
296     return;
297
298   const char *symbolName = entry.getKey().data();
299   info.name = symbolName;
300   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
301   info.isFunction = false;
302   info.symbol = clgv;
303   entry.setValue(info);
304 }
305
306 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
307 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
308   // Add to list of defined symbols.
309   addDefinedSymbol(v, false);
310
311   if (!v->hasSection() /* || !isTargetDarwin */)
312     return;
313
314   // Special case i386/ppc ObjC data structures in magic sections:
315   // The issue is that the old ObjC object format did some strange
316   // contortions to avoid real linker symbols.  For instance, the
317   // ObjC class data structure is allocated statically in the executable
318   // that defines that class.  That data structures contains a pointer to
319   // its superclass.  But instead of just initializing that part of the
320   // struct to the address of its superclass, and letting the static and
321   // dynamic linkers do the rest, the runtime works by having that field
322   // instead point to a C-string that is the name of the superclass.
323   // At runtime the objc initialization updates that pointer and sets
324   // it to point to the actual super class.  As far as the linker
325   // knows it is just a pointer to a string.  But then someone wanted the
326   // linker to issue errors at build time if the superclass was not found.
327   // So they figured out a way in mach-o object format to use an absolute
328   // symbols (.objc_class_name_Foo = 0) and a floating reference
329   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
330   // a class was missing.
331   // The following synthesizes the implicit .objc_* symbols for the linker
332   // from the ObjC data structures generated by the front end.
333
334   // special case if this data blob is an ObjC class definition
335   std::string Section = v->getSection();
336   if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
337     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
338       addObjCClass(gv);
339     }
340   }
341
342   // special case if this data blob is an ObjC category definition
343   else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
344     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
345       addObjCCategory(gv);
346     }
347   }
348
349   // special case if this data blob is the list of referenced classes
350   else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
351     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
352       addObjCClassRef(gv);
353     }
354   }
355 }
356
357 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
358 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
359   // add to list of defined symbols
360   addDefinedSymbol(f, true);
361 }
362
363 static bool canBeHidden(const GlobalValue *GV) {
364   // FIXME: this is duplicated with another static function in AsmPrinter.cpp
365   GlobalValue::LinkageTypes L = GV->getLinkage();
366
367   if (L != GlobalValue::LinkOnceODRLinkage)
368     return false;
369
370   if (GV->hasUnnamedAddr())
371     return true;
372
373   // If it is a non constant variable, it needs to be uniqued across shared
374   // objects.
375   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
376     if (!Var->isConstant())
377       return false;
378   }
379
380   GlobalStatus GS;
381   if (GlobalStatus::analyzeGlobal(GV, GS))
382     return false;
383
384   return !GS.IsCompared;
385 }
386
387 /// addDefinedSymbol - Add a defined symbol to the list.
388 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
389   // ignore all llvm.* symbols
390   if (def->getName().startswith("llvm."))
391     return;
392
393   // string is owned by _defines
394   SmallString<64> Buffer;
395   _target->getNameWithPrefix(Buffer, def, _mangler);
396
397   // set alignment part log2() can have rounding errors
398   uint32_t align = def->getAlignment();
399   uint32_t attr = align ? countTrailingZeros(align) : 0;
400
401   // set permissions part
402   if (isFunction) {
403     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
404   } else {
405     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
406     if (gv && gv->isConstant())
407       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
408     else
409       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
410   }
411
412   // set definition part
413   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
414     attr |= LTO_SYMBOL_DEFINITION_WEAK;
415   else if (def->hasCommonLinkage())
416     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
417   else
418     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
419
420   // set scope part
421   if (def->hasLocalLinkage())
422     // Ignore visibility if linkage is local.
423     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
424   else if (def->hasHiddenVisibility())
425     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
426   else if (def->hasProtectedVisibility())
427     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
428   else if (canBeHidden(def))
429     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
430   else
431     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
432
433   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
434   entry.setValue(1);
435
436   // fill information structure
437   NameAndAttributes info;
438   StringRef Name = entry.getKey();
439   info.name = Name.data();
440   assert(info.name[Name.size()] == '\0');
441   info.attributes = attr;
442   info.isFunction = isFunction;
443   info.symbol = def;
444
445   // add to table of symbols
446   _symbols.push_back(info);
447 }
448
449 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
450 /// defined list.
451 void LTOModule::addAsmGlobalSymbol(const char *name,
452                                    lto_symbol_attributes scope) {
453   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
454
455   // only add new define if not already defined
456   if (entry.getValue())
457     return;
458
459   entry.setValue(1);
460
461   NameAndAttributes &info = _undefines[entry.getKey().data()];
462
463   if (info.symbol == nullptr) {
464     // FIXME: This is trying to take care of module ASM like this:
465     //
466     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
467     //
468     // but is gross and its mother dresses it funny. Have the ASM parser give us
469     // more details for this type of situation so that we're not guessing so
470     // much.
471
472     // fill information structure
473     info.name = entry.getKey().data();
474     info.attributes =
475       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
476     info.isFunction = false;
477     info.symbol = nullptr;
478
479     // add to table of symbols
480     _symbols.push_back(info);
481     return;
482   }
483
484   if (info.isFunction)
485     addDefinedFunctionSymbol(cast<Function>(info.symbol));
486   else
487     addDefinedDataSymbol(info.symbol);
488
489   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
490   _symbols.back().attributes |= scope;
491 }
492
493 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
494 /// undefined list.
495 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
496   StringMap<NameAndAttributes>::value_type &entry =
497     _undefines.GetOrCreateValue(name);
498
499   _asm_undefines.push_back(entry.getKey().data());
500
501   // we already have the symbol
502   if (entry.getValue().name)
503     return;
504
505   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
506   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
507   NameAndAttributes info;
508   info.name = entry.getKey().data();
509   info.attributes = attr;
510   info.isFunction = false;
511   info.symbol = nullptr;
512
513   entry.setValue(info);
514 }
515
516 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
517 /// list to be resolved later.
518 void
519 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
520   // ignore all llvm.* symbols
521   if (decl->getName().startswith("llvm."))
522     return;
523
524   // ignore all aliases
525   if (isa<GlobalAlias>(decl))
526     return;
527
528   SmallString<64> name;
529   _target->getNameWithPrefix(name, decl, _mangler);
530
531   StringMap<NameAndAttributes>::value_type &entry =
532     _undefines.GetOrCreateValue(name);
533
534   // we already have the symbol
535   if (entry.getValue().name)
536     return;
537
538   NameAndAttributes info;
539
540   info.name = entry.getKey().data();
541
542   if (decl->hasExternalWeakLinkage())
543     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
544   else
545     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
546
547   info.isFunction = isFunc;
548   info.symbol = decl;
549
550   entry.setValue(info);
551 }
552
553 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
554 /// defined or undefined lists.
555 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
556   const std::string &inlineAsm = _module->getModuleInlineAsm();
557   if (inlineAsm.empty())
558     return false;
559
560   std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
561   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
562   SourceMgr SrcMgr;
563   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
564   std::unique_ptr<MCAsmParser> Parser(
565       createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
566   const Target &T = _target->getTarget();
567   std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
568   std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
569       _target->getTargetTriple(), _target->getTargetCPU(),
570       _target->getTargetFeatureString()));
571   std::unique_ptr<MCTargetAsmParser> TAP(
572       T.createMCAsmParser(*STI, *Parser.get(), *MCII,
573                           _target->Options.MCOptions));
574   if (!TAP) {
575     errMsg = "target " + std::string(T.getName()) +
576       " does not define AsmParser.";
577     return true;
578   }
579
580   Parser->setTargetParser(*TAP);
581   if (Parser->Run(false))
582     return true;
583
584   for (auto &KV : *Streamer) {
585     StringRef Key = KV.first();
586     RecordStreamer::State Value = KV.second;
587     if (Value == RecordStreamer::DefinedGlobal)
588       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
589     else if (Value == RecordStreamer::Defined)
590       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
591     else if (Value == RecordStreamer::Global ||
592              Value == RecordStreamer::Used)
593       addAsmGlobalSymbolUndef(Key.data());
594   }
595
596   return false;
597 }
598
599 /// isDeclaration - Return 'true' if the global value is a declaration.
600 static bool isDeclaration(const GlobalValue &V) {
601   if (V.hasAvailableExternallyLinkage())
602     return true;
603
604   if (V.isMaterializable())
605     return false;
606
607   return V.isDeclaration();
608 }
609
610 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
611 /// them to either the defined or undefined lists.
612 bool LTOModule::parseSymbols(std::string &errMsg) {
613   // add functions
614   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
615     if (isDeclaration(*f))
616       addPotentialUndefinedSymbol(f, true);
617     else
618       addDefinedFunctionSymbol(f);
619   }
620
621   // add data
622   for (Module::global_iterator v = _module->global_begin(),
623          e = _module->global_end(); v !=  e; ++v) {
624     if (isDeclaration(*v))
625       addPotentialUndefinedSymbol(v, false);
626     else
627       addDefinedDataSymbol(v);
628   }
629
630   // add asm globals
631   if (addAsmGlobalSymbols(errMsg))
632     return true;
633
634   // add aliases
635   for (const auto &Alias : _module->aliases())
636     addDefinedDataSymbol(&Alias);
637
638   // make symbols for all undefines
639   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
640          e = _undefines.end(); u != e; ++u) {
641     // If this symbol also has a definition, then don't make an undefine because
642     // it is a tentative definition.
643     if (_defines.count(u->getKey())) continue;
644     NameAndAttributes info = u->getValue();
645     _symbols.push_back(info);
646   }
647
648   return false;
649 }
650
651 /// parseMetadata - Parse metadata from the module
652 void LTOModule::parseMetadata() {
653   // Linker Options
654   if (Value *Val = _module->getModuleFlag("Linker Options")) {
655     MDNode *LinkerOptions = cast<MDNode>(Val);
656     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
657       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
658       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
659         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
660         StringRef Op = _linkeropt_strings.
661             GetOrCreateValue(MDOption->getString()).getKey();
662         StringRef DepLibName = _target->getTargetLowering()->
663             getObjFileLowering().getDepLibFromLinkerOpt(Op);
664         if (!DepLibName.empty())
665           _deplibs.push_back(DepLibName.data());
666         else if (!Op.empty())
667           _linkeropts.push_back(Op.data());
668       }
669     }
670   }
671
672   // Add other interesting metadata here.
673 }