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/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"
44 EnableFPMAD("enable-fp-mad",
45 cl::desc("Enable less precise MAD instructions to be generated"),
49 DisableFPElim("disable-fp-elim",
50 cl::desc("Disable frame pointer elimination optimization"),
54 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
55 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
59 EnableUnsafeFPMath("enable-unsafe-fp-math",
60 cl::desc("Enable optimizations that may decrease FP precision"),
64 EnableNoInfsFPMath("enable-no-infs-fp-math",
65 cl::desc("Enable FP math optimizations that assume no +-Infs"),
69 EnableNoNaNsFPMath("enable-no-nans-fp-math",
70 cl::desc("Enable FP math optimizations that assume no NaNs"),
74 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
76 cl::desc("Force codegen to assume rounding mode can change dynamically"),
80 GenerateSoftFloatCalls("soft-float",
81 cl::desc("Generate software floating point library calls"),
84 static cl::opt<llvm::FloatABI::ABIType>
85 FloatABIForCalls("float-abi",
86 cl::desc("Choose float ABI type"),
87 cl::init(FloatABI::Default),
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)"),
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),
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."),
111 DontPlaceZerosInBSS("nozero-initialized-in-bss",
112 cl::desc("Don't place zero-initialized symbols into bss section"),
116 EnableGuaranteedTailCallOpt("tailcallopt",
117 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
121 DisableTailCalls("disable-tail-calls",
122 cl::desc("Never emit tail calls"),
125 static cl::opt<unsigned>
126 OverrideStackAlignment("stack-alignment",
127 cl::desc("Override default stack alignment"),
131 EnableRealignStack("realign-stack",
132 cl::desc("Realign stack if needed"),
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"),
141 EnablePIE("enable-pie",
142 cl::desc("Assume the creation of a position independent executable."),
146 SegmentedStacks("segmented-stacks",
147 cl::desc("Use segmented stacks if possible."),
151 UseInitArray("use-init-array",
152 cl::desc("Use .init_array instead of .ctors."),
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"));
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) {}
165 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
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;
172 bool LTOModule::isBitcodeFile(const char *path) {
173 return llvm::sys::Path(path).isBitcodeFile();
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);
183 return isTargetMatch(buffer, triplePrefix);
186 bool LTOModule::isBitcodeFileForTarget(const char *path,
187 const char *triplePrefix) {
188 OwningPtr<MemoryBuffer> buffer;
189 if (MemoryBuffer::getFile(path, buffer))
191 return isTargetMatch(buffer.take(), triplePrefix);
194 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
196 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
197 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
199 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
202 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
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();
210 return makeLTOModule(buffer.take(), errMsg);
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);
218 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
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();
229 return makeLTOModule(buffer.take(), errMsg);
232 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
233 std::string &errMsg) {
234 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
237 return makeLTOModule(buffer.take(), errMsg);
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;
265 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
266 std::string &errMsg) {
267 static bool Initialized = false;
269 InitializeAllTargets();
270 InitializeAllTargetMCs();
271 InitializeAllAsmParsers();
275 // parse bitcode buffer
276 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
283 std::string TripleStr = m->getTargetTriple();
284 if (TripleStr.empty())
285 TripleStr = sys::getDefaultTargetTriple();
286 llvm::Triple Triple(TripleStr);
288 // find machine architecture for this module
289 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
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.
299 if (Triple.isOSDarwin()) {
300 if (Triple.getArch() == llvm::Triple::x86_64)
302 else if (Triple.getArch() == llvm::Triple::x86)
305 TargetOptions Options;
306 getTargetOptions(Options);
307 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
309 LTOModule *Ret = new LTOModule(m.take(), target);
310 if (Ret->parseSymbols(errMsg)) {
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);
324 /// objcClassNameFromExpression - Get string that the data pointer points to.
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();
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());
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;
359 entry.setValue(info);
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);
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;
375 _symbols.push_back(info);
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());
384 // second slot in __OBJC,__category is pointer to target class name
385 std::string targetclassName;
386 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
389 NameAndAttributes info;
390 StringMap<NameAndAttributes>::value_type &entry =
391 _undefines.GetOrCreateValue(targetclassName);
393 if (entry.getValue().name)
396 const char *symbolName = entry.getKey().data();
397 info.name = symbolName;
398 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
399 info.isFunction = false;
401 entry.setValue(info);
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))
410 NameAndAttributes info;
411 StringMap<NameAndAttributes>::value_type &entry =
412 _undefines.GetOrCreateValue(targetclassName);
413 if (entry.getValue().name)
416 const char *symbolName = entry.getKey().data();
417 info.name = symbolName;
418 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
419 info.isFunction = false;
421 entry.setValue(info);
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);
429 if (!v->hasSection() /* || !isTargetDarwin */)
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.
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)) {
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)) {
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)) {
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);
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."))
486 // string is owned by _defines
487 SmallString<64> Buffer;
488 _mangler.getNameWithPrefix(Buffer, def, false);
490 // set alignment part log2() can have rounding errors
491 uint32_t align = def->getAlignment();
492 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
494 // set permissions part
496 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
498 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
499 if (gv && gv->isConstant())
500 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
502 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
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;
512 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
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;
526 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
528 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
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;
540 // add to table of symbols
541 _symbols.push_back(info);
544 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
546 void LTOModule::addAsmGlobalSymbol(const char *name,
547 lto_symbol_attributes scope) {
548 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
550 // only add new define if not already defined
551 if (entry.getValue())
556 NameAndAttributes &info = _undefines[entry.getKey().data()];
558 if (info.symbol == 0) {
559 // FIXME: This is trying to take care of module ASM like this:
561 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
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
567 // fill information structure
568 info.name = entry.getKey().data();
570 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
571 info.isFunction = false;
574 // add to table of symbols
575 _symbols.push_back(info);
580 addDefinedFunctionSymbol(cast<Function>(info.symbol));
582 addDefinedDataSymbol(info.symbol);
584 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
585 _symbols.back().attributes |= scope;
588 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
590 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
591 StringMap<NameAndAttributes>::value_type &entry =
592 _undefines.GetOrCreateValue(name);
594 _asm_undefines.push_back(entry.getKey().data());
596 // we already have the symbol
597 if (entry.getValue().name)
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;
608 entry.setValue(info);
611 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
612 /// list to be resolved later.
614 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
615 // ignore all llvm.* symbols
616 if (decl->getName().startswith("llvm."))
619 // ignore all aliases
620 if (isa<GlobalAlias>(decl))
623 SmallString<64> name;
624 _mangler.getNameWithPrefix(name, decl, false);
626 StringMap<NameAndAttributes>::value_type &entry =
627 _undefines.GetOrCreateValue(name);
629 // we already have the symbol
630 if (entry.getValue().name)
633 NameAndAttributes info;
635 info.name = entry.getKey().data();
637 if (decl->hasExternalWeakLinkage())
638 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
640 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
642 info.isFunction = isFunc;
645 entry.setValue(info);
649 class RecordStreamer : public MCStreamer {
651 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
654 StringMap<State> Symbols;
656 void markDefined(const MCSymbol &Symbol) {
657 State &S = Symbols[Symbol.getName()];
670 void markGlobal(const MCSymbol &Symbol) {
671 State &S = Symbols[Symbol.getName()];
685 void markUsed(const MCSymbol &Symbol) {
686 State &S = Symbols[Symbol.getName()];
700 // FIXME: mostly copied for the obj streamer.
701 void AddValueSymbols(const MCExpr *Value) {
702 switch (Value->getKind()) {
704 // FIXME: What should we do in here?
707 case MCExpr::Constant:
710 case MCExpr::Binary: {
711 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
712 AddValueSymbols(BE->getLHS());
713 AddValueSymbols(BE->getRHS());
717 case MCExpr::SymbolRef:
718 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
722 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
728 typedef StringMap<State>::const_iterator const_iterator;
730 const_iterator begin() {
731 return Symbols.begin();
734 const_iterator end() {
735 return Symbols.end();
738 RecordStreamer(MCContext &Context)
739 : MCStreamer(SK_RecordStreamer, Context) {}
741 virtual void EmitInstruction(const MCInst &Inst) {
743 for (unsigned i = Inst.getNumOperands(); i--; )
744 if (Inst.getOperand(i).isExpr())
745 AddValueSymbols(Inst.getOperand(i).getExpr());
747 virtual void EmitLabel(MCSymbol *Symbol) {
748 Symbol->setSection(*getCurrentSection().first);
749 markDefined(*Symbol);
751 virtual void EmitDebugLabel(MCSymbol *Symbol) {
754 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
755 // FIXME: should we handle aliases?
756 markDefined(*Symbol);
758 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
759 if (Attribute == MCSA_Global)
762 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
763 uint64_t Size , unsigned ByteAlignment) {
764 markDefined(*Symbol);
766 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
767 unsigned ByteAlignment) {
768 markDefined(*Symbol);
771 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
772 virtual void EmitBundleLock(bool AlignToEnd) {}
773 virtual void EmitBundleUnlock() {}
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,
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() {}
812 static bool classof(const MCStreamer *S) {
813 return S->getKind() == SK_RecordStreamer;
816 } // end anonymous namespace
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())
825 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
826 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
828 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
829 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
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()));
839 errMsg = "target " + std::string(T.getName()) +
840 " does not define AsmParser.";
844 Parser->setTargetParser(*TAP);
845 if (Parser->Run(false))
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());
864 /// isDeclaration - Return 'true' if the global value is a declaration.
865 static bool isDeclaration(const GlobalValue &V) {
866 if (V.hasAvailableExternallyLinkage())
869 if (V.isMaterializable())
872 return V.isDeclaration();
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) {
879 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
880 if (isDeclaration(*f))
881 addPotentialUndefinedSymbol(f, true);
883 addDefinedFunctionSymbol(f);
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);
892 addDefinedDataSymbol(v);
896 if (addAsmGlobalSymbols(errMsg))
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);
906 addDefinedDataSymbol(a);
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);