InitToTextSection is redundant with InitSections. Remove it.
[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/OwningPtr.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.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/MCInstrInfo.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Transforms/Utils/GlobalStatus.h"
46 using namespace llvm;
47
48 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
49   : _module(m), _target(t),
50     _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), &ObjFileInfo),
51     _mangler(t->getDataLayout()) {
52   ObjFileInfo.InitMCObjectFileInfo(t->getTargetTriple(),
53                                    t->getRelocationModel(), t->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   OwningPtr<MemoryBuffer> buffer;
84   if (MemoryBuffer::getFile(path, buffer))
85     return false;
86   return isTargetMatch(buffer.take(), 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 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
98 /// the buffer.
99 LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options,
100                                     std::string &errMsg) {
101   OwningPtr<MemoryBuffer> buffer;
102   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
103     errMsg = ec.message();
104     return NULL;
105   }
106   return makeLTOModule(buffer.take(), options, errMsg);
107 }
108
109 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
110                                     size_t size, TargetOptions options,
111                                     std::string &errMsg) {
112   return makeLTOModule(fd, path, size, 0, options, errMsg);
113 }
114
115 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
116                                     size_t map_size,
117                                     off_t offset,
118                                     TargetOptions options,
119                                     std::string &errMsg) {
120   OwningPtr<MemoryBuffer> buffer;
121   if (error_code ec =
122           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
123     errMsg = ec.message();
124     return NULL;
125   }
126   return makeLTOModule(buffer.take(), options, errMsg);
127 }
128
129 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
130                                     TargetOptions options,
131                                     std::string &errMsg) {
132   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
133   if (!buffer)
134     return NULL;
135   return makeLTOModule(buffer.take(), options, errMsg);
136 }
137
138 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
139                                     TargetOptions options,
140                                     std::string &errMsg) {
141   // parse bitcode buffer
142   ErrorOr<Module *> ModuleOrErr =
143       getLazyBitcodeModule(buffer, getGlobalContext());
144   if (error_code EC = ModuleOrErr.getError()) {
145     errMsg = EC.message();
146     delete buffer;
147     return NULL;
148   }
149   OwningPtr<Module> m(ModuleOrErr.get());
150
151   std::string TripleStr = m->getTargetTriple();
152   if (TripleStr.empty())
153     TripleStr = sys::getDefaultTargetTriple();
154   llvm::Triple Triple(TripleStr);
155
156   // find machine architecture for this module
157   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
158   if (!march)
159     return NULL;
160
161   // construct LTOModule, hand over ownership of module and target
162   SubtargetFeatures Features;
163   Features.getDefaultSubtargetFeatures(Triple);
164   std::string FeatureStr = Features.getString();
165   // Set a default CPU for Darwin triples.
166   std::string CPU;
167   if (Triple.isOSDarwin()) {
168     if (Triple.getArch() == llvm::Triple::x86_64)
169       CPU = "core2";
170     else if (Triple.getArch() == llvm::Triple::x86)
171       CPU = "yonah";
172   }
173
174   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
175                                                      options);
176   m->materializeAllPermanently();
177
178   LTOModule *Ret = new LTOModule(m.take(), target);
179   if (Ret->parseSymbols(errMsg)) {
180     delete Ret;
181     return NULL;
182   }
183
184   Ret->parseMetadata();
185
186   return Ret;
187 }
188
189 /// makeBuffer - Create a MemoryBuffer from a memory range.
190 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
191   const char *startPtr = (const char*)mem;
192   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
193 }
194
195 /// objcClassNameFromExpression - Get string that the data pointer points to.
196 bool
197 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
198   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
199     Constant *op = ce->getOperand(0);
200     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
201       Constant *cn = gvn->getInitializer();
202       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
203         if (ca->isCString()) {
204           name = ".objc_class_name_" + ca->getAsCString().str();
205           return true;
206         }
207       }
208     }
209   }
210   return false;
211 }
212
213 /// addObjCClass - Parse i386/ppc ObjC class data structure.
214 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
215   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
216   if (!c) return;
217
218   // second slot in __OBJC,__class is pointer to superclass name
219   std::string superclassName;
220   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
221     NameAndAttributes info;
222     StringMap<NameAndAttributes>::value_type &entry =
223       _undefines.GetOrCreateValue(superclassName);
224     if (!entry.getValue().name) {
225       const char *symbolName = entry.getKey().data();
226       info.name = symbolName;
227       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
228       info.isFunction = false;
229       info.symbol = clgv;
230       entry.setValue(info);
231     }
232   }
233
234   // third slot in __OBJC,__class is pointer to class name
235   std::string className;
236   if (objcClassNameFromExpression(c->getOperand(2), className)) {
237     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
238     entry.setValue(1);
239
240     NameAndAttributes info;
241     info.name = entry.getKey().data();
242     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
243       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
244     info.isFunction = false;
245     info.symbol = clgv;
246     _symbols.push_back(info);
247   }
248 }
249
250 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
251 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
252   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
253   if (!c) return;
254
255   // second slot in __OBJC,__category is pointer to target class name
256   std::string targetclassName;
257   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
258     return;
259
260   NameAndAttributes info;
261   StringMap<NameAndAttributes>::value_type &entry =
262     _undefines.GetOrCreateValue(targetclassName);
263
264   if (entry.getValue().name)
265     return;
266
267   const char *symbolName = entry.getKey().data();
268   info.name = symbolName;
269   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
270   info.isFunction = false;
271   info.symbol = clgv;
272   entry.setValue(info);
273 }
274
275 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
276 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
277   std::string targetclassName;
278   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
279     return;
280
281   NameAndAttributes info;
282   StringMap<NameAndAttributes>::value_type &entry =
283     _undefines.GetOrCreateValue(targetclassName);
284   if (entry.getValue().name)
285     return;
286
287   const char *symbolName = entry.getKey().data();
288   info.name = symbolName;
289   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
290   info.isFunction = false;
291   info.symbol = clgv;
292   entry.setValue(info);
293 }
294
295 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
296 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
297   // Add to list of defined symbols.
298   addDefinedSymbol(v, false);
299
300   if (!v->hasSection() /* || !isTargetDarwin */)
301     return;
302
303   // Special case i386/ppc ObjC data structures in magic sections:
304   // The issue is that the old ObjC object format did some strange
305   // contortions to avoid real linker symbols.  For instance, the
306   // ObjC class data structure is allocated statically in the executable
307   // that defines that class.  That data structures contains a pointer to
308   // its superclass.  But instead of just initializing that part of the
309   // struct to the address of its superclass, and letting the static and
310   // dynamic linkers do the rest, the runtime works by having that field
311   // instead point to a C-string that is the name of the superclass.
312   // At runtime the objc initialization updates that pointer and sets
313   // it to point to the actual super class.  As far as the linker
314   // knows it is just a pointer to a string.  But then someone wanted the
315   // linker to issue errors at build time if the superclass was not found.
316   // So they figured out a way in mach-o object format to use an absolute
317   // symbols (.objc_class_name_Foo = 0) and a floating reference
318   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
319   // a class was missing.
320   // The following synthesizes the implicit .objc_* symbols for the linker
321   // from the ObjC data structures generated by the front end.
322
323   // special case if this data blob is an ObjC class definition
324   if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
325     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
326       addObjCClass(gv);
327     }
328   }
329
330   // special case if this data blob is an ObjC category definition
331   else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
332     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
333       addObjCCategory(gv);
334     }
335   }
336
337   // special case if this data blob is the list of referenced classes
338   else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
339     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
340       addObjCClassRef(gv);
341     }
342   }
343 }
344
345 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
346 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
347   // add to list of defined symbols
348   addDefinedSymbol(f, true);
349 }
350
351 static bool canBeHidden(const GlobalValue *GV) {
352   GlobalValue::LinkageTypes L = GV->getLinkage();
353
354   if (L != GlobalValue::LinkOnceODRLinkage)
355     return false;
356
357   if (GV->hasUnnamedAddr())
358     return true;
359
360   GlobalStatus GS;
361   if (GlobalStatus::analyzeGlobal(GV, GS))
362     return false;
363
364   return !GS.IsCompared;
365 }
366
367 /// addDefinedSymbol - Add a defined symbol to the list.
368 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
369   // ignore all llvm.* symbols
370   if (def->getName().startswith("llvm."))
371     return;
372
373   // string is owned by _defines
374   SmallString<64> Buffer;
375   _mangler.getNameWithPrefix(Buffer, def);
376
377   // set alignment part log2() can have rounding errors
378   uint32_t align = def->getAlignment();
379   uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
380
381   // set permissions part
382   if (isFunction) {
383     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
384   } else {
385     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
386     if (gv && gv->isConstant())
387       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
388     else
389       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
390   }
391
392   // set definition part
393   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
394       def->hasLinkerPrivateWeakLinkage())
395     attr |= LTO_SYMBOL_DEFINITION_WEAK;
396   else if (def->hasCommonLinkage())
397     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
398   else
399     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
400
401   // set scope part
402   if (def->hasHiddenVisibility())
403     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
404   else if (def->hasProtectedVisibility())
405     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
406   else if (canBeHidden(def))
407     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
408   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
409            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
410            def->hasLinkerPrivateWeakLinkage())
411     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
412   else
413     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
414
415   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
416   entry.setValue(1);
417
418   // fill information structure
419   NameAndAttributes info;
420   StringRef Name = entry.getKey();
421   info.name = Name.data();
422   assert(info.name[Name.size()] == '\0');
423   info.attributes = attr;
424   info.isFunction = isFunction;
425   info.symbol = def;
426
427   // add to table of symbols
428   _symbols.push_back(info);
429 }
430
431 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
432 /// defined list.
433 void LTOModule::addAsmGlobalSymbol(const char *name,
434                                    lto_symbol_attributes scope) {
435   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
436
437   // only add new define if not already defined
438   if (entry.getValue())
439     return;
440
441   entry.setValue(1);
442
443   NameAndAttributes &info = _undefines[entry.getKey().data()];
444
445   if (info.symbol == 0) {
446     // FIXME: This is trying to take care of module ASM like this:
447     //
448     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
449     //
450     // but is gross and its mother dresses it funny. Have the ASM parser give us
451     // more details for this type of situation so that we're not guessing so
452     // much.
453
454     // fill information structure
455     info.name = entry.getKey().data();
456     info.attributes =
457       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
458     info.isFunction = false;
459     info.symbol = 0;
460
461     // add to table of symbols
462     _symbols.push_back(info);
463     return;
464   }
465
466   if (info.isFunction)
467     addDefinedFunctionSymbol(cast<Function>(info.symbol));
468   else
469     addDefinedDataSymbol(info.symbol);
470
471   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
472   _symbols.back().attributes |= scope;
473 }
474
475 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
476 /// undefined list.
477 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
478   StringMap<NameAndAttributes>::value_type &entry =
479     _undefines.GetOrCreateValue(name);
480
481   _asm_undefines.push_back(entry.getKey().data());
482
483   // we already have the symbol
484   if (entry.getValue().name)
485     return;
486
487   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
488   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
489   NameAndAttributes info;
490   info.name = entry.getKey().data();
491   info.attributes = attr;
492   info.isFunction = false;
493   info.symbol = 0;
494
495   entry.setValue(info);
496 }
497
498 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
499 /// list to be resolved later.
500 void
501 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
502   // ignore all llvm.* symbols
503   if (decl->getName().startswith("llvm."))
504     return;
505
506   // ignore all aliases
507   if (isa<GlobalAlias>(decl))
508     return;
509
510   SmallString<64> name;
511   _mangler.getNameWithPrefix(name, decl);
512
513   StringMap<NameAndAttributes>::value_type &entry =
514     _undefines.GetOrCreateValue(name);
515
516   // we already have the symbol
517   if (entry.getValue().name)
518     return;
519
520   NameAndAttributes info;
521
522   info.name = entry.getKey().data();
523
524   if (decl->hasExternalWeakLinkage())
525     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
526   else
527     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
528
529   info.isFunction = isFunc;
530   info.symbol = decl;
531
532   entry.setValue(info);
533 }
534
535 namespace {
536
537 // Common infrastructure is allowed to assume the existence of a current
538 // section. Since this streamer doesn't need one itself, we just provide
539 // a dummy one.
540 class DummySection : public MCSection {
541 public:
542   DummySection() : MCSection(SV_ELF, SectionKind::getText()) {}
543
544   virtual void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS,
545                                     const MCExpr *Subsection) const {}
546
547   virtual std::string getLabelBeginName() const { return ""; }
548
549   virtual std::string getLabelEndName() const { return ""; }
550
551   virtual bool UseCodeAlign() const { return false; }
552
553   virtual bool isVirtualSection() const { return false; }
554 };
555
556   class RecordStreamer : public MCStreamer {
557   public:
558     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
559
560     DummySection TheSection;
561
562   private:
563     StringMap<State> Symbols;
564
565     void markDefined(const MCSymbol &Symbol) {
566       State &S = Symbols[Symbol.getName()];
567       switch (S) {
568       case DefinedGlobal:
569       case Global:
570         S = DefinedGlobal;
571         break;
572       case NeverSeen:
573       case Defined:
574       case Used:
575         S = Defined;
576         break;
577       }
578     }
579     void markGlobal(const MCSymbol &Symbol) {
580       State &S = Symbols[Symbol.getName()];
581       switch (S) {
582       case DefinedGlobal:
583       case Defined:
584         S = DefinedGlobal;
585         break;
586
587       case NeverSeen:
588       case Global:
589       case Used:
590         S = Global;
591         break;
592       }
593     }
594     void markUsed(const MCSymbol &Symbol) {
595       State &S = Symbols[Symbol.getName()];
596       switch (S) {
597       case DefinedGlobal:
598       case Defined:
599       case Global:
600         break;
601
602       case NeverSeen:
603       case Used:
604         S = Used;
605         break;
606       }
607     }
608
609     // FIXME: mostly copied for the obj streamer.
610     void AddValueSymbols(const MCExpr *Value) {
611       switch (Value->getKind()) {
612       case MCExpr::Target:
613         // FIXME: What should we do in here?
614         break;
615
616       case MCExpr::Constant:
617         break;
618
619       case MCExpr::Binary: {
620         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
621         AddValueSymbols(BE->getLHS());
622         AddValueSymbols(BE->getRHS());
623         break;
624       }
625
626       case MCExpr::SymbolRef:
627         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
628         break;
629
630       case MCExpr::Unary:
631         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
632         break;
633       }
634     }
635
636   public:
637     typedef StringMap<State>::const_iterator const_iterator;
638
639     const_iterator begin() {
640       return Symbols.begin();
641     }
642
643     const_iterator end() {
644       return Symbols.end();
645     }
646
647     RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {
648       SwitchSection(&TheSection);
649     }
650
651     virtual void EmitInstruction(const MCInst &Inst) {
652       // Scan for values.
653       for (unsigned i = Inst.getNumOperands(); i--; )
654         if (Inst.getOperand(i).isExpr())
655           AddValueSymbols(Inst.getOperand(i).getExpr());
656     }
657     virtual void EmitLabel(MCSymbol *Symbol) {
658       Symbol->setSection(*getCurrentSection().first);
659       markDefined(*Symbol);
660     }
661     virtual void EmitDebugLabel(MCSymbol *Symbol) {
662       EmitLabel(Symbol);
663     }
664     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
665       // FIXME: should we handle aliases?
666       markDefined(*Symbol);
667     }
668     virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
669       if (Attribute == MCSA_Global)
670         markGlobal(*Symbol);
671       return true;
672     }
673     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
674                               uint64_t Size , unsigned ByteAlignment) {
675       markDefined(*Symbol);
676     }
677     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
678                                   unsigned ByteAlignment) {
679       markDefined(*Symbol);
680     }
681
682     virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
683     virtual void EmitBundleLock(bool AlignToEnd) {}
684     virtual void EmitBundleUnlock() {}
685
686     // Noop calls.
687     virtual void ChangeSection(const MCSection *Section,
688                                const MCExpr *Subsection) {}
689     virtual void InitSections() {}
690     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
691     virtual void EmitThumbFunc(MCSymbol *Func) {}
692     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
693     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
694     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
695     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
696     virtual void EmitCOFFSymbolType(int Type) {}
697     virtual void EndCOFFSymbolDef() {}
698     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
699     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
700                                        unsigned ByteAlignment) {}
701     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
702                                 uint64_t Size, unsigned ByteAlignment) {}
703     virtual void EmitBytes(StringRef Data) {}
704     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
705     virtual void EmitULEB128Value(const MCExpr *Value) {}
706     virtual void EmitSLEB128Value(const MCExpr *Value) {}
707     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
708                                       unsigned ValueSize,
709                                       unsigned MaxBytesToEmit) {}
710     virtual void EmitCodeAlignment(unsigned ByteAlignment,
711                                    unsigned MaxBytesToEmit) {}
712     virtual bool EmitValueToOffset(const MCExpr *Offset,
713                                    unsigned char Value ) { return false; }
714     virtual void EmitFileDirective(StringRef Filename) {}
715     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
716                                           const MCSymbol *LastLabel,
717                                           const MCSymbol *Label,
718                                           unsigned PointerSize) {}
719     virtual void FinishImpl() {}
720     virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
721       RecordProcEnd(Frame);
722     }
723   };
724 } // end anonymous namespace
725
726 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
727 /// defined or undefined lists.
728 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
729   const std::string &inlineAsm = _module->getModuleInlineAsm();
730   if (inlineAsm.empty())
731     return false;
732
733   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
734   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
735   SourceMgr SrcMgr;
736   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
737   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
738                                                   _context, *Streamer,
739                                                   *_target->getMCAsmInfo()));
740   const Target &T = _target->getTarget();
741   OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo());
742   OwningPtr<MCSubtargetInfo>
743     STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
744                                 _target->getTargetCPU(),
745                                 _target->getTargetFeatureString()));
746   OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
747   if (!TAP) {
748     errMsg = "target " + std::string(T.getName()) +
749       " does not define AsmParser.";
750     return true;
751   }
752
753   Parser->setTargetParser(*TAP);
754   if (Parser->Run(false))
755     return true;
756
757   for (RecordStreamer::const_iterator i = Streamer->begin(),
758          e = Streamer->end(); i != e; ++i) {
759     StringRef Key = i->first();
760     RecordStreamer::State Value = i->second;
761     if (Value == RecordStreamer::DefinedGlobal)
762       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
763     else if (Value == RecordStreamer::Defined)
764       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
765     else if (Value == RecordStreamer::Global ||
766              Value == RecordStreamer::Used)
767       addAsmGlobalSymbolUndef(Key.data());
768   }
769
770   return false;
771 }
772
773 /// isDeclaration - Return 'true' if the global value is a declaration.
774 static bool isDeclaration(const GlobalValue &V) {
775   if (V.hasAvailableExternallyLinkage())
776     return true;
777
778   if (V.isMaterializable())
779     return false;
780
781   return V.isDeclaration();
782 }
783
784 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
785 /// them to either the defined or undefined lists.
786 bool LTOModule::parseSymbols(std::string &errMsg) {
787   // add functions
788   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
789     if (isDeclaration(*f))
790       addPotentialUndefinedSymbol(f, true);
791     else
792       addDefinedFunctionSymbol(f);
793   }
794
795   // add data
796   for (Module::global_iterator v = _module->global_begin(),
797          e = _module->global_end(); v !=  e; ++v) {
798     if (isDeclaration(*v))
799       addPotentialUndefinedSymbol(v, false);
800     else
801       addDefinedDataSymbol(v);
802   }
803
804   // add asm globals
805   if (addAsmGlobalSymbols(errMsg))
806     return true;
807
808   // add aliases
809   for (Module::alias_iterator a = _module->alias_begin(),
810          e = _module->alias_end(); a != e; ++a) {
811     if (isDeclaration(*a->getAliasedGlobal()))
812       // Is an alias to a declaration.
813       addPotentialUndefinedSymbol(a, false);
814     else
815       addDefinedDataSymbol(a);
816   }
817
818   // make symbols for all undefines
819   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
820          e = _undefines.end(); u != e; ++u) {
821     // If this symbol also has a definition, then don't make an undefine because
822     // it is a tentative definition.
823     if (_defines.count(u->getKey())) continue;
824     NameAndAttributes info = u->getValue();
825     _symbols.push_back(info);
826   }
827
828   return false;
829 }
830
831 /// parseMetadata - Parse metadata from the module
832 void LTOModule::parseMetadata() {
833   // Linker Options
834   if (Value *Val = _module->getModuleFlag("Linker Options")) {
835     MDNode *LinkerOptions = cast<MDNode>(Val);
836     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
837       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
838       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
839         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
840         StringRef Op = _linkeropt_strings.
841             GetOrCreateValue(MDOption->getString()).getKey();
842         StringRef DepLibName = _target->getTargetLowering()->
843             getObjFileLowering().getDepLibFromLinkerOpt(Op);
844         if (!DepLibName.empty())
845           _deplibs.push_back(DepLibName.data());
846         else if (!Op.empty())
847           _linkeropts.push_back(Op.data());
848       }
849     }
850   }
851
852   // Add other interesting metadata here.
853 }