[llvm-dwp] Implement the required on-disk probed hash table
[oota-llvm.git] / tools / llvm-dwp / llvm-dwp.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/StringSet.h"
3 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
4 #include "llvm/CodeGen/AsmPrinter.h"
5 #include "llvm/MC/MCAsmInfo.h"
6 #include "llvm/MC/MCContext.h"
7 #include "llvm/MC/MCInstrInfo.h"
8 #include "llvm/MC/MCObjectFileInfo.h"
9 #include "llvm/MC/MCRegisterInfo.h"
10 #include "llvm/MC/MCSectionELF.h"
11 #include "llvm/MC/MCStreamer.h"
12 #include "llvm/Object/ObjectFile.h"
13 #include "llvm/Support/DataExtractor.h"
14 #include "llvm/Support/Options.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/TargetRegistry.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Support/TargetSelect.h"
21 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <memory>
24 #include <list>
25 #include <unordered_set>
26
27 using namespace llvm;
28 using namespace llvm::object;
29 using namespace cl;
30
31 OptionCategory DwpCategory("Specific Options");
32 static list<std::string> InputFiles(Positional, OneOrMore,
33                                     desc("<input files>"), cat(DwpCategory));
34
35 static opt<std::string> OutputFilename(Required, "o", desc("Specify the output file."),
36                                       value_desc("filename"), cat(DwpCategory));
37
38 static int error(const Twine &Error, const Twine &Context) {
39   errs() << Twine("while processing ") + Context + ":\n";
40   errs() << Twine("error: ") + Error + "\n";
41   return 1;
42 }
43
44 static std::error_code
45 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
46                        uint32_t &StringOffset, MCSection *StrSection,
47                        MCSection *StrOffsetSection, StringRef CurStrSection,
48                        StringRef CurStrOffsetSection) {
49   // Could possibly produce an error or warning if one of these was non-null but
50   // the other was null.
51   if (CurStrSection.empty() || CurStrOffsetSection.empty())
52     return std::error_code();
53
54   DenseMap<uint32_t, uint32_t> OffsetRemapping;
55
56   DataExtractor Data(CurStrSection, true, 0);
57   uint32_t LocalOffset = 0;
58   uint32_t PrevOffset = 0;
59   while (const char *s = Data.getCStr(&LocalOffset)) {
60     StringRef Str(s, LocalOffset - PrevOffset - 1);
61     auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
62     if (Pair.second) {
63       Out.SwitchSection(StrSection);
64       Out.EmitBytes(
65           StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
66       StringOffset += Str.size() + 1;
67     }
68     OffsetRemapping[PrevOffset] = Pair.first->second;
69     PrevOffset = LocalOffset;
70   }
71
72   Data = DataExtractor(CurStrOffsetSection, true, 0);
73
74   Out.SwitchSection(StrOffsetSection);
75
76   uint32_t Offset = 0;
77   uint64_t Size = CurStrOffsetSection.size();
78   while (Offset < Size) {
79     auto OldOffset = Data.getU32(&Offset);
80     auto NewOffset = OffsetRemapping[OldOffset];
81     Out.EmitIntValue(NewOffset, 4);
82   }
83
84   return std::error_code();
85 }
86
87 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
88   uint64_t CurCode;
89   uint32_t Offset = 0;
90   DataExtractor AbbrevData(Abbrev, true, 0);
91   while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
92     // Tag
93     AbbrevData.getULEB128(&Offset);
94     // DW_CHILDREN
95     AbbrevData.getU8(&Offset);
96     // Attributes
97     while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
98       ;
99   }
100   return Offset;
101 }
102
103 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
104   uint32_t Offset = 0;
105   DataExtractor InfoData(Info, true, 0);
106   InfoData.getU32(&Offset); // Length
107   uint16_t Version = InfoData.getU16(&Offset);
108   InfoData.getU32(&Offset); // Abbrev offset (should be zero)
109   uint8_t AddrSize = InfoData.getU8(&Offset);
110
111   uint32_t AbbrCode = InfoData.getULEB128(&Offset);
112
113   DataExtractor AbbrevData(Abbrev, true, 0);
114   uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
115   uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
116   (void)Tag;
117   // FIXME: Real error handling
118   assert(Tag == dwarf::DW_TAG_compile_unit);
119   // DW_CHILDREN
120   AbbrevData.getU8(&AbbrevOffset);
121   uint32_t Name;
122   uint32_t Form;
123   while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
124              (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
125          Name != dwarf::DW_AT_GNU_dwo_id) {
126     DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
127   }
128   // FIXME: Real error handling
129   assert(Name == dwarf::DW_AT_GNU_dwo_id);
130   return InfoData.getU64(&Offset);
131 }
132
133 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
134   const auto &MCOFI = *Out.getContext().getObjectFileInfo();
135   MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
136   MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
137   const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
138       {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
139       {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
140       {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
141       {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
142       {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
143       {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
144       {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
145
146   struct UnitIndexEntry {
147     uint64_t Signature;
148     DWARFUnitIndex::Entry::SectionContribution Contributions[8];
149   };
150
151   std::vector<UnitIndexEntry> IndexEntries;
152
153   StringMap<uint32_t> Strings;
154   uint32_t StringOffset = 0;
155
156   uint32_t ContributionOffsets[8] = {};
157
158   for (const auto &Input : Inputs) {
159     auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
160     if (!ErrOrObj)
161       return ErrOrObj.getError();
162
163     IndexEntries.emplace_back();
164     UnitIndexEntry &CurEntry = IndexEntries.back();
165
166     StringRef CurStrSection;
167     StringRef CurStrOffsetSection;
168     StringRef InfoSection;
169     StringRef AbbrevSection;
170
171     for (const auto &Section : ErrOrObj->getBinary()->sections()) {
172       StringRef Name;
173       if (std::error_code Err = Section.getName(Name))
174         return Err;
175
176       auto SectionPair =
177           KnownSections.find(Name.substr(Name.find_first_not_of("._")));
178       if (SectionPair == KnownSections.end())
179         continue;
180
181       StringRef Contents;
182       if (auto Err = Section.getContents(Contents))
183         return Err;
184
185       if (DWARFSectionKind Kind = SectionPair->second.second) {
186         auto Index = Kind - DW_SECT_INFO;
187         CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
188         ContributionOffsets[Index] +=
189             (CurEntry.Contributions[Index].Length = Contents.size());
190
191         if (Kind == DW_SECT_INFO) {
192           assert(InfoSection.empty());
193           InfoSection = Contents;
194         } else if (Kind == DW_SECT_ABBREV) {
195           assert(AbbrevSection.empty());
196           AbbrevSection = Contents;
197         }
198       }
199
200       MCSection *OutSection = SectionPair->second.first;
201       if (OutSection == StrOffsetSection)
202         CurStrOffsetSection = Contents;
203       else if (OutSection == StrSection)
204         CurStrSection = Contents;
205       else {
206         Out.SwitchSection(OutSection);
207         Out.EmitBytes(Contents);
208       }
209     }
210
211     assert(!AbbrevSection.empty());
212     assert(!InfoSection.empty());
213     CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
214
215     if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
216                                           StrSection, StrOffsetSection,
217                                           CurStrSection, CurStrOffsetSection))
218       return Err;
219   }
220
221   unsigned Columns = 0;
222   for (auto &C : ContributionOffsets)
223     if (C)
224       ++Columns;
225
226   std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
227   uint64_t Mask = Buckets.size() - 1;
228   for (size_t i = 0; i != IndexEntries.size(); ++i) {
229     auto S = IndexEntries[i].Signature;
230     auto H = S & Mask;
231     while (Buckets[H])
232       H += ((S >> 32) & Mask) | 1;
233     Buckets[H] = i + 1;
234   }
235
236   Out.SwitchSection(MCOFI.getDwarfCUIndexSection());
237   Out.EmitIntValue(2, 4);                   // Version
238   Out.EmitIntValue(Columns, 4);             // Columns
239   Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
240   // FIXME: This is not the right number of buckets for a real hash.
241   Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
242
243   // Write the signatures.
244   for (const auto &I : Buckets)
245     Out.EmitIntValue(I ? IndexEntries[I - 1].Signature : 0, 8);
246
247   // Write the indexes.
248   for (const auto &I : Buckets)
249     Out.EmitIntValue(I, 4);
250
251   // Write the column headers (which sections will appear in the table)
252   for (size_t i = 0; i != array_lengthof(ContributionOffsets); ++i)
253     if (ContributionOffsets[i])
254       Out.EmitIntValue(i + DW_SECT_INFO, 4);
255
256   // Write the offsets.
257   for (const auto &E : IndexEntries)
258     for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
259       if (ContributionOffsets[i])
260         Out.EmitIntValue(E.Contributions[i].Offset, 4);
261
262   // Write the lengths.
263   for (const auto &E : IndexEntries)
264     for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
265       if (ContributionOffsets[i])
266         Out.EmitIntValue(E.Contributions[i].Length, 4);
267
268   return std::error_code();
269 }
270
271 int main(int argc, char** argv) {
272
273   ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
274
275   llvm::InitializeAllTargetInfos();
276   llvm::InitializeAllTargetMCs();
277   llvm::InitializeAllTargets();
278   llvm::InitializeAllAsmPrinters();
279
280   std::string ErrorStr;
281   StringRef Context = "dwarf streamer init";
282
283   Triple TheTriple("x86_64-linux-gnu");
284
285   // Get the target.
286   const Target *TheTarget =
287       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
288   if (!TheTarget)
289     return error(ErrorStr, Context);
290   std::string TripleName = TheTriple.getTriple();
291
292   // Create all the MC Objects.
293   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
294   if (!MRI)
295     return error(Twine("no register info for target ") + TripleName, Context);
296
297   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
298   if (!MAI)
299     return error("no asm info for target " + TripleName, Context);
300
301   MCObjectFileInfo MOFI;
302   MCContext MC(MAI.get(), MRI.get(), &MOFI);
303   MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
304                              MC);
305
306   auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
307   if (!MAB)
308     return error("no asm backend for target " + TripleName, Context);
309
310   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
311   if (!MII)
312     return error("no instr info info for target " + TripleName, Context);
313
314   std::unique_ptr<MCSubtargetInfo> MSTI(
315       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
316   if (!MSTI)
317     return error("no subtarget info for target " + TripleName, Context);
318
319   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
320   if (!MCE)
321     return error("no code emitter for target " + TripleName, Context);
322
323   // Create the output file.
324   std::error_code EC;
325   raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
326   if (EC)
327     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
328
329   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
330       TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
331       /*DWARFMustBeAtTheEnd*/ false));
332   if (!MS)
333     return error("no object streamer for target " + TripleName, Context);
334
335   if (auto Err = write(*MS, InputFiles))
336     return error(Err.message(), "Writing DWP file");
337
338   MS->Finish();
339 }