1 //===- llvm/CodeGen/DwarfStringPool.cpp - Dwarf Debug Framework -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "DwarfStringPool.h" 11 #include "llvm/ADT/SmallVector.h" 12 #include "llvm/ADT/StringRef.h" 13 #include "llvm/ADT/Twine.h" 14 #include "llvm/CodeGen/AsmPrinter.h" 15 #include "llvm/MC/MCAsmInfo.h" 16 #include "llvm/MC/MCStreamer.h" 17 #include <cassert> 18 #include <utility> 19 20 using namespace llvm; 21 22 DwarfStringPool::DwarfStringPool(BumpPtrAllocator &A, AsmPrinter &Asm, 23 StringRef Prefix) 24 : Pool(A), Prefix(Prefix), 25 ShouldCreateSymbols(Asm.MAI->doesDwarfUseRelocationsAcrossSections()) {} 26 27 DwarfStringPool::EntryRef DwarfStringPool::getEntry(AsmPrinter &Asm, 28 StringRef Str) { 29 auto I = Pool.insert(std::make_pair(Str, EntryTy())); 30 if (I.second) { 31 auto &Entry = I.first->second; 32 Entry.Index = Pool.size() - 1; 33 Entry.Offset = NumBytes; 34 Entry.Symbol = ShouldCreateSymbols ? Asm.createTempSymbol(Prefix) : nullptr; 35 36 NumBytes += Str.size() + 1; 37 assert(NumBytes > Entry.Offset && "Unexpected overflow"); 38 } 39 return EntryRef(*I.first); 40 } 41 42 void DwarfStringPool::emit(AsmPrinter &Asm, MCSection *StrSection, 43 MCSection *OffsetSection, bool UseRelativeOffsets) { 44 if (Pool.empty()) 45 return; 46 47 // Start the dwarf str section. 48 Asm.OutStreamer->SwitchSection(StrSection); 49 50 // Get all of the string pool entries and put them in an array by their ID so 51 // we can sort them. 52 SmallVector<const StringMapEntry<EntryTy> *, 64> Entries(Pool.size()); 53 54 for (const auto &E : Pool) 55 Entries[E.getValue().Index] = &E; 56 57 for (const auto &Entry : Entries) { 58 assert(ShouldCreateSymbols == static_cast<bool>(Entry->getValue().Symbol) && 59 "Mismatch between setting and entry"); 60 61 // Emit a label for reference from debug information entries. 62 if (ShouldCreateSymbols) 63 Asm.OutStreamer->EmitLabel(Entry->getValue().Symbol); 64 65 // Emit the string itself with a terminating null byte. 66 Asm.OutStreamer->AddComment("string offset=" + 67 Twine(Entry->getValue().Offset)); 68 Asm.OutStreamer->EmitBytes( 69 StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1)); 70 } 71 72 // If we've got an offset section go ahead and emit that now as well. 73 if (OffsetSection) { 74 Asm.OutStreamer->SwitchSection(OffsetSection); 75 unsigned size = 4; // FIXME: DWARF64 is 8. 76 for (const auto &Entry : Entries) 77 if (UseRelativeOffsets) 78 Asm.emitDwarfStringOffset(Entry->getValue()); 79 else 80 Asm.OutStreamer->EmitIntValue(Entry->getValue().Offset, size); 81 } 82 } 83