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"
17 #include "llvm/Constants.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/system_error.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/Target/TargetAsmParser.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Target/TargetSelect.h"
48 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
49 return llvm::sys::IdentifyFileType((char*)mem, length)
50 == llvm::sys::Bitcode_FileType;
53 bool LTOModule::isBitcodeFile(const char *path) {
54 return llvm::sys::Path(path).isBitcodeFile();
57 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
58 const char *triplePrefix) {
59 MemoryBuffer *buffer = makeBuffer(mem, length);
62 return isTargetMatch(buffer, triplePrefix);
66 bool LTOModule::isBitcodeFileForTarget(const char *path,
67 const char *triplePrefix) {
68 OwningPtr<MemoryBuffer> buffer;
69 if (MemoryBuffer::getFile(path, buffer))
71 return isTargetMatch(buffer.take(), triplePrefix);
74 // Takes ownership of buffer.
75 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
76 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
78 return (strncmp(Triple.c_str(), triplePrefix,
79 strlen(triplePrefix)) == 0);
83 LTOModule::LTOModule(Module *m, TargetMachine *t)
84 : _module(m), _target(t)
88 LTOModule *LTOModule::makeLTOModule(const char *path,
89 std::string &errMsg) {
90 OwningPtr<MemoryBuffer> buffer;
91 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
92 errMsg = ec.message();
95 return makeLTOModule(buffer.take(), errMsg);
98 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
100 std::string &errMsg) {
101 return makeLTOModule(fd, path, size, size, 0, errMsg);
104 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
108 std::string &errMsg) {
109 OwningPtr<MemoryBuffer> buffer;
110 if (error_code ec = MemoryBuffer::getOpenFile(fd, path, buffer, file_size,
111 map_size, offset, false)) {
112 errMsg = ec.message();
115 return makeLTOModule(buffer.take(), errMsg);
118 /// makeBuffer - Create a MemoryBuffer from a memory range.
119 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
120 const char *startPtr = (char*)mem;
121 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
125 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
126 std::string &errMsg) {
127 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
130 return makeLTOModule(buffer.take(), errMsg);
133 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
134 std::string &errMsg) {
135 static bool Initialized = false;
137 InitializeAllTargets();
138 InitializeAllMCSubtargetInfos();
139 InitializeAllAsmParsers();
143 // parse bitcode buffer
144 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
151 std::string Triple = m->getTargetTriple();
153 Triple = sys::getHostTriple();
155 // find machine architecture for this module
156 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
160 // construct LTOModule, hand over ownership of module and target
161 SubtargetFeatures Features;
162 Features.getDefaultSubtargetFeatures(llvm::Triple(Triple));
163 std::string FeatureStr = Features.getString();
165 TargetMachine *target = march->createTargetMachine(Triple, CPU, FeatureStr);
166 LTOModule *Ret = new LTOModule(m.take(), target);
167 bool Err = Ret->ParseSymbols();
176 const char *LTOModule::getTargetTriple() {
177 return _module->getTargetTriple().c_str();
180 void LTOModule::setTargetTriple(const char *triple) {
181 _module->setTargetTriple(triple);
184 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
185 // add to list of defined symbols
186 addDefinedSymbol(f, mangler, true);
189 // Get string that data pointer points to.
190 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
191 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
192 Constant *op = ce->getOperand(0);
193 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
194 Constant *cn = gvn->getInitializer();
195 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
196 if (ca->isCString()) {
197 name = ".objc_class_name_" + ca->getAsCString();
206 // Parse i386/ppc ObjC class data structure.
207 void LTOModule::addObjCClass(GlobalVariable *clgv) {
208 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
209 // second slot in __OBJC,__class is pointer to superclass name
210 std::string superclassName;
211 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
212 NameAndAttributes info;
213 StringMap<NameAndAttributes>::value_type &entry =
214 _undefines.GetOrCreateValue(superclassName);
215 if (!entry.getValue().name) {
216 const char *symbolName = entry.getKey().data();
217 info.name = symbolName;
218 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
219 entry.setValue(info);
222 // third slot in __OBJC,__class is pointer to class name
223 std::string className;
224 if (objcClassNameFromExpression(c->getOperand(2), className)) {
225 StringSet::value_type &entry =
226 _defines.GetOrCreateValue(className);
228 NameAndAttributes info;
229 info.name = entry.getKey().data();
230 info.attributes = (lto_symbol_attributes)
231 (LTO_SYMBOL_PERMISSIONS_DATA |
232 LTO_SYMBOL_DEFINITION_REGULAR |
233 LTO_SYMBOL_SCOPE_DEFAULT);
234 _symbols.push_back(info);
240 // Parse i386/ppc ObjC category data structure.
241 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
242 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
243 // second slot in __OBJC,__category is pointer to target class name
244 std::string targetclassName;
245 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
246 NameAndAttributes info;
248 StringMap<NameAndAttributes>::value_type &entry =
249 _undefines.GetOrCreateValue(targetclassName);
251 if (entry.getValue().name)
254 const char *symbolName = entry.getKey().data();
255 info.name = symbolName;
256 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
257 entry.setValue(info);
263 // Parse i386/ppc ObjC class list data structure.
264 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
265 std::string targetclassName;
266 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
267 NameAndAttributes info;
269 StringMap<NameAndAttributes>::value_type &entry =
270 _undefines.GetOrCreateValue(targetclassName);
271 if (entry.getValue().name)
274 const char *symbolName = entry.getKey().data();
275 info.name = symbolName;
276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
277 entry.setValue(info);
282 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
283 // Add to list of defined symbols.
284 addDefinedSymbol(v, mangler, false);
286 // Special case i386/ppc ObjC data structures in magic sections:
287 // The issue is that the old ObjC object format did some strange
288 // contortions to avoid real linker symbols. For instance, the
289 // ObjC class data structure is allocated statically in the executable
290 // that defines that class. That data structures contains a pointer to
291 // its superclass. But instead of just initializing that part of the
292 // struct to the address of its superclass, and letting the static and
293 // dynamic linkers do the rest, the runtime works by having that field
294 // instead point to a C-string that is the name of the superclass.
295 // At runtime the objc initialization updates that pointer and sets
296 // it to point to the actual super class. As far as the linker
297 // knows it is just a pointer to a string. But then someone wanted the
298 // linker to issue errors at build time if the superclass was not found.
299 // So they figured out a way in mach-o object format to use an absolute
300 // symbols (.objc_class_name_Foo = 0) and a floating reference
301 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
302 // a class was missing.
303 // The following synthesizes the implicit .objc_* symbols for the linker
304 // from the ObjC data structures generated by the front end.
305 if (v->hasSection() /* && isTargetDarwin */) {
306 // special case if this data blob is an ObjC class definition
307 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
308 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
313 // special case if this data blob is an ObjC category definition
314 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
315 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
320 // special case if this data blob is the list of referenced classes
321 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
322 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
330 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
332 // ignore all llvm.* symbols
333 if (def->getName().startswith("llvm."))
336 // string is owned by _defines
337 SmallString<64> Buffer;
338 mangler.getNameWithPrefix(Buffer, def, false);
340 // set alignment part log2() can have rounding errors
341 uint32_t align = def->getAlignment();
342 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
344 // set permissions part
346 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
348 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
349 if (gv && gv->isConstant())
350 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
352 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
355 // set definition part
356 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
357 def->hasLinkerPrivateWeakLinkage() ||
358 def->hasLinkerPrivateWeakDefAutoLinkage())
359 attr |= LTO_SYMBOL_DEFINITION_WEAK;
360 else if (def->hasCommonLinkage())
361 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
363 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
366 if (def->hasHiddenVisibility())
367 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
368 else if (def->hasProtectedVisibility())
369 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
370 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
371 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
372 def->hasLinkerPrivateWeakLinkage())
373 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
374 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
375 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
377 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
379 // add to table of symbols
380 NameAndAttributes info;
381 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
384 StringRef Name = entry.getKey();
385 info.name = Name.data();
386 assert(info.name[Name.size()] == '\0');
387 info.attributes = (lto_symbol_attributes)attr;
388 _symbols.push_back(info);
391 void LTOModule::addAsmGlobalSymbol(const char *name,
392 lto_symbol_attributes scope) {
393 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
395 // only add new define if not already defined
396 if (entry.getValue())
400 const char *symbolName = entry.getKey().data();
401 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
403 NameAndAttributes info;
404 info.name = symbolName;
405 info.attributes = (lto_symbol_attributes)attr;
406 _symbols.push_back(info);
409 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
410 StringMap<NameAndAttributes>::value_type &entry =
411 _undefines.GetOrCreateValue(name);
413 _asm_undefines.push_back(entry.getKey().data());
415 // we already have the symbol
416 if (entry.getValue().name)
419 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
420 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
421 NameAndAttributes info;
422 info.name = entry.getKey().data();
423 info.attributes = (lto_symbol_attributes)attr;
425 entry.setValue(info);
428 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
430 // ignore all llvm.* symbols
431 if (decl->getName().startswith("llvm."))
434 // ignore all aliases
435 if (isa<GlobalAlias>(decl))
438 SmallString<64> name;
439 mangler.getNameWithPrefix(name, decl, false);
441 StringMap<NameAndAttributes>::value_type &entry =
442 _undefines.GetOrCreateValue(name);
444 // we already have the symbol
445 if (entry.getValue().name)
448 NameAndAttributes info;
450 info.name = entry.getKey().data();
451 if (decl->hasExternalWeakLinkage())
452 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
454 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
456 entry.setValue(info);
461 class RecordStreamer : public MCStreamer {
463 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used};
466 StringMap<State> Symbols;
468 void markDefined(const MCSymbol &Symbol) {
469 State &S = Symbols[Symbol.getName()];
482 void markGlobal(const MCSymbol &Symbol) {
483 State &S = Symbols[Symbol.getName()];
497 void markUsed(const MCSymbol &Symbol) {
498 State &S = Symbols[Symbol.getName()];
512 // FIXME: mostly copied for the obj streamer.
513 void AddValueSymbols(const MCExpr *Value) {
514 switch (Value->getKind()) {
516 // FIXME: What should we do in here?
519 case MCExpr::Constant:
522 case MCExpr::Binary: {
523 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
524 AddValueSymbols(BE->getLHS());
525 AddValueSymbols(BE->getRHS());
529 case MCExpr::SymbolRef:
530 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
534 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
540 typedef StringMap<State>::const_iterator const_iterator;
542 const_iterator begin() {
543 return Symbols.begin();
546 const_iterator end() {
547 return Symbols.end();
550 RecordStreamer(MCContext &Context) : MCStreamer(Context) {}
552 virtual void ChangeSection(const MCSection *Section) {}
553 virtual void InitSections() {}
554 virtual void EmitLabel(MCSymbol *Symbol) {
555 Symbol->setSection(*getCurrentSection());
556 markDefined(*Symbol);
558 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
559 virtual void EmitThumbFunc(MCSymbol *Func) {}
560 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
561 // FIXME: should we handle aliases?
562 markDefined(*Symbol);
564 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
565 if (Attribute == MCSA_Global)
568 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
569 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
570 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
571 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
572 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
573 unsigned Size , unsigned ByteAlignment) {
574 markDefined(*Symbol);
576 virtual void EmitCOFFSymbolType(int Type) {}
577 virtual void EndCOFFSymbolDef() {}
578 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
579 unsigned ByteAlignment) {
580 markDefined(*Symbol);
582 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
583 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {}
584 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
585 uint64_t Size, unsigned ByteAlignment) {}
586 virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {}
587 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
588 unsigned AddrSpace) {}
589 virtual void EmitULEB128Value(const MCExpr *Value) {}
590 virtual void EmitSLEB128Value(const MCExpr *Value) {}
591 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
593 unsigned MaxBytesToEmit) {}
594 virtual void EmitCodeAlignment(unsigned ByteAlignment,
595 unsigned MaxBytesToEmit) {}
596 virtual void EmitValueToOffset(const MCExpr *Offset,
597 unsigned char Value ) {}
598 virtual void EmitFileDirective(StringRef Filename) {}
599 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
600 const MCSymbol *LastLabel,
601 const MCSymbol *Label,
602 unsigned PointerSize) {}
604 virtual void EmitInstruction(const MCInst &Inst) {
606 for (unsigned i = Inst.getNumOperands(); i--; )
607 if (Inst.getOperand(i).isExpr())
608 AddValueSymbols(Inst.getOperand(i).getExpr());
610 virtual void Finish() {}
614 bool LTOModule::addAsmGlobalSymbols(MCContext &Context) {
615 const std::string &inlineAsm = _module->getModuleInlineAsm();
617 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(Context));
618 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
620 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
621 OwningPtr<MCAsmParser> Parser(createMCAsmParser(_target->getTarget(), SrcMgr,
623 *_target->getMCAsmInfo()));
624 OwningPtr<MCSubtargetInfo> STI(_target->getTarget().
625 createMCSubtargetInfo(_target->getTargetTriple(),
626 _target->getTargetCPU(),
627 _target->getTargetFeatureString()));
628 OwningPtr<TargetAsmParser>
629 TAP(_target->getTarget().createAsmParser(*STI, *Parser.get()));
630 Parser->setTargetParser(*TAP);
631 int Res = Parser->Run(false);
635 for (RecordStreamer::const_iterator i = Streamer->begin(),
636 e = Streamer->end(); i != e; ++i) {
637 StringRef Key = i->first();
638 RecordStreamer::State Value = i->second;
639 if (Value == RecordStreamer::DefinedGlobal)
640 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
641 else if (Value == RecordStreamer::Defined)
642 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
643 else if (Value == RecordStreamer::Global ||
644 Value == RecordStreamer::Used)
645 addAsmGlobalSymbolUndef(Key.data());
650 static bool isDeclaration(const GlobalValue &V) {
651 if (V.hasAvailableExternallyLinkage())
653 if (V.isMaterializable())
655 return V.isDeclaration();
658 static bool isAliasToDeclaration(const GlobalAlias &V) {
659 return isDeclaration(*V.getAliasedGlobal());
662 bool LTOModule::ParseSymbols() {
663 // Use mangler to add GlobalPrefix to names to match linker names.
664 MCContext Context(*_target->getMCAsmInfo(), NULL);
665 Mangler mangler(Context, *_target->getTargetData());
668 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
669 if (isDeclaration(*f))
670 addPotentialUndefinedSymbol(f, mangler);
672 addDefinedFunctionSymbol(f, mangler);
676 for (Module::global_iterator v = _module->global_begin(),
677 e = _module->global_end(); v != e; ++v) {
678 if (isDeclaration(*v))
679 addPotentialUndefinedSymbol(v, mangler);
681 addDefinedDataSymbol(v, mangler);
685 if (addAsmGlobalSymbols(Context))
689 for (Module::alias_iterator i = _module->alias_begin(),
690 e = _module->alias_end(); i != e; ++i) {
691 if (isAliasToDeclaration(*i))
692 addPotentialUndefinedSymbol(i, mangler);
694 addDefinedDataSymbol(i, mangler);
697 // make symbols for all undefines
698 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
699 it != _undefines.end(); ++it) {
700 // if this symbol also has a definition, then don't make an undefine
701 // because it is a tentative definition
702 if (_defines.count(it->getKey()) == 0) {
703 NameAndAttributes info = it->getValue();
704 _symbols.push_back(info);
711 uint32_t LTOModule::getSymbolCount() {
712 return _symbols.size();
716 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
717 if (index < _symbols.size())
718 return _symbols[index].attributes;
720 return lto_symbol_attributes(0);
723 const char *LTOModule::getSymbolName(uint32_t index) {
724 if (index < _symbols.size())
725 return _symbols[index].name;