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/SourceMgr.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
43 EnableFPMAD("enable-fp-mad",
44 cl::desc("Enable less precise MAD instructions to be generated"),
48 DisableFPElim("disable-fp-elim",
49 cl::desc("Disable frame pointer elimination optimization"),
53 EnableUnsafeFPMath("enable-unsafe-fp-math",
54 cl::desc("Enable optimizations that may decrease FP precision"),
58 EnableNoInfsFPMath("enable-no-infs-fp-math",
59 cl::desc("Enable FP math optimizations that assume no +-Infs"),
63 EnableNoNaNsFPMath("enable-no-nans-fp-math",
64 cl::desc("Enable FP math optimizations that assume no NaNs"),
68 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
70 cl::desc("Force codegen to assume rounding mode can change dynamically"),
74 GenerateSoftFloatCalls("soft-float",
75 cl::desc("Generate software floating point library calls"),
78 static cl::opt<llvm::FloatABI::ABIType>
79 FloatABIForCalls("float-abi",
80 cl::desc("Choose float ABI type"),
81 cl::init(FloatABI::Default),
83 clEnumValN(FloatABI::Default, "default",
84 "Target default float ABI type"),
85 clEnumValN(FloatABI::Soft, "soft",
86 "Soft float ABI (implied by -soft-float)"),
87 clEnumValN(FloatABI::Hard, "hard",
88 "Hard float ABI (uses FP registers)"),
91 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
92 FuseFPOps("fp-contract",
93 cl::desc("Enable aggresive formation of fused FP ops"),
94 cl::init(FPOpFusion::Standard),
96 clEnumValN(FPOpFusion::Fast, "fast",
97 "Fuse FP ops whenever profitable"),
98 clEnumValN(FPOpFusion::Standard, "on",
99 "Only fuse 'blessed' FP ops."),
100 clEnumValN(FPOpFusion::Strict, "off",
101 "Only fuse FP ops when the result won't be effected."),
105 DontPlaceZerosInBSS("nozero-initialized-in-bss",
106 cl::desc("Don't place zero-initialized symbols into bss section"),
110 EnableGuaranteedTailCallOpt("tailcallopt",
111 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
115 DisableTailCalls("disable-tail-calls",
116 cl::desc("Never emit tail calls"),
119 static cl::opt<unsigned>
120 OverrideStackAlignment("stack-alignment",
121 cl::desc("Override default stack alignment"),
125 EnableRealignStack("realign-stack",
126 cl::desc("Realign stack if needed"),
129 static cl::opt<std::string>
130 TrapFuncName("trap-func", cl::Hidden,
131 cl::desc("Emit a call to trap function rather than a trap instruction"),
135 EnablePIE("enable-pie",
136 cl::desc("Assume the creation of a position independent executable."),
140 SegmentedStacks("segmented-stacks",
141 cl::desc("Use segmented stacks if possible."),
145 UseInitArray("use-init-array",
146 cl::desc("Use .init_array instead of .ctors."),
149 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
150 : _module(m), _target(t),
151 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
152 _mangler(_context, t) {}
154 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
156 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
157 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
158 sys::fs::file_magic::bitcode;
161 bool LTOModule::isBitcodeFile(const char *path) {
162 sys::fs::file_magic type;
163 if (sys::fs::identify_magic(path, type))
165 return type == sys::fs::file_magic::bitcode;
168 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
169 /// LLVM bitcode for the specified triple.
170 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
171 const char *triplePrefix) {
172 MemoryBuffer *buffer = makeBuffer(mem, length);
175 return isTargetMatch(buffer, triplePrefix);
178 bool LTOModule::isBitcodeFileForTarget(const char *path,
179 const char *triplePrefix) {
180 OwningPtr<MemoryBuffer> buffer;
181 if (MemoryBuffer::getFile(path, buffer))
183 return isTargetMatch(buffer.take(), triplePrefix);
186 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
188 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
189 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
191 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
194 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
196 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
197 OwningPtr<MemoryBuffer> buffer;
198 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
199 errMsg = ec.message();
202 return makeLTOModule(buffer.take(), errMsg);
205 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
206 size_t size, std::string &errMsg) {
207 return makeLTOModule(fd, path, size, 0, errMsg);
210 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
213 std::string &errMsg) {
214 OwningPtr<MemoryBuffer> buffer;
216 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
217 errMsg = ec.message();
220 return makeLTOModule(buffer.take(), errMsg);
223 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
224 std::string &errMsg) {
225 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
228 return makeLTOModule(buffer.take(), errMsg);
231 void LTOModule::getTargetOptions(TargetOptions &Options) {
232 Options.LessPreciseFPMADOption = EnableFPMAD;
233 Options.NoFramePointerElim = DisableFPElim;
234 Options.AllowFPOpFusion = FuseFPOps;
235 Options.UnsafeFPMath = EnableUnsafeFPMath;
236 Options.NoInfsFPMath = EnableNoInfsFPMath;
237 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
238 Options.HonorSignDependentRoundingFPMathOption =
239 EnableHonorSignDependentRoundingFPMath;
240 Options.UseSoftFloat = GenerateSoftFloatCalls;
241 if (FloatABIForCalls != FloatABI::Default)
242 Options.FloatABIType = FloatABIForCalls;
243 Options.NoZerosInBSS = DontPlaceZerosInBSS;
244 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
245 Options.DisableTailCalls = DisableTailCalls;
246 Options.StackAlignmentOverride = OverrideStackAlignment;
247 Options.RealignStack = EnableRealignStack;
248 Options.TrapFuncName = TrapFuncName;
249 Options.PositionIndependentExecutable = EnablePIE;
250 Options.EnableSegmentedStacks = SegmentedStacks;
251 Options.UseInitArray = UseInitArray;
254 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
255 std::string &errMsg) {
256 static bool Initialized = false;
258 InitializeAllTargets();
259 InitializeAllTargetMCs();
260 InitializeAllAsmParsers();
264 // parse bitcode buffer
265 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
272 std::string TripleStr = m->getTargetTriple();
273 if (TripleStr.empty())
274 TripleStr = sys::getDefaultTargetTriple();
275 llvm::Triple Triple(TripleStr);
277 // find machine architecture for this module
278 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
282 // construct LTOModule, hand over ownership of module and target
283 SubtargetFeatures Features;
284 Features.getDefaultSubtargetFeatures(Triple);
285 std::string FeatureStr = Features.getString();
286 // Set a default CPU for Darwin triples.
288 if (Triple.isOSDarwin()) {
289 if (Triple.getArch() == llvm::Triple::x86_64)
291 else if (Triple.getArch() == llvm::Triple::x86)
294 TargetOptions Options;
295 getTargetOptions(Options);
296 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
298 LTOModule *Ret = new LTOModule(m.take(), target);
299 if (Ret->parseSymbols(errMsg)) {
307 /// makeBuffer - Create a MemoryBuffer from a memory range.
308 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
309 const char *startPtr = (const char*)mem;
310 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
313 /// objcClassNameFromExpression - Get string that the data pointer points to.
315 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
316 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
317 Constant *op = ce->getOperand(0);
318 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
319 Constant *cn = gvn->getInitializer();
320 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
321 if (ca->isCString()) {
322 name = ".objc_class_name_" + ca->getAsCString().str();
331 /// addObjCClass - Parse i386/ppc ObjC class data structure.
332 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
333 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
336 // second slot in __OBJC,__class is pointer to superclass name
337 std::string superclassName;
338 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
339 NameAndAttributes info;
340 StringMap<NameAndAttributes>::value_type &entry =
341 _undefines.GetOrCreateValue(superclassName);
342 if (!entry.getValue().name) {
343 const char *symbolName = entry.getKey().data();
344 info.name = symbolName;
345 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
346 info.isFunction = false;
348 entry.setValue(info);
352 // third slot in __OBJC,__class is pointer to class name
353 std::string className;
354 if (objcClassNameFromExpression(c->getOperand(2), className)) {
355 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
358 NameAndAttributes info;
359 info.name = entry.getKey().data();
360 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
361 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
362 info.isFunction = false;
364 _symbols.push_back(info);
368 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
369 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
370 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
373 // second slot in __OBJC,__category is pointer to target class name
374 std::string targetclassName;
375 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
378 NameAndAttributes info;
379 StringMap<NameAndAttributes>::value_type &entry =
380 _undefines.GetOrCreateValue(targetclassName);
382 if (entry.getValue().name)
385 const char *symbolName = entry.getKey().data();
386 info.name = symbolName;
387 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
388 info.isFunction = false;
390 entry.setValue(info);
393 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
394 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
395 std::string targetclassName;
396 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
399 NameAndAttributes info;
400 StringMap<NameAndAttributes>::value_type &entry =
401 _undefines.GetOrCreateValue(targetclassName);
402 if (entry.getValue().name)
405 const char *symbolName = entry.getKey().data();
406 info.name = symbolName;
407 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
408 info.isFunction = false;
410 entry.setValue(info);
413 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
414 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
415 // Add to list of defined symbols.
416 addDefinedSymbol(v, false);
418 if (!v->hasSection() /* || !isTargetDarwin */)
421 // Special case i386/ppc ObjC data structures in magic sections:
422 // The issue is that the old ObjC object format did some strange
423 // contortions to avoid real linker symbols. For instance, the
424 // ObjC class data structure is allocated statically in the executable
425 // that defines that class. That data structures contains a pointer to
426 // its superclass. But instead of just initializing that part of the
427 // struct to the address of its superclass, and letting the static and
428 // dynamic linkers do the rest, the runtime works by having that field
429 // instead point to a C-string that is the name of the superclass.
430 // At runtime the objc initialization updates that pointer and sets
431 // it to point to the actual super class. As far as the linker
432 // knows it is just a pointer to a string. But then someone wanted the
433 // linker to issue errors at build time if the superclass was not found.
434 // So they figured out a way in mach-o object format to use an absolute
435 // symbols (.objc_class_name_Foo = 0) and a floating reference
436 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
437 // a class was missing.
438 // The following synthesizes the implicit .objc_* symbols for the linker
439 // from the ObjC data structures generated by the front end.
441 // special case if this data blob is an ObjC class definition
442 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
443 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
448 // special case if this data blob is an ObjC category definition
449 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
450 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
455 // special case if this data blob is the list of referenced classes
456 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
457 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
463 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
464 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
465 // add to list of defined symbols
466 addDefinedSymbol(f, true);
469 /// addDefinedSymbol - Add a defined symbol to the list.
470 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
471 // ignore all llvm.* symbols
472 if (def->getName().startswith("llvm."))
475 // string is owned by _defines
476 SmallString<64> Buffer;
477 _mangler.getNameWithPrefix(Buffer, def, false);
479 // set alignment part log2() can have rounding errors
480 uint32_t align = def->getAlignment();
481 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
483 // set permissions part
485 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
487 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
488 if (gv && gv->isConstant())
489 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
491 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
494 // set definition part
495 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
496 def->hasLinkerPrivateWeakLinkage())
497 attr |= LTO_SYMBOL_DEFINITION_WEAK;
498 else if (def->hasCommonLinkage())
499 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
501 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
504 if (def->hasHiddenVisibility())
505 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
506 else if (def->hasProtectedVisibility())
507 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
508 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
509 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
510 def->hasLinkerPrivateWeakLinkage())
511 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
512 else if (def->hasLinkOnceODRAutoHideLinkage())
513 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
515 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
517 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
520 // fill information structure
521 NameAndAttributes info;
522 StringRef Name = entry.getKey();
523 info.name = Name.data();
524 assert(info.name[Name.size()] == '\0');
525 info.attributes = attr;
526 info.isFunction = isFunction;
529 // add to table of symbols
530 _symbols.push_back(info);
533 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
535 void LTOModule::addAsmGlobalSymbol(const char *name,
536 lto_symbol_attributes scope) {
537 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
539 // only add new define if not already defined
540 if (entry.getValue())
545 NameAndAttributes &info = _undefines[entry.getKey().data()];
547 if (info.symbol == 0) {
548 // FIXME: This is trying to take care of module ASM like this:
550 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
552 // but is gross and its mother dresses it funny. Have the ASM parser give us
553 // more details for this type of situation so that we're not guessing so
556 // fill information structure
557 info.name = entry.getKey().data();
559 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
560 info.isFunction = false;
563 // add to table of symbols
564 _symbols.push_back(info);
569 addDefinedFunctionSymbol(cast<Function>(info.symbol));
571 addDefinedDataSymbol(info.symbol);
573 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
574 _symbols.back().attributes |= scope;
577 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
579 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
580 StringMap<NameAndAttributes>::value_type &entry =
581 _undefines.GetOrCreateValue(name);
583 _asm_undefines.push_back(entry.getKey().data());
585 // we already have the symbol
586 if (entry.getValue().name)
589 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
590 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
591 NameAndAttributes info;
592 info.name = entry.getKey().data();
593 info.attributes = attr;
594 info.isFunction = false;
597 entry.setValue(info);
600 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
601 /// list to be resolved later.
603 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
604 // ignore all llvm.* symbols
605 if (decl->getName().startswith("llvm."))
608 // ignore all aliases
609 if (isa<GlobalAlias>(decl))
612 SmallString<64> name;
613 _mangler.getNameWithPrefix(name, decl, false);
615 StringMap<NameAndAttributes>::value_type &entry =
616 _undefines.GetOrCreateValue(name);
618 // we already have the symbol
619 if (entry.getValue().name)
622 NameAndAttributes info;
624 info.name = entry.getKey().data();
626 if (decl->hasExternalWeakLinkage())
627 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
629 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
631 info.isFunction = isFunc;
634 entry.setValue(info);
638 class RecordStreamer : public MCStreamer {
640 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
643 StringMap<State> Symbols;
645 void markDefined(const MCSymbol &Symbol) {
646 State &S = Symbols[Symbol.getName()];
659 void markGlobal(const MCSymbol &Symbol) {
660 State &S = Symbols[Symbol.getName()];
674 void markUsed(const MCSymbol &Symbol) {
675 State &S = Symbols[Symbol.getName()];
689 // FIXME: mostly copied for the obj streamer.
690 void AddValueSymbols(const MCExpr *Value) {
691 switch (Value->getKind()) {
693 // FIXME: What should we do in here?
696 case MCExpr::Constant:
699 case MCExpr::Binary: {
700 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
701 AddValueSymbols(BE->getLHS());
702 AddValueSymbols(BE->getRHS());
706 case MCExpr::SymbolRef:
707 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
711 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
717 typedef StringMap<State>::const_iterator const_iterator;
719 const_iterator begin() {
720 return Symbols.begin();
723 const_iterator end() {
724 return Symbols.end();
727 RecordStreamer(MCContext &Context)
728 : MCStreamer(SK_RecordStreamer, Context) {}
730 virtual void EmitInstruction(const MCInst &Inst) {
732 for (unsigned i = Inst.getNumOperands(); i--; )
733 if (Inst.getOperand(i).isExpr())
734 AddValueSymbols(Inst.getOperand(i).getExpr());
736 virtual void EmitLabel(MCSymbol *Symbol) {
737 Symbol->setSection(*getCurrentSection().first);
738 markDefined(*Symbol);
740 virtual void EmitDebugLabel(MCSymbol *Symbol) {
743 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
744 // FIXME: should we handle aliases?
745 markDefined(*Symbol);
747 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
748 if (Attribute == MCSA_Global)
751 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
752 uint64_t Size , unsigned ByteAlignment) {
753 markDefined(*Symbol);
755 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
756 unsigned ByteAlignment) {
757 markDefined(*Symbol);
760 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
761 virtual void EmitBundleLock(bool AlignToEnd) {}
762 virtual void EmitBundleUnlock() {}
765 virtual void ChangeSection(const MCSection *Section,
766 const MCExpr *Subsection) {}
767 virtual void InitToTextSection() {}
768 virtual void InitSections() {}
769 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
770 virtual void EmitThumbFunc(MCSymbol *Func) {}
771 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
772 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
773 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
774 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
775 virtual void EmitCOFFSymbolType(int Type) {}
776 virtual void EndCOFFSymbolDef() {}
777 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
778 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
779 unsigned ByteAlignment) {}
780 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
781 uint64_t Size, unsigned ByteAlignment) {}
782 virtual void EmitBytes(StringRef Data) {}
783 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
784 virtual void EmitULEB128Value(const MCExpr *Value) {}
785 virtual void EmitSLEB128Value(const MCExpr *Value) {}
786 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
788 unsigned MaxBytesToEmit) {}
789 virtual void EmitCodeAlignment(unsigned ByteAlignment,
790 unsigned MaxBytesToEmit) {}
791 virtual bool EmitValueToOffset(const MCExpr *Offset,
792 unsigned char Value ) { return false; }
793 virtual void EmitFileDirective(StringRef Filename) {}
794 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
795 const MCSymbol *LastLabel,
796 const MCSymbol *Label,
797 unsigned PointerSize) {}
798 virtual void FinishImpl() {}
800 static bool classof(const MCStreamer *S) {
801 return S->getKind() == SK_RecordStreamer;
804 } // end anonymous namespace
806 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
807 /// defined or undefined lists.
808 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
809 const std::string &inlineAsm = _module->getModuleInlineAsm();
810 if (inlineAsm.empty())
813 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
814 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
816 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
817 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
819 *_target->getMCAsmInfo()));
820 const Target &T = _target->getTarget();
821 OwningPtr<MCSubtargetInfo>
822 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
823 _target->getTargetCPU(),
824 _target->getTargetFeatureString()));
825 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
827 errMsg = "target " + std::string(T.getName()) +
828 " does not define AsmParser.";
832 Parser->setTargetParser(*TAP);
833 if (Parser->Run(false))
836 for (RecordStreamer::const_iterator i = Streamer->begin(),
837 e = Streamer->end(); i != e; ++i) {
838 StringRef Key = i->first();
839 RecordStreamer::State Value = i->second;
840 if (Value == RecordStreamer::DefinedGlobal)
841 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
842 else if (Value == RecordStreamer::Defined)
843 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
844 else if (Value == RecordStreamer::Global ||
845 Value == RecordStreamer::Used)
846 addAsmGlobalSymbolUndef(Key.data());
852 /// isDeclaration - Return 'true' if the global value is a declaration.
853 static bool isDeclaration(const GlobalValue &V) {
854 if (V.hasAvailableExternallyLinkage())
857 if (V.isMaterializable())
860 return V.isDeclaration();
863 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
864 /// them to either the defined or undefined lists.
865 bool LTOModule::parseSymbols(std::string &errMsg) {
867 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
868 if (isDeclaration(*f))
869 addPotentialUndefinedSymbol(f, true);
871 addDefinedFunctionSymbol(f);
875 for (Module::global_iterator v = _module->global_begin(),
876 e = _module->global_end(); v != e; ++v) {
877 if (isDeclaration(*v))
878 addPotentialUndefinedSymbol(v, false);
880 addDefinedDataSymbol(v);
884 if (addAsmGlobalSymbols(errMsg))
888 for (Module::alias_iterator a = _module->alias_begin(),
889 e = _module->alias_end(); a != e; ++a) {
890 if (isDeclaration(*a->getAliasedGlobal()))
891 // Is an alias to a declaration.
892 addPotentialUndefinedSymbol(a, false);
894 addDefinedDataSymbol(a);
897 // make symbols for all undefines
898 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
899 e = _undefines.end(); u != e; ++u) {
900 // If this symbol also has a definition, then don't make an undefine because
901 // it is a tentative definition.
902 if (_defines.count(u->getKey())) continue;
903 NameAndAttributes info = u->getValue();
904 _symbols.push_back(info);