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