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"),
124 static cl::opt<std::string>
125 TrapFuncName("trap-func", cl::Hidden,
126 cl::desc("Emit a call to trap function rather than a trap instruction"),
130 EnablePIE("enable-pie",
131 cl::desc("Assume the creation of a position independent executable."),
135 SegmentedStacks("segmented-stacks",
136 cl::desc("Use segmented stacks if possible."),
140 UseInitArray("use-init-array",
141 cl::desc("Use .init_array instead of .ctors."),
144 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
145 : _module(m), _target(t),
146 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
147 _mangler(_context, t) {}
149 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
151 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
152 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
153 sys::fs::file_magic::bitcode;
156 bool LTOModule::isBitcodeFile(const char *path) {
157 sys::fs::file_magic type;
158 if (sys::fs::identify_magic(path, type))
160 return type == sys::fs::file_magic::bitcode;
163 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
164 /// LLVM bitcode for the specified triple.
165 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
166 const char *triplePrefix) {
167 MemoryBuffer *buffer = makeBuffer(mem, length);
170 return isTargetMatch(buffer, triplePrefix);
173 bool LTOModule::isBitcodeFileForTarget(const char *path,
174 const char *triplePrefix) {
175 OwningPtr<MemoryBuffer> buffer;
176 if (MemoryBuffer::getFile(path, buffer))
178 return isTargetMatch(buffer.take(), triplePrefix);
181 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
183 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
184 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
186 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
189 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
191 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
192 OwningPtr<MemoryBuffer> buffer;
193 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
194 errMsg = ec.message();
197 return makeLTOModule(buffer.take(), errMsg);
200 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
201 size_t size, std::string &errMsg) {
202 return makeLTOModule(fd, path, size, 0, errMsg);
205 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
208 std::string &errMsg) {
209 OwningPtr<MemoryBuffer> buffer;
211 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
212 errMsg = ec.message();
215 return makeLTOModule(buffer.take(), errMsg);
218 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
219 std::string &errMsg) {
220 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
223 return makeLTOModule(buffer.take(), errMsg);
226 void LTOModule::getTargetOptions(TargetOptions &Options) {
227 Options.LessPreciseFPMADOption = EnableFPMAD;
228 Options.NoFramePointerElim = DisableFPElim;
229 Options.AllowFPOpFusion = FuseFPOps;
230 Options.UnsafeFPMath = EnableUnsafeFPMath;
231 Options.NoInfsFPMath = EnableNoInfsFPMath;
232 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
233 Options.HonorSignDependentRoundingFPMathOption =
234 EnableHonorSignDependentRoundingFPMath;
235 Options.UseSoftFloat = GenerateSoftFloatCalls;
236 if (FloatABIForCalls != FloatABI::Default)
237 Options.FloatABIType = FloatABIForCalls;
238 Options.NoZerosInBSS = DontPlaceZerosInBSS;
239 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
240 Options.DisableTailCalls = DisableTailCalls;
241 Options.StackAlignmentOverride = OverrideStackAlignment;
242 Options.TrapFuncName = TrapFuncName;
243 Options.PositionIndependentExecutable = EnablePIE;
244 Options.EnableSegmentedStacks = SegmentedStacks;
245 Options.UseInitArray = UseInitArray;
248 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
249 std::string &errMsg) {
250 static bool Initialized = false;
252 InitializeAllTargets();
253 InitializeAllTargetMCs();
254 InitializeAllAsmParsers();
258 // parse bitcode buffer
259 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
266 std::string TripleStr = m->getTargetTriple();
267 if (TripleStr.empty())
268 TripleStr = sys::getDefaultTargetTriple();
269 llvm::Triple Triple(TripleStr);
271 // find machine architecture for this module
272 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
276 // construct LTOModule, hand over ownership of module and target
277 SubtargetFeatures Features;
278 Features.getDefaultSubtargetFeatures(Triple);
279 std::string FeatureStr = Features.getString();
280 // Set a default CPU for Darwin triples.
282 if (Triple.isOSDarwin()) {
283 if (Triple.getArch() == llvm::Triple::x86_64)
285 else if (Triple.getArch() == llvm::Triple::x86)
288 TargetOptions Options;
289 getTargetOptions(Options);
290 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
292 LTOModule *Ret = new LTOModule(m.take(), target);
293 if (Ret->parseSymbols(errMsg)) {
301 /// makeBuffer - Create a MemoryBuffer from a memory range.
302 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
303 const char *startPtr = (const char*)mem;
304 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
307 /// objcClassNameFromExpression - Get string that the data pointer points to.
309 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
310 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
311 Constant *op = ce->getOperand(0);
312 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
313 Constant *cn = gvn->getInitializer();
314 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
315 if (ca->isCString()) {
316 name = ".objc_class_name_" + ca->getAsCString().str();
325 /// addObjCClass - Parse i386/ppc ObjC class data structure.
326 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
327 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
330 // second slot in __OBJC,__class is pointer to superclass name
331 std::string superclassName;
332 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
333 NameAndAttributes info;
334 StringMap<NameAndAttributes>::value_type &entry =
335 _undefines.GetOrCreateValue(superclassName);
336 if (!entry.getValue().name) {
337 const char *symbolName = entry.getKey().data();
338 info.name = symbolName;
339 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
340 info.isFunction = false;
342 entry.setValue(info);
346 // third slot in __OBJC,__class is pointer to class name
347 std::string className;
348 if (objcClassNameFromExpression(c->getOperand(2), className)) {
349 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
352 NameAndAttributes info;
353 info.name = entry.getKey().data();
354 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
355 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
356 info.isFunction = false;
358 _symbols.push_back(info);
362 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
363 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
364 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
367 // second slot in __OBJC,__category is pointer to target class name
368 std::string targetclassName;
369 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
372 NameAndAttributes info;
373 StringMap<NameAndAttributes>::value_type &entry =
374 _undefines.GetOrCreateValue(targetclassName);
376 if (entry.getValue().name)
379 const char *symbolName = entry.getKey().data();
380 info.name = symbolName;
381 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
382 info.isFunction = false;
384 entry.setValue(info);
387 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
388 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
389 std::string targetclassName;
390 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
393 NameAndAttributes info;
394 StringMap<NameAndAttributes>::value_type &entry =
395 _undefines.GetOrCreateValue(targetclassName);
396 if (entry.getValue().name)
399 const char *symbolName = entry.getKey().data();
400 info.name = symbolName;
401 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
402 info.isFunction = false;
404 entry.setValue(info);
407 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
408 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
409 // Add to list of defined symbols.
410 addDefinedSymbol(v, false);
412 if (!v->hasSection() /* || !isTargetDarwin */)
415 // Special case i386/ppc ObjC data structures in magic sections:
416 // The issue is that the old ObjC object format did some strange
417 // contortions to avoid real linker symbols. For instance, the
418 // ObjC class data structure is allocated statically in the executable
419 // that defines that class. That data structures contains a pointer to
420 // its superclass. But instead of just initializing that part of the
421 // struct to the address of its superclass, and letting the static and
422 // dynamic linkers do the rest, the runtime works by having that field
423 // instead point to a C-string that is the name of the superclass.
424 // At runtime the objc initialization updates that pointer and sets
425 // it to point to the actual super class. As far as the linker
426 // knows it is just a pointer to a string. But then someone wanted the
427 // linker to issue errors at build time if the superclass was not found.
428 // So they figured out a way in mach-o object format to use an absolute
429 // symbols (.objc_class_name_Foo = 0) and a floating reference
430 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
431 // a class was missing.
432 // The following synthesizes the implicit .objc_* symbols for the linker
433 // from the ObjC data structures generated by the front end.
435 // special case if this data blob is an ObjC class definition
436 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
437 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
442 // special case if this data blob is an ObjC category definition
443 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
444 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
449 // special case if this data blob is the list of referenced classes
450 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
451 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
457 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
458 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
459 // add to list of defined symbols
460 addDefinedSymbol(f, true);
463 /// addDefinedSymbol - Add a defined symbol to the list.
464 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
465 // ignore all llvm.* symbols
466 if (def->getName().startswith("llvm."))
469 // string is owned by _defines
470 SmallString<64> Buffer;
471 _mangler.getNameWithPrefix(Buffer, def, false);
473 // set alignment part log2() can have rounding errors
474 uint32_t align = def->getAlignment();
475 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
477 // set permissions part
479 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
481 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
482 if (gv && gv->isConstant())
483 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
485 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
488 // set definition part
489 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
490 def->hasLinkerPrivateWeakLinkage())
491 attr |= LTO_SYMBOL_DEFINITION_WEAK;
492 else if (def->hasCommonLinkage())
493 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
495 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
498 if (def->hasHiddenVisibility())
499 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
500 else if (def->hasProtectedVisibility())
501 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
502 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
503 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
504 def->hasLinkerPrivateWeakLinkage())
505 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
506 else if (def->hasLinkOnceODRAutoHideLinkage())
507 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
509 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
511 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
514 // fill information structure
515 NameAndAttributes info;
516 StringRef Name = entry.getKey();
517 info.name = Name.data();
518 assert(info.name[Name.size()] == '\0');
519 info.attributes = attr;
520 info.isFunction = isFunction;
523 // add to table of symbols
524 _symbols.push_back(info);
527 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
529 void LTOModule::addAsmGlobalSymbol(const char *name,
530 lto_symbol_attributes scope) {
531 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
533 // only add new define if not already defined
534 if (entry.getValue())
539 NameAndAttributes &info = _undefines[entry.getKey().data()];
541 if (info.symbol == 0) {
542 // FIXME: This is trying to take care of module ASM like this:
544 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
546 // but is gross and its mother dresses it funny. Have the ASM parser give us
547 // more details for this type of situation so that we're not guessing so
550 // fill information structure
551 info.name = entry.getKey().data();
553 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
554 info.isFunction = false;
557 // add to table of symbols
558 _symbols.push_back(info);
563 addDefinedFunctionSymbol(cast<Function>(info.symbol));
565 addDefinedDataSymbol(info.symbol);
567 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
568 _symbols.back().attributes |= scope;
571 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
573 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
574 StringMap<NameAndAttributes>::value_type &entry =
575 _undefines.GetOrCreateValue(name);
577 _asm_undefines.push_back(entry.getKey().data());
579 // we already have the symbol
580 if (entry.getValue().name)
583 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
584 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
585 NameAndAttributes info;
586 info.name = entry.getKey().data();
587 info.attributes = attr;
588 info.isFunction = false;
591 entry.setValue(info);
594 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
595 /// list to be resolved later.
597 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
598 // ignore all llvm.* symbols
599 if (decl->getName().startswith("llvm."))
602 // ignore all aliases
603 if (isa<GlobalAlias>(decl))
606 SmallString<64> name;
607 _mangler.getNameWithPrefix(name, decl, false);
609 StringMap<NameAndAttributes>::value_type &entry =
610 _undefines.GetOrCreateValue(name);
612 // we already have the symbol
613 if (entry.getValue().name)
616 NameAndAttributes info;
618 info.name = entry.getKey().data();
620 if (decl->hasExternalWeakLinkage())
621 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
623 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
625 info.isFunction = isFunc;
628 entry.setValue(info);
632 class RecordStreamer : public MCStreamer {
634 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
637 StringMap<State> Symbols;
639 void markDefined(const MCSymbol &Symbol) {
640 State &S = Symbols[Symbol.getName()];
653 void markGlobal(const MCSymbol &Symbol) {
654 State &S = Symbols[Symbol.getName()];
668 void markUsed(const MCSymbol &Symbol) {
669 State &S = Symbols[Symbol.getName()];
683 // FIXME: mostly copied for the obj streamer.
684 void AddValueSymbols(const MCExpr *Value) {
685 switch (Value->getKind()) {
687 // FIXME: What should we do in here?
690 case MCExpr::Constant:
693 case MCExpr::Binary: {
694 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
695 AddValueSymbols(BE->getLHS());
696 AddValueSymbols(BE->getRHS());
700 case MCExpr::SymbolRef:
701 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
705 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
711 typedef StringMap<State>::const_iterator const_iterator;
713 const_iterator begin() {
714 return Symbols.begin();
717 const_iterator end() {
718 return Symbols.end();
721 RecordStreamer(MCContext &Context)
722 : MCStreamer(SK_RecordStreamer, Context) {}
724 virtual void EmitInstruction(const MCInst &Inst) {
726 for (unsigned i = Inst.getNumOperands(); i--; )
727 if (Inst.getOperand(i).isExpr())
728 AddValueSymbols(Inst.getOperand(i).getExpr());
730 virtual void EmitLabel(MCSymbol *Symbol) {
731 Symbol->setSection(*getCurrentSection().first);
732 markDefined(*Symbol);
734 virtual void EmitDebugLabel(MCSymbol *Symbol) {
737 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
738 // FIXME: should we handle aliases?
739 markDefined(*Symbol);
741 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
742 if (Attribute == MCSA_Global)
745 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
746 uint64_t Size , unsigned ByteAlignment) {
747 markDefined(*Symbol);
749 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
750 unsigned ByteAlignment) {
751 markDefined(*Symbol);
754 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
755 virtual void EmitBundleLock(bool AlignToEnd) {}
756 virtual void EmitBundleUnlock() {}
759 virtual void ChangeSection(const MCSection *Section,
760 const MCExpr *Subsection) {}
761 virtual void InitToTextSection() {}
762 virtual void InitSections() {}
763 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
764 virtual void EmitThumbFunc(MCSymbol *Func) {}
765 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
766 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
767 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
768 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
769 virtual void EmitCOFFSymbolType(int Type) {}
770 virtual void EndCOFFSymbolDef() {}
771 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
772 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
773 unsigned ByteAlignment) {}
774 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
775 uint64_t Size, unsigned ByteAlignment) {}
776 virtual void EmitBytes(StringRef Data) {}
777 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
778 virtual void EmitULEB128Value(const MCExpr *Value) {}
779 virtual void EmitSLEB128Value(const MCExpr *Value) {}
780 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
782 unsigned MaxBytesToEmit) {}
783 virtual void EmitCodeAlignment(unsigned ByteAlignment,
784 unsigned MaxBytesToEmit) {}
785 virtual bool EmitValueToOffset(const MCExpr *Offset,
786 unsigned char Value ) { return false; }
787 virtual void EmitFileDirective(StringRef Filename) {}
788 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
789 const MCSymbol *LastLabel,
790 const MCSymbol *Label,
791 unsigned PointerSize) {}
792 virtual void FinishImpl() {}
794 static bool classof(const MCStreamer *S) {
795 return S->getKind() == SK_RecordStreamer;
798 } // end anonymous namespace
800 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
801 /// defined or undefined lists.
802 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
803 const std::string &inlineAsm = _module->getModuleInlineAsm();
804 if (inlineAsm.empty())
807 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
808 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
810 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
811 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
813 *_target->getMCAsmInfo()));
814 const Target &T = _target->getTarget();
815 OwningPtr<MCSubtargetInfo>
816 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
817 _target->getTargetCPU(),
818 _target->getTargetFeatureString()));
819 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
821 errMsg = "target " + std::string(T.getName()) +
822 " does not define AsmParser.";
826 Parser->setTargetParser(*TAP);
827 if (Parser->Run(false))
830 for (RecordStreamer::const_iterator i = Streamer->begin(),
831 e = Streamer->end(); i != e; ++i) {
832 StringRef Key = i->first();
833 RecordStreamer::State Value = i->second;
834 if (Value == RecordStreamer::DefinedGlobal)
835 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
836 else if (Value == RecordStreamer::Defined)
837 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
838 else if (Value == RecordStreamer::Global ||
839 Value == RecordStreamer::Used)
840 addAsmGlobalSymbolUndef(Key.data());
846 /// isDeclaration - Return 'true' if the global value is a declaration.
847 static bool isDeclaration(const GlobalValue &V) {
848 if (V.hasAvailableExternallyLinkage())
851 if (V.isMaterializable())
854 return V.isDeclaration();
857 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
858 /// them to either the defined or undefined lists.
859 bool LTOModule::parseSymbols(std::string &errMsg) {
861 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
862 if (isDeclaration(*f))
863 addPotentialUndefinedSymbol(f, true);
865 addDefinedFunctionSymbol(f);
869 for (Module::global_iterator v = _module->global_begin(),
870 e = _module->global_end(); v != e; ++v) {
871 if (isDeclaration(*v))
872 addPotentialUndefinedSymbol(v, false);
874 addDefinedDataSymbol(v);
878 if (addAsmGlobalSymbols(errMsg))
882 for (Module::alias_iterator a = _module->alias_begin(),
883 e = _module->alias_end(); a != e; ++a) {
884 if (isDeclaration(*a->getAliasedGlobal()))
885 // Is an alias to a declaration.
886 addPotentialUndefinedSymbol(a, false);
888 addDefinedDataSymbol(a);
891 // make symbols for all undefines
892 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
893 e = _undefines.end(); u != e; ++u) {
894 // If this symbol also has a definition, then don't make an undefine because
895 // it is a tentative definition.
896 if (_defines.count(u->getKey())) continue;
897 NameAndAttributes info = u->getValue();
898 _symbols.push_back(info);