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 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
54 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
58 EnableUnsafeFPMath("enable-unsafe-fp-math",
59 cl::desc("Enable optimizations that may decrease FP precision"),
63 EnableNoInfsFPMath("enable-no-infs-fp-math",
64 cl::desc("Enable FP math optimizations that assume no +-Infs"),
68 EnableNoNaNsFPMath("enable-no-nans-fp-math",
69 cl::desc("Enable FP math optimizations that assume no NaNs"),
73 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
75 cl::desc("Force codegen to assume rounding mode can change dynamically"),
79 GenerateSoftFloatCalls("soft-float",
80 cl::desc("Generate software floating point library calls"),
83 static cl::opt<llvm::FloatABI::ABIType>
84 FloatABIForCalls("float-abi",
85 cl::desc("Choose float ABI type"),
86 cl::init(FloatABI::Default),
88 clEnumValN(FloatABI::Default, "default",
89 "Target default float ABI type"),
90 clEnumValN(FloatABI::Soft, "soft",
91 "Soft float ABI (implied by -soft-float)"),
92 clEnumValN(FloatABI::Hard, "hard",
93 "Hard float ABI (uses FP registers)"),
96 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
97 FuseFPOps("fp-contract",
98 cl::desc("Enable aggresive formation of fused FP ops"),
99 cl::init(FPOpFusion::Standard),
101 clEnumValN(FPOpFusion::Fast, "fast",
102 "Fuse FP ops whenever profitable"),
103 clEnumValN(FPOpFusion::Standard, "on",
104 "Only fuse 'blessed' FP ops."),
105 clEnumValN(FPOpFusion::Strict, "off",
106 "Only fuse FP ops when the result won't be effected."),
110 DontPlaceZerosInBSS("nozero-initialized-in-bss",
111 cl::desc("Don't place zero-initialized symbols into bss section"),
115 EnableGuaranteedTailCallOpt("tailcallopt",
116 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
120 DisableTailCalls("disable-tail-calls",
121 cl::desc("Never emit tail calls"),
124 static cl::opt<unsigned>
125 OverrideStackAlignment("stack-alignment",
126 cl::desc("Override default stack alignment"),
130 EnableRealignStack("realign-stack",
131 cl::desc("Realign stack if needed"),
134 static cl::opt<std::string>
135 TrapFuncName("trap-func", cl::Hidden,
136 cl::desc("Emit a call to trap function rather than a trap instruction"),
140 EnablePIE("enable-pie",
141 cl::desc("Assume the creation of a position independent executable."),
145 SegmentedStacks("segmented-stacks",
146 cl::desc("Use segmented stacks if possible."),
150 UseInitArray("use-init-array",
151 cl::desc("Use .init_array instead of .ctors."),
154 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
155 : _module(m), _target(t),
156 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
157 _mangler(_context, t) {}
159 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
161 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
162 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
163 sys::fs::file_magic::bitcode;
166 bool LTOModule::isBitcodeFile(const char *path) {
167 sys::fs::file_magic type;
168 if (sys::fs::identify_magic(path, type))
170 return type == sys::fs::file_magic::bitcode;
173 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
174 /// LLVM bitcode for the specified triple.
175 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
176 const char *triplePrefix) {
177 MemoryBuffer *buffer = makeBuffer(mem, length);
180 return isTargetMatch(buffer, triplePrefix);
183 bool LTOModule::isBitcodeFileForTarget(const char *path,
184 const char *triplePrefix) {
185 OwningPtr<MemoryBuffer> buffer;
186 if (MemoryBuffer::getFile(path, buffer))
188 return isTargetMatch(buffer.take(), triplePrefix);
191 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
193 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
194 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
196 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
199 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
201 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
202 OwningPtr<MemoryBuffer> buffer;
203 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
204 errMsg = ec.message();
207 return makeLTOModule(buffer.take(), errMsg);
210 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
211 size_t size, std::string &errMsg) {
212 return makeLTOModule(fd, path, size, size, 0, errMsg);
215 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
219 std::string &errMsg) {
220 OwningPtr<MemoryBuffer> buffer;
221 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
222 map_size, offset, false)) {
223 errMsg = ec.message();
226 return makeLTOModule(buffer.take(), errMsg);
229 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
230 std::string &errMsg) {
231 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
234 return makeLTOModule(buffer.take(), errMsg);
237 void LTOModule::getTargetOptions(TargetOptions &Options) {
238 Options.LessPreciseFPMADOption = EnableFPMAD;
239 Options.NoFramePointerElim = DisableFPElim;
240 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
241 Options.AllowFPOpFusion = FuseFPOps;
242 Options.UnsafeFPMath = EnableUnsafeFPMath;
243 Options.NoInfsFPMath = EnableNoInfsFPMath;
244 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
245 Options.HonorSignDependentRoundingFPMathOption =
246 EnableHonorSignDependentRoundingFPMath;
247 Options.UseSoftFloat = GenerateSoftFloatCalls;
248 if (FloatABIForCalls != FloatABI::Default)
249 Options.FloatABIType = FloatABIForCalls;
250 Options.NoZerosInBSS = DontPlaceZerosInBSS;
251 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
252 Options.DisableTailCalls = DisableTailCalls;
253 Options.StackAlignmentOverride = OverrideStackAlignment;
254 Options.RealignStack = EnableRealignStack;
255 Options.TrapFuncName = TrapFuncName;
256 Options.PositionIndependentExecutable = EnablePIE;
257 Options.EnableSegmentedStacks = SegmentedStacks;
258 Options.UseInitArray = UseInitArray;
261 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
262 std::string &errMsg) {
263 static bool Initialized = false;
265 InitializeAllTargets();
266 InitializeAllTargetMCs();
267 InitializeAllAsmParsers();
271 // parse bitcode buffer
272 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
279 std::string TripleStr = m->getTargetTriple();
280 if (TripleStr.empty())
281 TripleStr = sys::getDefaultTargetTriple();
282 llvm::Triple Triple(TripleStr);
284 // find machine architecture for this module
285 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
289 // construct LTOModule, hand over ownership of module and target
290 SubtargetFeatures Features;
291 Features.getDefaultSubtargetFeatures(Triple);
292 std::string FeatureStr = Features.getString();
293 // Set a default CPU for Darwin triples.
295 if (Triple.isOSDarwin()) {
296 if (Triple.getArch() == llvm::Triple::x86_64)
298 else if (Triple.getArch() == llvm::Triple::x86)
301 TargetOptions Options;
302 getTargetOptions(Options);
303 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
305 LTOModule *Ret = new LTOModule(m.take(), target);
306 if (Ret->parseSymbols(errMsg)) {
314 /// makeBuffer - Create a MemoryBuffer from a memory range.
315 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
316 const char *startPtr = (const char*)mem;
317 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
320 /// objcClassNameFromExpression - Get string that the data pointer points to.
322 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
323 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
324 Constant *op = ce->getOperand(0);
325 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
326 Constant *cn = gvn->getInitializer();
327 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
328 if (ca->isCString()) {
329 name = ".objc_class_name_" + ca->getAsCString().str();
338 /// addObjCClass - Parse i386/ppc ObjC class data structure.
339 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
340 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
343 // second slot in __OBJC,__class is pointer to superclass name
344 std::string superclassName;
345 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
346 NameAndAttributes info;
347 StringMap<NameAndAttributes>::value_type &entry =
348 _undefines.GetOrCreateValue(superclassName);
349 if (!entry.getValue().name) {
350 const char *symbolName = entry.getKey().data();
351 info.name = symbolName;
352 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
353 info.isFunction = false;
355 entry.setValue(info);
359 // third slot in __OBJC,__class is pointer to class name
360 std::string className;
361 if (objcClassNameFromExpression(c->getOperand(2), className)) {
362 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
365 NameAndAttributes info;
366 info.name = entry.getKey().data();
367 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
368 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
369 info.isFunction = false;
371 _symbols.push_back(info);
375 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
376 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
377 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
380 // second slot in __OBJC,__category is pointer to target class name
381 std::string targetclassName;
382 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
385 NameAndAttributes info;
386 StringMap<NameAndAttributes>::value_type &entry =
387 _undefines.GetOrCreateValue(targetclassName);
389 if (entry.getValue().name)
392 const char *symbolName = entry.getKey().data();
393 info.name = symbolName;
394 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
395 info.isFunction = false;
397 entry.setValue(info);
400 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
401 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
402 std::string targetclassName;
403 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
406 NameAndAttributes info;
407 StringMap<NameAndAttributes>::value_type &entry =
408 _undefines.GetOrCreateValue(targetclassName);
409 if (entry.getValue().name)
412 const char *symbolName = entry.getKey().data();
413 info.name = symbolName;
414 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
415 info.isFunction = false;
417 entry.setValue(info);
420 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
421 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
422 // Add to list of defined symbols.
423 addDefinedSymbol(v, false);
425 if (!v->hasSection() /* || !isTargetDarwin */)
428 // Special case i386/ppc ObjC data structures in magic sections:
429 // The issue is that the old ObjC object format did some strange
430 // contortions to avoid real linker symbols. For instance, the
431 // ObjC class data structure is allocated statically in the executable
432 // that defines that class. That data structures contains a pointer to
433 // its superclass. But instead of just initializing that part of the
434 // struct to the address of its superclass, and letting the static and
435 // dynamic linkers do the rest, the runtime works by having that field
436 // instead point to a C-string that is the name of the superclass.
437 // At runtime the objc initialization updates that pointer and sets
438 // it to point to the actual super class. As far as the linker
439 // knows it is just a pointer to a string. But then someone wanted the
440 // linker to issue errors at build time if the superclass was not found.
441 // So they figured out a way in mach-o object format to use an absolute
442 // symbols (.objc_class_name_Foo = 0) and a floating reference
443 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
444 // a class was missing.
445 // The following synthesizes the implicit .objc_* symbols for the linker
446 // from the ObjC data structures generated by the front end.
448 // special case if this data blob is an ObjC class definition
449 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
450 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
455 // special case if this data blob is an ObjC category definition
456 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
457 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
462 // special case if this data blob is the list of referenced classes
463 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
464 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
470 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
471 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
472 // add to list of defined symbols
473 addDefinedSymbol(f, true);
476 /// addDefinedSymbol - Add a defined symbol to the list.
477 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
478 // ignore all llvm.* symbols
479 if (def->getName().startswith("llvm."))
482 // string is owned by _defines
483 SmallString<64> Buffer;
484 _mangler.getNameWithPrefix(Buffer, def, false);
486 // set alignment part log2() can have rounding errors
487 uint32_t align = def->getAlignment();
488 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
490 // set permissions part
492 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
494 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
495 if (gv && gv->isConstant())
496 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
498 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
501 // set definition part
502 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
503 def->hasLinkerPrivateWeakLinkage())
504 attr |= LTO_SYMBOL_DEFINITION_WEAK;
505 else if (def->hasCommonLinkage())
506 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
508 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
511 if (def->hasHiddenVisibility())
512 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
513 else if (def->hasProtectedVisibility())
514 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
515 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
516 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
517 def->hasLinkerPrivateWeakLinkage())
518 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
519 else if (def->hasLinkOnceODRAutoHideLinkage())
520 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
522 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
524 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
527 // fill information structure
528 NameAndAttributes info;
529 StringRef Name = entry.getKey();
530 info.name = Name.data();
531 assert(info.name[Name.size()] == '\0');
532 info.attributes = attr;
533 info.isFunction = isFunction;
536 // add to table of symbols
537 _symbols.push_back(info);
540 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
542 void LTOModule::addAsmGlobalSymbol(const char *name,
543 lto_symbol_attributes scope) {
544 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
546 // only add new define if not already defined
547 if (entry.getValue())
552 NameAndAttributes &info = _undefines[entry.getKey().data()];
554 if (info.symbol == 0) {
555 // FIXME: This is trying to take care of module ASM like this:
557 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
559 // but is gross and its mother dresses it funny. Have the ASM parser give us
560 // more details for this type of situation so that we're not guessing so
563 // fill information structure
564 info.name = entry.getKey().data();
566 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
567 info.isFunction = false;
570 // add to table of symbols
571 _symbols.push_back(info);
576 addDefinedFunctionSymbol(cast<Function>(info.symbol));
578 addDefinedDataSymbol(info.symbol);
580 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
581 _symbols.back().attributes |= scope;
584 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
586 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
587 StringMap<NameAndAttributes>::value_type &entry =
588 _undefines.GetOrCreateValue(name);
590 _asm_undefines.push_back(entry.getKey().data());
592 // we already have the symbol
593 if (entry.getValue().name)
596 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
597 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
598 NameAndAttributes info;
599 info.name = entry.getKey().data();
600 info.attributes = attr;
601 info.isFunction = false;
604 entry.setValue(info);
607 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
608 /// list to be resolved later.
610 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
611 // ignore all llvm.* symbols
612 if (decl->getName().startswith("llvm."))
615 // ignore all aliases
616 if (isa<GlobalAlias>(decl))
619 SmallString<64> name;
620 _mangler.getNameWithPrefix(name, decl, false);
622 StringMap<NameAndAttributes>::value_type &entry =
623 _undefines.GetOrCreateValue(name);
625 // we already have the symbol
626 if (entry.getValue().name)
629 NameAndAttributes info;
631 info.name = entry.getKey().data();
633 if (decl->hasExternalWeakLinkage())
634 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
636 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
638 info.isFunction = isFunc;
641 entry.setValue(info);
645 class RecordStreamer : public MCStreamer {
647 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
650 StringMap<State> Symbols;
652 void markDefined(const MCSymbol &Symbol) {
653 State &S = Symbols[Symbol.getName()];
666 void markGlobal(const MCSymbol &Symbol) {
667 State &S = Symbols[Symbol.getName()];
681 void markUsed(const MCSymbol &Symbol) {
682 State &S = Symbols[Symbol.getName()];
696 // FIXME: mostly copied for the obj streamer.
697 void AddValueSymbols(const MCExpr *Value) {
698 switch (Value->getKind()) {
700 // FIXME: What should we do in here?
703 case MCExpr::Constant:
706 case MCExpr::Binary: {
707 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
708 AddValueSymbols(BE->getLHS());
709 AddValueSymbols(BE->getRHS());
713 case MCExpr::SymbolRef:
714 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
718 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
724 typedef StringMap<State>::const_iterator const_iterator;
726 const_iterator begin() {
727 return Symbols.begin();
730 const_iterator end() {
731 return Symbols.end();
734 RecordStreamer(MCContext &Context)
735 : MCStreamer(SK_RecordStreamer, Context) {}
737 virtual void EmitInstruction(const MCInst &Inst) {
739 for (unsigned i = Inst.getNumOperands(); i--; )
740 if (Inst.getOperand(i).isExpr())
741 AddValueSymbols(Inst.getOperand(i).getExpr());
743 virtual void EmitLabel(MCSymbol *Symbol) {
744 Symbol->setSection(*getCurrentSection().first);
745 markDefined(*Symbol);
747 virtual void EmitDebugLabel(MCSymbol *Symbol) {
750 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
751 // FIXME: should we handle aliases?
752 markDefined(*Symbol);
754 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
755 if (Attribute == MCSA_Global)
758 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
759 uint64_t Size , unsigned ByteAlignment) {
760 markDefined(*Symbol);
762 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
763 unsigned ByteAlignment) {
764 markDefined(*Symbol);
767 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
768 virtual void EmitBundleLock(bool AlignToEnd) {}
769 virtual void EmitBundleUnlock() {}
772 virtual void ChangeSection(const MCSection *Section,
773 const MCExpr *Subsection) {}
774 virtual void InitToTextSection() {}
775 virtual void InitSections() {}
776 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
777 virtual void EmitThumbFunc(MCSymbol *Func) {}
778 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
779 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
780 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
781 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
782 virtual void EmitCOFFSymbolType(int Type) {}
783 virtual void EndCOFFSymbolDef() {}
784 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
785 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
786 unsigned ByteAlignment) {}
787 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
788 uint64_t Size, unsigned ByteAlignment) {}
789 virtual void EmitBytes(StringRef Data) {}
790 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
791 virtual void EmitULEB128Value(const MCExpr *Value) {}
792 virtual void EmitSLEB128Value(const MCExpr *Value) {}
793 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
795 unsigned MaxBytesToEmit) {}
796 virtual void EmitCodeAlignment(unsigned ByteAlignment,
797 unsigned MaxBytesToEmit) {}
798 virtual bool EmitValueToOffset(const MCExpr *Offset,
799 unsigned char Value ) { return false; }
800 virtual void EmitFileDirective(StringRef Filename) {}
801 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
802 const MCSymbol *LastLabel,
803 const MCSymbol *Label,
804 unsigned PointerSize) {}
805 virtual void FinishImpl() {}
807 static bool classof(const MCStreamer *S) {
808 return S->getKind() == SK_RecordStreamer;
811 } // end anonymous namespace
813 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
814 /// defined or undefined lists.
815 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
816 const std::string &inlineAsm = _module->getModuleInlineAsm();
817 if (inlineAsm.empty())
820 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
821 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
823 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
824 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
826 *_target->getMCAsmInfo()));
827 const Target &T = _target->getTarget();
828 OwningPtr<MCSubtargetInfo>
829 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
830 _target->getTargetCPU(),
831 _target->getTargetFeatureString()));
832 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
834 errMsg = "target " + std::string(T.getName()) +
835 " does not define AsmParser.";
839 Parser->setTargetParser(*TAP);
840 if (Parser->Run(false))
843 for (RecordStreamer::const_iterator i = Streamer->begin(),
844 e = Streamer->end(); i != e; ++i) {
845 StringRef Key = i->first();
846 RecordStreamer::State Value = i->second;
847 if (Value == RecordStreamer::DefinedGlobal)
848 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
849 else if (Value == RecordStreamer::Defined)
850 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
851 else if (Value == RecordStreamer::Global ||
852 Value == RecordStreamer::Used)
853 addAsmGlobalSymbolUndef(Key.data());
859 /// isDeclaration - Return 'true' if the global value is a declaration.
860 static bool isDeclaration(const GlobalValue &V) {
861 if (V.hasAvailableExternallyLinkage())
864 if (V.isMaterializable())
867 return V.isDeclaration();
870 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
871 /// them to either the defined or undefined lists.
872 bool LTOModule::parseSymbols(std::string &errMsg) {
874 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
875 if (isDeclaration(*f))
876 addPotentialUndefinedSymbol(f, true);
878 addDefinedFunctionSymbol(f);
882 for (Module::global_iterator v = _module->global_begin(),
883 e = _module->global_end(); v != e; ++v) {
884 if (isDeclaration(*v))
885 addPotentialUndefinedSymbol(v, false);
887 addDefinedDataSymbol(v);
891 if (addAsmGlobalSymbols(errMsg))
895 for (Module::alias_iterator a = _module->alias_begin(),
896 e = _module->alias_end(); a != e; ++a) {
897 if (isDeclaration(*a->getAliasedGlobal()))
898 // Is an alias to a declaration.
899 addPotentialUndefinedSymbol(a, false);
901 addDefinedDataSymbol(a);
904 // make symbols for all undefines
905 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
906 e = _undefines.end(); u != e; ++u) {
907 // If this symbol also has a definition, then don't make an undefine because
908 // it is a tentative definition.
909 if (_defines.count(u->getKey())) continue;
910 NameAndAttributes info = u->getValue();
911 _symbols.push_back(info);