Cache a commonly used reference.
[oota-llvm.git] / tools / 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 "LTOModule.h"
16 #include "llvm/Constants.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/MC/MCTargetAsmParser.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/MC/MCParser/MCAsmParser.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/TargetSelect.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/ADT/Triple.h"
39 using namespace llvm;
40
41 static cl::opt<bool>
42 EnableFPMAD("enable-fp-mad",
43   cl::desc("Enable less precise MAD instructions to be generated"),
44   cl::init(false));
45
46 static cl::opt<bool>
47 DisableFPElim("disable-fp-elim",
48   cl::desc("Disable frame pointer elimination optimization"),
49   cl::init(false));
50
51 static cl::opt<bool>
52 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
53   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
54   cl::init(false));
55
56 static cl::opt<bool>
57 EnableUnsafeFPMath("enable-unsafe-fp-math",
58   cl::desc("Enable optimizations that may decrease FP precision"),
59   cl::init(false));
60
61 static cl::opt<bool>
62 EnableNoInfsFPMath("enable-no-infs-fp-math",
63   cl::desc("Enable FP math optimizations that assume no +-Infs"),
64   cl::init(false));
65
66 static cl::opt<bool>
67 EnableNoNaNsFPMath("enable-no-nans-fp-math",
68   cl::desc("Enable FP math optimizations that assume no NaNs"),
69   cl::init(false));
70
71 static cl::opt<bool>
72 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
73   cl::Hidden,
74   cl::desc("Force codegen to assume rounding mode can change dynamically"),
75   cl::init(false));
76
77 static cl::opt<bool>
78 GenerateSoftFloatCalls("soft-float",
79   cl::desc("Generate software floating point library calls"),
80   cl::init(false));
81
82 static cl::opt<llvm::FloatABI::ABIType>
83 FloatABIForCalls("float-abi",
84   cl::desc("Choose float ABI type"),
85   cl::init(FloatABI::Default),
86   cl::values(
87     clEnumValN(FloatABI::Default, "default",
88                "Target default float ABI type"),
89     clEnumValN(FloatABI::Soft, "soft",
90                "Soft float ABI (implied by -soft-float)"),
91     clEnumValN(FloatABI::Hard, "hard",
92                "Hard float ABI (uses FP registers)"),
93     clEnumValEnd));
94
95 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
96 FuseFPOps("fp-contract",
97   cl::desc("Enable aggresive formation of fused FP ops"),
98   cl::init(FPOpFusion::Standard),
99   cl::values(
100     clEnumValN(FPOpFusion::Fast, "fast",
101                "Fuse FP ops whenever profitable"),
102     clEnumValN(FPOpFusion::Standard, "on",
103                "Only fuse 'blessed' FP ops."),
104     clEnumValN(FPOpFusion::Strict, "off",
105                "Only fuse FP ops when the result won't be effected."),
106     clEnumValEnd));
107
108 static cl::opt<bool>
109 DontPlaceZerosInBSS("nozero-initialized-in-bss",
110   cl::desc("Don't place zero-initialized symbols into bss section"),
111   cl::init(false));
112
113 static cl::opt<bool>
114 EnableGuaranteedTailCallOpt("tailcallopt",
115   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
116   cl::init(false));
117
118 static cl::opt<bool>
119 DisableTailCalls("disable-tail-calls",
120   cl::desc("Never emit tail calls"),
121   cl::init(false));
122
123 static cl::opt<unsigned>
124 OverrideStackAlignment("stack-alignment",
125   cl::desc("Override default stack alignment"),
126   cl::init(0));
127
128 static cl::opt<bool>
129 EnableRealignStack("realign-stack",
130   cl::desc("Realign stack if needed"),
131   cl::init(true));
132
133 static cl::opt<std::string>
134 TrapFuncName("trap-func", cl::Hidden,
135   cl::desc("Emit a call to trap function rather than a trap instruction"),
136   cl::init(""));
137
138 static cl::opt<bool>
139 EnablePIE("enable-pie",
140   cl::desc("Assume the creation of a position independent executable."),
141   cl::init(false));
142
143 static cl::opt<bool>
144 SegmentedStacks("segmented-stacks",
145   cl::desc("Use segmented stacks if possible."),
146   cl::init(false));
147
148 static cl::opt<bool>
149 UseInitArray("use-init-array",
150   cl::desc("Use .init_array instead of .ctors."),
151   cl::init(false));
152
153 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
154   : _module(m), _target(t),
155     _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
156     _mangler(_context, *_target->getTargetData()) {}
157
158 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
159 /// bitcode.
160 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
161   return llvm::sys::IdentifyFileType((char*)mem, length)
162     == llvm::sys::Bitcode_FileType;
163 }
164
165 bool LTOModule::isBitcodeFile(const char *path) {
166   return llvm::sys::Path(path).isBitcodeFile();
167 }
168
169 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
170 /// LLVM bitcode for the specified triple.
171 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
172                                        const char *triplePrefix) {
173   MemoryBuffer *buffer = makeBuffer(mem, length);
174   if (!buffer)
175     return false;
176   return isTargetMatch(buffer, triplePrefix);
177 }
178
179 bool LTOModule::isBitcodeFileForTarget(const char *path,
180                                        const char *triplePrefix) {
181   OwningPtr<MemoryBuffer> buffer;
182   if (MemoryBuffer::getFile(path, buffer))
183     return false;
184   return isTargetMatch(buffer.take(), triplePrefix);
185 }
186
187 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
188 /// target triple.
189 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
190   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
191   delete buffer;
192   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
193 }
194
195 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
196 /// the buffer.
197 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
198   OwningPtr<MemoryBuffer> buffer;
199   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
200     errMsg = ec.message();
201     return NULL;
202   }
203   return makeLTOModule(buffer.take(), errMsg);
204 }
205
206 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
207                                     size_t size, std::string &errMsg) {
208   return makeLTOModule(fd, path, size, size, 0, errMsg);
209 }
210
211 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
212                                     size_t file_size,
213                                     size_t map_size,
214                                     off_t offset,
215                                     std::string &errMsg) {
216   OwningPtr<MemoryBuffer> buffer;
217   if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
218                                                 map_size, offset, false)) {
219     errMsg = ec.message();
220     return NULL;
221   }
222   return makeLTOModule(buffer.take(), errMsg);
223 }
224
225 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
226                                     std::string &errMsg) {
227   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
228   if (!buffer)
229     return NULL;
230   return makeLTOModule(buffer.take(), errMsg);
231 }
232
233 void LTOModule::getTargetOptions(TargetOptions &Options) {
234   Options.LessPreciseFPMADOption = EnableFPMAD;
235   Options.NoFramePointerElim = DisableFPElim;
236   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
237   Options.AllowFPOpFusion = FuseFPOps;
238   Options.UnsafeFPMath = EnableUnsafeFPMath;
239   Options.NoInfsFPMath = EnableNoInfsFPMath;
240   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
241   Options.HonorSignDependentRoundingFPMathOption =
242     EnableHonorSignDependentRoundingFPMath;
243   Options.UseSoftFloat = GenerateSoftFloatCalls;
244   if (FloatABIForCalls != FloatABI::Default)
245     Options.FloatABIType = FloatABIForCalls;
246   Options.NoZerosInBSS = DontPlaceZerosInBSS;
247   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
248   Options.DisableTailCalls = DisableTailCalls;
249   Options.StackAlignmentOverride = OverrideStackAlignment;
250   Options.RealignStack = EnableRealignStack;
251   Options.TrapFuncName = TrapFuncName;
252   Options.PositionIndependentExecutable = EnablePIE;
253   Options.EnableSegmentedStacks = SegmentedStacks;
254   Options.UseInitArray = UseInitArray;
255 }
256
257 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
258                                     std::string &errMsg) {
259   static bool Initialized = false;
260   if (!Initialized) {
261     InitializeAllTargets();
262     InitializeAllTargetMCs();
263     InitializeAllAsmParsers();
264     Initialized = true;
265   }
266
267   // parse bitcode buffer
268   OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
269                                            &errMsg));
270   if (!m) {
271     delete buffer;
272     return NULL;
273   }
274
275   std::string Triple = m->getTargetTriple();
276   if (Triple.empty())
277     Triple = sys::getDefaultTargetTriple();
278
279   // find machine architecture for this module
280   const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
281   if (!march)
282     return NULL;
283
284   // construct LTOModule, hand over ownership of module and target
285   SubtargetFeatures Features;
286   Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
287   std::string FeatureStr = Features.getString();
288   std::string CPU;
289   TargetOptions Options;
290   getTargetOptions(Options);
291   TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr,
292                                                      Options);
293   LTOModule *Ret = new LTOModule(m.take(), target);
294   if (Ret->parseSymbols(errMsg)) {
295     delete Ret;
296     return NULL;
297   }
298
299   return Ret;
300 }
301
302 /// makeBuffer - Create a MemoryBuffer from a memory range.
303 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
304   const char *startPtr = (char*)mem;
305   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
306 }
307
308 /// objcClassNameFromExpression - Get string that the data pointer points to.
309 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
310   if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
311     Constant *op = ce->getOperand(0);
312     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
313       Constant *cn = gvn->getInitializer();
314       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
315         if (ca->isCString()) {
316           name = ".objc_class_name_" + ca->getAsCString().str();
317           return true;
318         }
319       }
320     }
321   }
322   return false;
323 }
324
325 /// addObjCClass - Parse i386/ppc ObjC class data structure.
326 void LTOModule::addObjCClass(GlobalVariable *clgv) {
327   ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
328   if (!c) return;
329
330   // second slot in __OBJC,__class is pointer to superclass name
331   std::string superclassName;
332   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
333     NameAndAttributes info;
334     StringMap<NameAndAttributes>::value_type &entry =
335       _undefines.GetOrCreateValue(superclassName);
336     if (!entry.getValue().name) {
337       const char *symbolName = entry.getKey().data();
338       info.name = symbolName;
339       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
340       info.isFunction = false;
341       info.symbol = clgv;
342       entry.setValue(info);
343     }
344   }
345
346   // third slot in __OBJC,__class is pointer to class name
347   std::string className;
348   if (objcClassNameFromExpression(c->getOperand(2), className)) {
349     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
350     entry.setValue(1);
351
352     NameAndAttributes info;
353     info.name = entry.getKey().data();
354     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
355       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
356     info.isFunction = false;
357     info.symbol = clgv;
358     _symbols.push_back(info);
359   }
360 }
361
362 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
363 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
364   ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
365   if (!c) return;
366
367   // second slot in __OBJC,__category is pointer to target class name
368   std::string targetclassName;
369   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
370     return;
371
372   NameAndAttributes info;
373   StringMap<NameAndAttributes>::value_type &entry =
374     _undefines.GetOrCreateValue(targetclassName);
375
376   if (entry.getValue().name)
377     return;
378
379   const char *symbolName = entry.getKey().data();
380   info.name = symbolName;
381   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
382   info.isFunction = false;
383   info.symbol = clgv;
384   entry.setValue(info);
385 }
386
387 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
388 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
389   std::string targetclassName;
390   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
391     return;
392
393   NameAndAttributes info;
394   StringMap<NameAndAttributes>::value_type &entry =
395     _undefines.GetOrCreateValue(targetclassName);
396   if (entry.getValue().name)
397     return;
398
399   const char *symbolName = entry.getKey().data();
400   info.name = symbolName;
401   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
402   info.isFunction = false;
403   info.symbol = clgv;
404   entry.setValue(info);
405 }
406
407 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
408 void LTOModule::addDefinedDataSymbol(GlobalValue *v) {
409   // Add to list of defined symbols.
410   addDefinedSymbol(v, false);
411
412   if (!v->hasSection() /* || !isTargetDarwin */)
413     return;
414
415   // Special case i386/ppc ObjC data structures in magic sections:
416   // The issue is that the old ObjC object format did some strange
417   // contortions to avoid real linker symbols.  For instance, the
418   // ObjC class data structure is allocated statically in the executable
419   // that defines that class.  That data structures contains a pointer to
420   // its superclass.  But instead of just initializing that part of the
421   // struct to the address of its superclass, and letting the static and
422   // dynamic linkers do the rest, the runtime works by having that field
423   // instead point to a C-string that is the name of the superclass.
424   // At runtime the objc initialization updates that pointer and sets
425   // it to point to the actual super class.  As far as the linker
426   // knows it is just a pointer to a string.  But then someone wanted the
427   // linker to issue errors at build time if the superclass was not found.
428   // So they figured out a way in mach-o object format to use an absolute
429   // symbols (.objc_class_name_Foo = 0) and a floating reference
430   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
431   // a class was missing.
432   // The following synthesizes the implicit .objc_* symbols for the linker
433   // from the ObjC data structures generated by the front end.
434
435   // special case if this data blob is an ObjC class definition
436   if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
437     if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
438       addObjCClass(gv);
439     }
440   }
441
442   // special case if this data blob is an ObjC category definition
443   else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
444     if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
445       addObjCCategory(gv);
446     }
447   }
448
449   // special case if this data blob is the list of referenced classes
450   else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
451     if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
452       addObjCClassRef(gv);
453     }
454   }
455 }
456
457 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
458 void LTOModule::addDefinedFunctionSymbol(Function *f) {
459   // add to list of defined symbols
460   addDefinedSymbol(f, true);
461 }
462
463 /// addDefinedSymbol - Add a defined symbol to the list.
464 void LTOModule::addDefinedSymbol(GlobalValue *def, bool isFunction) {
465   // ignore all llvm.* symbols
466   if (def->getName().startswith("llvm."))
467     return;
468
469   // string is owned by _defines
470   SmallString<64> Buffer;
471   _mangler.getNameWithPrefix(Buffer, def, false);
472
473   // set alignment part log2() can have rounding errors
474   uint32_t align = def->getAlignment();
475   uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
476
477   // set permissions part
478   if (isFunction) {
479     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
480   } else {
481     GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
482     if (gv && gv->isConstant())
483       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
484     else
485       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
486   }
487
488   // set definition part
489   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
490       def->hasLinkerPrivateWeakLinkage() ||
491       def->hasLinkerPrivateWeakDefAutoLinkage())
492     attr |= LTO_SYMBOL_DEFINITION_WEAK;
493   else if (def->hasCommonLinkage())
494     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
495   else
496     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
497
498   // set scope part
499   if (def->hasHiddenVisibility())
500     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
501   else if (def->hasProtectedVisibility())
502     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
503   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
504            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
505            def->hasLinkerPrivateWeakLinkage())
506     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
507   else if (def->hasLinkerPrivateWeakDefAutoLinkage())
508     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
509   else
510     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
511
512   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
513   entry.setValue(1);
514
515   // fill information structure
516   NameAndAttributes info;
517   StringRef Name = entry.getKey();
518   info.name = Name.data();
519   assert(info.name[Name.size()] == '\0');
520   info.attributes = attr;
521   info.isFunction = isFunction;
522   info.symbol = def;
523
524   // add to table of symbols
525   _symbols.push_back(info);
526 }
527
528 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
529 /// defined list.
530 void LTOModule::addAsmGlobalSymbol(const char *name,
531                                    lto_symbol_attributes scope) {
532   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
533
534   // only add new define if not already defined
535   if (entry.getValue())
536     return;
537
538   entry.setValue(1);
539
540   NameAndAttributes &info = _undefines[entry.getKey().data()];
541
542   if (info.symbol == 0) {
543     // FIXME: This is trying to take care of module ASM like this:
544     //
545     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
546     //
547     // but is gross and its mother dresses it funny. Have the ASM parser give us
548     // more details for this type of situation so that we're not guessing so
549     // much.
550
551     // fill information structure
552     info.name = entry.getKey().data();
553     info.attributes =
554       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
555     info.isFunction = false;
556     info.symbol = 0;
557
558     // add to table of symbols
559     _symbols.push_back(info);
560     return;
561   }
562
563   if (info.isFunction)
564     addDefinedFunctionSymbol(cast<Function>(info.symbol));
565   else
566     addDefinedDataSymbol(info.symbol);
567
568   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
569   _symbols.back().attributes |= scope;
570 }
571
572 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
573 /// undefined list.
574 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
575   StringMap<NameAndAttributes>::value_type &entry =
576     _undefines.GetOrCreateValue(name);
577
578   _asm_undefines.push_back(entry.getKey().data());
579
580   // we already have the symbol
581   if (entry.getValue().name)
582     return;
583
584   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
585   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
586   NameAndAttributes info;
587   info.name = entry.getKey().data();
588   info.attributes = attr;
589   info.isFunction = false;
590   info.symbol = 0;
591
592   entry.setValue(info);
593 }
594
595 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
596 /// list to be resolved later.
597 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl, bool isFunc) {
598   // ignore all llvm.* symbols
599   if (decl->getName().startswith("llvm."))
600     return;
601
602   // ignore all aliases
603   if (isa<GlobalAlias>(decl))
604     return;
605
606   SmallString<64> name;
607   _mangler.getNameWithPrefix(name, decl, false);
608
609   StringMap<NameAndAttributes>::value_type &entry =
610     _undefines.GetOrCreateValue(name);
611
612   // we already have the symbol
613   if (entry.getValue().name)
614     return;
615
616   NameAndAttributes info;
617
618   info.name = entry.getKey().data();
619
620   if (decl->hasExternalWeakLinkage())
621     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
622   else
623     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
624
625   info.isFunction = isFunc;
626   info.symbol = decl;
627
628   entry.setValue(info);
629 }
630
631 namespace {
632   class RecordStreamer : public MCStreamer {
633   public:
634     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
635
636   private:
637     StringMap<State> Symbols;
638
639     void markDefined(const MCSymbol &Symbol) {
640       State &S = Symbols[Symbol.getName()];
641       switch (S) {
642       case DefinedGlobal:
643       case Global:
644         S = DefinedGlobal;
645         break;
646       case NeverSeen:
647       case Defined:
648       case Used:
649         S = Defined;
650         break;
651       }
652     }
653     void markGlobal(const MCSymbol &Symbol) {
654       State &S = Symbols[Symbol.getName()];
655       switch (S) {
656       case DefinedGlobal:
657       case Defined:
658         S = DefinedGlobal;
659         break;
660
661       case NeverSeen:
662       case Global:
663       case Used:
664         S = Global;
665         break;
666       }
667     }
668     void markUsed(const MCSymbol &Symbol) {
669       State &S = Symbols[Symbol.getName()];
670       switch (S) {
671       case DefinedGlobal:
672       case Defined:
673       case Global:
674         break;
675
676       case NeverSeen:
677       case Used:
678         S = Used;
679         break;
680       }
681     }
682
683     // FIXME: mostly copied for the obj streamer.
684     void AddValueSymbols(const MCExpr *Value) {
685       switch (Value->getKind()) {
686       case MCExpr::Target:
687         // FIXME: What should we do in here?
688         break;
689
690       case MCExpr::Constant:
691         break;
692
693       case MCExpr::Binary: {
694         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
695         AddValueSymbols(BE->getLHS());
696         AddValueSymbols(BE->getRHS());
697         break;
698       }
699
700       case MCExpr::SymbolRef:
701         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
702         break;
703
704       case MCExpr::Unary:
705         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
706         break;
707       }
708     }
709
710   public:
711     typedef StringMap<State>::const_iterator const_iterator;
712
713     const_iterator begin() {
714       return Symbols.begin();
715     }
716
717     const_iterator end() {
718       return Symbols.end();
719     }
720
721     RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
722
723     virtual void EmitInstruction(const MCInst &Inst) {
724       // Scan for values.
725       for (unsigned i = Inst.getNumOperands(); i--; )
726         if (Inst.getOperand(i).isExpr())
727           AddValueSymbols(Inst.getOperand(i).getExpr());
728     }
729     virtual void EmitLabel(MCSymbol *Symbol) {
730       Symbol->setSection(*getCurrentSection());
731       markDefined(*Symbol);
732     }
733     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
734       // FIXME: should we handle aliases?
735       markDefined(*Symbol);
736     }
737     virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
738       if (Attribute == MCSA_Global)
739         markGlobal(*Symbol);
740     }
741     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
742                               uint64_t Size , unsigned ByteAlignment) {
743       markDefined(*Symbol);
744     }
745     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
746                                   unsigned ByteAlignment) {
747       markDefined(*Symbol);
748     }
749
750     // Noop calls.
751     virtual void ChangeSection(const MCSection *Section) {}
752     virtual void InitSections() {}
753     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
754     virtual void EmitThumbFunc(MCSymbol *Func) {}
755     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
756     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
757     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
758     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
759     virtual void EmitCOFFSymbolType(int Type) {}
760     virtual void EndCOFFSymbolDef() {}
761     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
762     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
763                                        unsigned ByteAlignment) {}
764     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
765                                 uint64_t Size, unsigned ByteAlignment) {}
766     virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
767     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
768                                unsigned AddrSpace) {}
769     virtual void EmitULEB128Value(const MCExpr *Value) {}
770     virtual void EmitSLEB128Value(const MCExpr *Value) {}
771     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
772                                       unsigned ValueSize,
773                                       unsigned MaxBytesToEmit) {}
774     virtual void EmitCodeAlignment(unsigned ByteAlignment,
775                                    unsigned MaxBytesToEmit) {}
776     virtual bool EmitValueToOffset(const MCExpr *Offset,
777                                    unsigned char Value ) { return false; }
778     virtual void EmitFileDirective(StringRef Filename) {}
779     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
780                                           const MCSymbol *LastLabel,
781                                           const MCSymbol *Label,
782                                           unsigned PointerSize) {}
783     virtual void FinishImpl() {}
784   };
785 } // end anonymous namespace
786
787 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
788 /// defined or undefined lists.
789 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
790   const std::string &inlineAsm = _module->getModuleInlineAsm();
791   if (inlineAsm.empty())
792     return false;
793
794   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
795   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
796   SourceMgr SrcMgr;
797   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
798   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
799                                                   _context, *Streamer,
800                                                   *_target->getMCAsmInfo()));
801   const Target &T = _target->getTarget();
802   OwningPtr<MCSubtargetInfo>
803     STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
804                                 _target->getTargetCPU(),
805                                 _target->getTargetFeatureString()));
806   OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
807   if (!TAP) {
808     errMsg = "target " + std::string(T.getName()) +
809       " does not define AsmParser.";
810     return true;
811   }
812
813   Parser->setTargetParser(*TAP);
814   if (Parser->Run(false))
815     return true;
816
817   for (RecordStreamer::const_iterator i = Streamer->begin(),
818          e = Streamer->end(); i != e; ++i) {
819     StringRef Key = i->first();
820     RecordStreamer::State Value = i->second;
821     if (Value == RecordStreamer::DefinedGlobal)
822       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
823     else if (Value == RecordStreamer::Defined)
824       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
825     else if (Value == RecordStreamer::Global ||
826              Value == RecordStreamer::Used)
827       addAsmGlobalSymbolUndef(Key.data());
828   }
829
830   return false;
831 }
832
833 /// isDeclaration - Return 'true' if the global value is a declaration.
834 static bool isDeclaration(const GlobalValue &V) {
835   if (V.hasAvailableExternallyLinkage())
836     return true;
837
838   if (V.isMaterializable())
839     return false;
840
841   return V.isDeclaration();
842 }
843
844 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
845 /// them to either the defined or undefined lists.
846 bool LTOModule::parseSymbols(std::string &errMsg) {
847   // add functions
848   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
849     if (isDeclaration(*f))
850       addPotentialUndefinedSymbol(f, true);
851     else
852       addDefinedFunctionSymbol(f);
853   }
854
855   // add data
856   for (Module::global_iterator v = _module->global_begin(),
857          e = _module->global_end(); v !=  e; ++v) {
858     if (isDeclaration(*v))
859       addPotentialUndefinedSymbol(v, false);
860     else
861       addDefinedDataSymbol(v);
862   }
863
864   // add asm globals
865   if (addAsmGlobalSymbols(errMsg))
866     return true;
867
868   // add aliases
869   for (Module::alias_iterator a = _module->alias_begin(),
870          e = _module->alias_end(); a != e; ++a) {
871     if (isDeclaration(*a->getAliasedGlobal()))
872       // Is an alias to a declaration.
873       addPotentialUndefinedSymbol(a, false);
874     else
875       addDefinedDataSymbol(a);
876   }
877
878   // make symbols for all undefines
879   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
880          e = _undefines.end(); u != e; ++u) {
881     // If this symbol also has a definition, then don't make an undefine because
882     // it is a tentative definition.
883     if (_defines.count(u->getKey())) continue;
884     NameAndAttributes info = u->getValue();
885     _symbols.push_back(info);
886   }
887
888   return false;
889 }