1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Support/system_error.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
42 EnableFPMAD("enable-fp-mad",
43 cl::desc("Enable less precise MAD instructions to be generated"),
47 DisableFPElim("disable-fp-elim",
48 cl::desc("Disable frame pointer elimination optimization"),
52 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
53 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
57 EnableUnsafeFPMath("enable-unsafe-fp-math",
58 cl::desc("Enable optimizations that may decrease FP precision"),
62 EnableNoInfsFPMath("enable-no-infs-fp-math",
63 cl::desc("Enable FP math optimizations that assume no +-Infs"),
67 EnableNoNaNsFPMath("enable-no-nans-fp-math",
68 cl::desc("Enable FP math optimizations that assume no NaNs"),
72 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
74 cl::desc("Force codegen to assume rounding mode can change dynamically"),
78 GenerateSoftFloatCalls("soft-float",
79 cl::desc("Generate software floating point library calls"),
82 static cl::opt<llvm::FloatABI::ABIType>
83 FloatABIForCalls("float-abi",
84 cl::desc("Choose float ABI type"),
85 cl::init(FloatABI::Default),
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)"),
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),
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."),
109 DontPlaceZerosInBSS("nozero-initialized-in-bss",
110 cl::desc("Don't place zero-initialized symbols into bss section"),
114 EnableGuaranteedTailCallOpt("tailcallopt",
115 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
119 DisableTailCalls("disable-tail-calls",
120 cl::desc("Never emit tail calls"),
123 static cl::opt<unsigned>
124 OverrideStackAlignment("stack-alignment",
125 cl::desc("Override default stack alignment"),
129 EnableRealignStack("realign-stack",
130 cl::desc("Realign stack if needed"),
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"),
139 EnablePIE("enable-pie",
140 cl::desc("Assume the creation of a position independent executable."),
144 SegmentedStacks("segmented-stacks",
145 cl::desc("Use segmented stacks if possible."),
149 UseInitArray("use-init-array",
150 cl::desc("Use .init_array instead of .ctors."),
153 static cl::opt<unsigned>
154 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
155 cl::desc("Lower bound for a buffer to be considered for "
156 "stack protection"));
158 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
159 : _module(m), _target(t),
160 _context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(), NULL),
161 _mangler(_context, *_target->getDataLayout()) {}
163 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
165 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
166 return llvm::sys::IdentifyFileType((const char*)mem, length)
167 == llvm::sys::Bitcode_FileType;
170 bool LTOModule::isBitcodeFile(const char *path) {
171 return llvm::sys::Path(path).isBitcodeFile();
174 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
175 /// LLVM bitcode for the specified triple.
176 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
177 const char *triplePrefix) {
178 MemoryBuffer *buffer = makeBuffer(mem, length);
181 return isTargetMatch(buffer, triplePrefix);
184 bool LTOModule::isBitcodeFileForTarget(const char *path,
185 const char *triplePrefix) {
186 OwningPtr<MemoryBuffer> buffer;
187 if (MemoryBuffer::getFile(path, buffer))
189 return isTargetMatch(buffer.take(), triplePrefix);
192 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
194 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
195 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
197 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
200 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
202 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
203 OwningPtr<MemoryBuffer> buffer;
204 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
205 errMsg = ec.message();
208 return makeLTOModule(buffer.take(), errMsg);
211 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
212 size_t size, std::string &errMsg) {
213 return makeLTOModule(fd, path, size, size, 0, errMsg);
216 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
220 std::string &errMsg) {
221 OwningPtr<MemoryBuffer> buffer;
222 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
223 map_size, offset, false)) {
224 errMsg = ec.message();
227 return makeLTOModule(buffer.take(), errMsg);
230 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
231 std::string &errMsg) {
232 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
235 return makeLTOModule(buffer.take(), errMsg);
238 void LTOModule::getTargetOptions(TargetOptions &Options) {
239 Options.LessPreciseFPMADOption = EnableFPMAD;
240 Options.NoFramePointerElim = DisableFPElim;
241 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
242 Options.AllowFPOpFusion = FuseFPOps;
243 Options.UnsafeFPMath = EnableUnsafeFPMath;
244 Options.NoInfsFPMath = EnableNoInfsFPMath;
245 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
246 Options.HonorSignDependentRoundingFPMathOption =
247 EnableHonorSignDependentRoundingFPMath;
248 Options.UseSoftFloat = GenerateSoftFloatCalls;
249 if (FloatABIForCalls != FloatABI::Default)
250 Options.FloatABIType = FloatABIForCalls;
251 Options.NoZerosInBSS = DontPlaceZerosInBSS;
252 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
253 Options.DisableTailCalls = DisableTailCalls;
254 Options.StackAlignmentOverride = OverrideStackAlignment;
255 Options.RealignStack = EnableRealignStack;
256 Options.TrapFuncName = TrapFuncName;
257 Options.PositionIndependentExecutable = EnablePIE;
258 Options.EnableSegmentedStacks = SegmentedStacks;
259 Options.UseInitArray = UseInitArray;
260 Options.SSPBufferSize = SSPBufferSize;
263 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
264 std::string &errMsg) {
265 static bool Initialized = false;
267 InitializeAllTargets();
268 InitializeAllTargetMCs();
269 InitializeAllAsmParsers();
273 // parse bitcode buffer
274 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
281 std::string TripleStr = m->getTargetTriple();
282 if (TripleStr.empty())
283 TripleStr = sys::getDefaultTargetTriple();
284 llvm::Triple Triple(TripleStr);
286 // find machine architecture for this module
287 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
291 // construct LTOModule, hand over ownership of module and target
292 SubtargetFeatures Features;
293 Features.getDefaultSubtargetFeatures(Triple);
294 std::string FeatureStr = Features.getString();
295 // Set a default CPU for Darwin triples.
297 if (Triple.isOSDarwin()) {
298 if (Triple.getArch() == llvm::Triple::x86_64)
300 else if (Triple.getArch() == llvm::Triple::x86)
303 TargetOptions Options;
304 getTargetOptions(Options);
305 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
307 LTOModule *Ret = new LTOModule(m.take(), target);
308 if (Ret->parseSymbols(errMsg)) {
316 /// makeBuffer - Create a MemoryBuffer from a memory range.
317 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
318 const char *startPtr = (const char*)mem;
319 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
322 /// objcClassNameFromExpression - Get string that the data pointer points to.
324 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
325 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
326 Constant *op = ce->getOperand(0);
327 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
328 Constant *cn = gvn->getInitializer();
329 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
330 if (ca->isCString()) {
331 name = ".objc_class_name_" + ca->getAsCString().str();
340 /// addObjCClass - Parse i386/ppc ObjC class data structure.
341 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
342 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
345 // second slot in __OBJC,__class is pointer to superclass name
346 std::string superclassName;
347 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
348 NameAndAttributes info;
349 StringMap<NameAndAttributes>::value_type &entry =
350 _undefines.GetOrCreateValue(superclassName);
351 if (!entry.getValue().name) {
352 const char *symbolName = entry.getKey().data();
353 info.name = symbolName;
354 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
355 info.isFunction = false;
357 entry.setValue(info);
361 // third slot in __OBJC,__class is pointer to class name
362 std::string className;
363 if (objcClassNameFromExpression(c->getOperand(2), className)) {
364 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
367 NameAndAttributes info;
368 info.name = entry.getKey().data();
369 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
370 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
371 info.isFunction = false;
373 _symbols.push_back(info);
377 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
378 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
379 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
382 // second slot in __OBJC,__category is pointer to target class name
383 std::string targetclassName;
384 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
387 NameAndAttributes info;
388 StringMap<NameAndAttributes>::value_type &entry =
389 _undefines.GetOrCreateValue(targetclassName);
391 if (entry.getValue().name)
394 const char *symbolName = entry.getKey().data();
395 info.name = symbolName;
396 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
397 info.isFunction = false;
399 entry.setValue(info);
402 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
403 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
404 std::string targetclassName;
405 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
408 NameAndAttributes info;
409 StringMap<NameAndAttributes>::value_type &entry =
410 _undefines.GetOrCreateValue(targetclassName);
411 if (entry.getValue().name)
414 const char *symbolName = entry.getKey().data();
415 info.name = symbolName;
416 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
417 info.isFunction = false;
419 entry.setValue(info);
422 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
423 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
424 // Add to list of defined symbols.
425 addDefinedSymbol(v, false);
427 if (!v->hasSection() /* || !isTargetDarwin */)
430 // Special case i386/ppc ObjC data structures in magic sections:
431 // The issue is that the old ObjC object format did some strange
432 // contortions to avoid real linker symbols. For instance, the
433 // ObjC class data structure is allocated statically in the executable
434 // that defines that class. That data structures contains a pointer to
435 // its superclass. But instead of just initializing that part of the
436 // struct to the address of its superclass, and letting the static and
437 // dynamic linkers do the rest, the runtime works by having that field
438 // instead point to a C-string that is the name of the superclass.
439 // At runtime the objc initialization updates that pointer and sets
440 // it to point to the actual super class. As far as the linker
441 // knows it is just a pointer to a string. But then someone wanted the
442 // linker to issue errors at build time if the superclass was not found.
443 // So they figured out a way in mach-o object format to use an absolute
444 // symbols (.objc_class_name_Foo = 0) and a floating reference
445 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
446 // a class was missing.
447 // The following synthesizes the implicit .objc_* symbols for the linker
448 // from the ObjC data structures generated by the front end.
450 // special case if this data blob is an ObjC class definition
451 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
452 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
457 // special case if this data blob is an ObjC category definition
458 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
459 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
464 // special case if this data blob is the list of referenced classes
465 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
466 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
472 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
473 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
474 // add to list of defined symbols
475 addDefinedSymbol(f, true);
478 /// addDefinedSymbol - Add a defined symbol to the list.
479 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
480 // ignore all llvm.* symbols
481 if (def->getName().startswith("llvm."))
484 // string is owned by _defines
485 SmallString<64> Buffer;
486 _mangler.getNameWithPrefix(Buffer, def, false);
488 // set alignment part log2() can have rounding errors
489 uint32_t align = def->getAlignment();
490 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
492 // set permissions part
494 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
496 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
497 if (gv && gv->isConstant())
498 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
500 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
503 // set definition part
504 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
505 def->hasLinkerPrivateWeakLinkage())
506 attr |= LTO_SYMBOL_DEFINITION_WEAK;
507 else if (def->hasCommonLinkage())
508 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
510 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
513 if (def->hasHiddenVisibility())
514 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
515 else if (def->hasProtectedVisibility())
516 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
517 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
518 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
519 def->hasLinkerPrivateWeakLinkage())
520 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
521 else if (def->hasLinkOnceODRAutoHideLinkage())
522 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
524 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
526 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
529 // fill information structure
530 NameAndAttributes info;
531 StringRef Name = entry.getKey();
532 info.name = Name.data();
533 assert(info.name[Name.size()] == '\0');
534 info.attributes = attr;
535 info.isFunction = isFunction;
538 // add to table of symbols
539 _symbols.push_back(info);
542 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
544 void LTOModule::addAsmGlobalSymbol(const char *name,
545 lto_symbol_attributes scope) {
546 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
548 // only add new define if not already defined
549 if (entry.getValue())
554 NameAndAttributes &info = _undefines[entry.getKey().data()];
556 if (info.symbol == 0) {
557 // FIXME: This is trying to take care of module ASM like this:
559 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
561 // but is gross and its mother dresses it funny. Have the ASM parser give us
562 // more details for this type of situation so that we're not guessing so
565 // fill information structure
566 info.name = entry.getKey().data();
568 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
569 info.isFunction = false;
572 // add to table of symbols
573 _symbols.push_back(info);
578 addDefinedFunctionSymbol(cast<Function>(info.symbol));
580 addDefinedDataSymbol(info.symbol);
582 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
583 _symbols.back().attributes |= scope;
586 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
588 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
589 StringMap<NameAndAttributes>::value_type &entry =
590 _undefines.GetOrCreateValue(name);
592 _asm_undefines.push_back(entry.getKey().data());
594 // we already have the symbol
595 if (entry.getValue().name)
598 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
599 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
600 NameAndAttributes info;
601 info.name = entry.getKey().data();
602 info.attributes = attr;
603 info.isFunction = false;
606 entry.setValue(info);
609 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
610 /// list to be resolved later.
612 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
613 // ignore all llvm.* symbols
614 if (decl->getName().startswith("llvm."))
617 // ignore all aliases
618 if (isa<GlobalAlias>(decl))
621 SmallString<64> name;
622 _mangler.getNameWithPrefix(name, decl, false);
624 StringMap<NameAndAttributes>::value_type &entry =
625 _undefines.GetOrCreateValue(name);
627 // we already have the symbol
628 if (entry.getValue().name)
631 NameAndAttributes info;
633 info.name = entry.getKey().data();
635 if (decl->hasExternalWeakLinkage())
636 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
638 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
640 info.isFunction = isFunc;
643 entry.setValue(info);
647 class RecordStreamer : public MCStreamer {
649 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
652 StringMap<State> Symbols;
654 void markDefined(const MCSymbol &Symbol) {
655 State &S = Symbols[Symbol.getName()];
668 void markGlobal(const MCSymbol &Symbol) {
669 State &S = Symbols[Symbol.getName()];
683 void markUsed(const MCSymbol &Symbol) {
684 State &S = Symbols[Symbol.getName()];
698 // FIXME: mostly copied for the obj streamer.
699 void AddValueSymbols(const MCExpr *Value) {
700 switch (Value->getKind()) {
702 // FIXME: What should we do in here?
705 case MCExpr::Constant:
708 case MCExpr::Binary: {
709 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
710 AddValueSymbols(BE->getLHS());
711 AddValueSymbols(BE->getRHS());
715 case MCExpr::SymbolRef:
716 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
720 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
726 typedef StringMap<State>::const_iterator const_iterator;
728 const_iterator begin() {
729 return Symbols.begin();
732 const_iterator end() {
733 return Symbols.end();
736 RecordStreamer(MCContext &Context)
737 : MCStreamer(SK_RecordStreamer, Context) {}
739 virtual void EmitInstruction(const MCInst &Inst) {
741 for (unsigned i = Inst.getNumOperands(); i--; )
742 if (Inst.getOperand(i).isExpr())
743 AddValueSymbols(Inst.getOperand(i).getExpr());
745 virtual void EmitLabel(MCSymbol *Symbol) {
746 Symbol->setSection(*getCurrentSection());
747 markDefined(*Symbol);
749 virtual void EmitDebugLabel(MCSymbol *Symbol) {
752 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
753 // FIXME: should we handle aliases?
754 markDefined(*Symbol);
756 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
757 if (Attribute == MCSA_Global)
760 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
761 uint64_t Size , unsigned ByteAlignment) {
762 markDefined(*Symbol);
764 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
765 unsigned ByteAlignment) {
766 markDefined(*Symbol);
769 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
770 virtual void EmitBundleLock(bool AlignToEnd) {}
771 virtual void EmitBundleUnlock() {}
774 virtual void ChangeSection(const MCSection *Section) {}
775 virtual void InitToTextSection() {}
776 virtual void InitSections() {}
777 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
778 virtual void EmitThumbFunc(MCSymbol *Func) {}
779 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
780 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
781 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
782 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
783 virtual void EmitCOFFSymbolType(int Type) {}
784 virtual void EndCOFFSymbolDef() {}
785 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
786 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
787 unsigned ByteAlignment) {}
788 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
789 uint64_t Size, unsigned ByteAlignment) {}
790 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
791 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
792 unsigned AddrSpace) {}
793 virtual void EmitULEB128Value(const MCExpr *Value) {}
794 virtual void EmitSLEB128Value(const MCExpr *Value) {}
795 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
797 unsigned MaxBytesToEmit) {}
798 virtual void EmitCodeAlignment(unsigned ByteAlignment,
799 unsigned MaxBytesToEmit) {}
800 virtual bool EmitValueToOffset(const MCExpr *Offset,
801 unsigned char Value ) { return false; }
802 virtual void EmitFileDirective(StringRef Filename) {}
803 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
804 const MCSymbol *LastLabel,
805 const MCSymbol *Label,
806 unsigned PointerSize) {}
807 virtual void FinishImpl() {}
809 static bool classof(const MCStreamer *S) {
810 return S->getKind() == SK_RecordStreamer;
813 } // end anonymous namespace
815 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
816 /// defined or undefined lists.
817 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
818 const std::string &inlineAsm = _module->getModuleInlineAsm();
819 if (inlineAsm.empty())
822 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
823 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
825 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
826 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
828 *_target->getMCAsmInfo()));
829 const Target &T = _target->getTarget();
830 OwningPtr<MCSubtargetInfo>
831 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
832 _target->getTargetCPU(),
833 _target->getTargetFeatureString()));
834 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
836 errMsg = "target " + std::string(T.getName()) +
837 " does not define AsmParser.";
841 Parser->setTargetParser(*TAP);
842 if (Parser->Run(false))
845 for (RecordStreamer::const_iterator i = Streamer->begin(),
846 e = Streamer->end(); i != e; ++i) {
847 StringRef Key = i->first();
848 RecordStreamer::State Value = i->second;
849 if (Value == RecordStreamer::DefinedGlobal)
850 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
851 else if (Value == RecordStreamer::Defined)
852 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
853 else if (Value == RecordStreamer::Global ||
854 Value == RecordStreamer::Used)
855 addAsmGlobalSymbolUndef(Key.data());
861 /// isDeclaration - Return 'true' if the global value is a declaration.
862 static bool isDeclaration(const GlobalValue &V) {
863 if (V.hasAvailableExternallyLinkage())
866 if (V.isMaterializable())
869 return V.isDeclaration();
872 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
873 /// them to either the defined or undefined lists.
874 bool LTOModule::parseSymbols(std::string &errMsg) {
876 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
877 if (isDeclaration(*f))
878 addPotentialUndefinedSymbol(f, true);
880 addDefinedFunctionSymbol(f);
884 for (Module::global_iterator v = _module->global_begin(),
885 e = _module->global_end(); v != e; ++v) {
886 if (isDeclaration(*v))
887 addPotentialUndefinedSymbol(v, false);
889 addDefinedDataSymbol(v);
893 if (addAsmGlobalSymbols(errMsg))
897 for (Module::alias_iterator a = _module->alias_begin(),
898 e = _module->alias_end(); a != e; ++a) {
899 if (isDeclaration(*a->getAliasedGlobal()))
900 // Is an alias to a declaration.
901 addPotentialUndefinedSymbol(a, false);
903 addDefinedDataSymbol(a);
906 // make symbols for all undefines
907 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
908 e = _undefines.end(); u != e; ++u) {
909 // If this symbol also has a definition, then don't make an undefine because
910 // it is a tentative definition.
911 if (_defines.count(u->getKey())) continue;
912 NameAndAttributes info = u->getValue();
913 _symbols.push_back(info);