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