1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/MC/MCDwarf.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/Hashing.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectStreamer.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/EndianStream.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <optional>
42 #include <string>
43 #include <utility>
44 #include <vector>
45
46 using namespace llvm;
47
emitListsTableHeaderStart(MCStreamer & S)48 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
49 MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
50 MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
51 auto DwarfFormat = S.getContext().getDwarfFormat();
52 if (DwarfFormat == dwarf::DWARF64) {
53 S.AddComment("DWARF64 mark");
54 S.emitInt32(dwarf::DW_LENGTH_DWARF64);
55 }
56 S.AddComment("Length");
57 S.emitAbsoluteSymbolDiff(End, Start,
58 dwarf::getDwarfOffsetByteSize(DwarfFormat));
59 S.emitLabel(Start);
60 S.AddComment("Version");
61 S.emitInt16(S.getContext().getDwarfVersion());
62 S.AddComment("Address size");
63 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
64 S.AddComment("Segment selector size");
65 S.emitInt8(0);
66 return End;
67 }
68
ScaleAddrDelta(MCContext & Context,uint64_t AddrDelta)69 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
70 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
71 if (MinInsnLength == 1)
72 return AddrDelta;
73 if (AddrDelta % MinInsnLength != 0) {
74 // TODO: report this error, but really only once.
75 ;
76 }
77 return AddrDelta / MinInsnLength;
78 }
79
MCDwarfLineStr(MCContext & Ctx)80 MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
81 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
82 if (UseRelocs) {
83 MCSection *DwarfLineStrSection =
84 Ctx.getObjectFileInfo()->getDwarfLineStrSection();
85 assert(DwarfLineStrSection && "DwarfLineStrSection must not be NULL");
86 LineStrLabel = DwarfLineStrSection->getBeginSymbol();
87 }
88 }
89
90 //
91 // This is called when an instruction is assembled into the specified section
92 // and if there is information from the last .loc directive that has yet to have
93 // a line entry made for it is made.
94 //
make(MCStreamer * MCOS,MCSection * Section)95 void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
96 if (!MCOS->getContext().getDwarfLocSeen())
97 return;
98
99 // Create a symbol at in the current section for use in the line entry.
100 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
101 // Set the value of the symbol to use for the MCDwarfLineEntry.
102 MCOS->emitLabel(LineSym);
103
104 // Get the current .loc info saved in the context.
105 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
106
107 // Create a (local) line entry with the symbol and the current .loc info.
108 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
109
110 // clear DwarfLocSeen saying the current .loc info is now used.
111 MCOS->getContext().clearDwarfLocSeen();
112
113 // Add the line entry to this section's entries.
114 MCOS->getContext()
115 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
116 .getMCLineSections()
117 .addLineEntry(LineEntry, Section);
118 }
119
120 //
121 // This helper routine returns an expression of End - Start - IntVal .
122 //
makeEndMinusStartExpr(MCContext & Ctx,const MCSymbol & Start,const MCSymbol & End,int IntVal)123 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
124 const MCSymbol &Start,
125 const MCSymbol &End,
126 int IntVal) {
127 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
128 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
129 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
130 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
131 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
132 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
133 return Res3;
134 }
135
136 //
137 // This helper routine returns an expression of Start + IntVal .
138 //
139 static inline const MCExpr *
makeStartPlusIntExpr(MCContext & Ctx,const MCSymbol & Start,int IntVal)140 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
141 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
142 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
143 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
144 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
145 return Res;
146 }
147
addEndEntry(MCSymbol * EndLabel)148 void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
149 auto *Sec = &EndLabel->getSection();
150 // The line table may be empty, which we should skip adding an end entry.
151 // There are two cases:
152 // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in
153 // place instead of adding a line entry if the target has
154 // usesDwarfFileAndLocDirectives.
155 // (2) MCObjectStreamer - if a function has incomplete debug info where
156 // instructions don't have DILocations, the line entries are missing.
157 auto I = MCLineDivisions.find(Sec);
158 if (I != MCLineDivisions.end()) {
159 auto &Entries = I->second;
160 auto EndEntry = Entries.back();
161 EndEntry.setEndLabel(EndLabel);
162 Entries.push_back(EndEntry);
163 }
164 }
165
166 //
167 // This emits the Dwarf line table for the specified section from the entries
168 // in the LineSection.
169 //
emitOne(MCStreamer * MCOS,MCSection * Section,const MCLineSection::MCDwarfLineEntryCollection & LineEntries)170 void MCDwarfLineTable::emitOne(
171 MCStreamer *MCOS, MCSection *Section,
172 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
173
174 unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
175 MCSymbol *LastLabel;
176 auto init = [&]() {
177 FileNum = 1;
178 LastLine = 1;
179 Column = 0;
180 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
181 Isa = 0;
182 Discriminator = 0;
183 LastLabel = nullptr;
184 };
185 init();
186
187 // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
188 bool EndEntryEmitted = false;
189 for (const MCDwarfLineEntry &LineEntry : LineEntries) {
190 MCSymbol *Label = LineEntry.getLabel();
191 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
192 if (LineEntry.IsEndEntry) {
193 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,
194 asmInfo->getCodePointerSize());
195 init();
196 EndEntryEmitted = true;
197 continue;
198 }
199
200 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
201
202 if (FileNum != LineEntry.getFileNum()) {
203 FileNum = LineEntry.getFileNum();
204 MCOS->emitInt8(dwarf::DW_LNS_set_file);
205 MCOS->emitULEB128IntValue(FileNum);
206 }
207 if (Column != LineEntry.getColumn()) {
208 Column = LineEntry.getColumn();
209 MCOS->emitInt8(dwarf::DW_LNS_set_column);
210 MCOS->emitULEB128IntValue(Column);
211 }
212 if (Discriminator != LineEntry.getDiscriminator() &&
213 MCOS->getContext().getDwarfVersion() >= 4) {
214 Discriminator = LineEntry.getDiscriminator();
215 unsigned Size = getULEB128Size(Discriminator);
216 MCOS->emitInt8(dwarf::DW_LNS_extended_op);
217 MCOS->emitULEB128IntValue(Size + 1);
218 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
219 MCOS->emitULEB128IntValue(Discriminator);
220 }
221 if (Isa != LineEntry.getIsa()) {
222 Isa = LineEntry.getIsa();
223 MCOS->emitInt8(dwarf::DW_LNS_set_isa);
224 MCOS->emitULEB128IntValue(Isa);
225 }
226 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
227 Flags = LineEntry.getFlags();
228 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
229 }
230 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
231 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
232 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
233 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
234 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
235 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
236
237 // At this point we want to emit/create the sequence to encode the delta in
238 // line numbers and the increment of the address from the previous Label
239 // and the current Label.
240 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
241 asmInfo->getCodePointerSize());
242
243 Discriminator = 0;
244 LastLine = LineEntry.getLine();
245 LastLabel = Label;
246 }
247
248 // Generate DWARF line end entry.
249 // We do not need this for DwarfDebug that explicitly terminates the line
250 // table using ranges whenever CU or section changes. However, the MC path
251 // does not track ranges nor terminate the line table. In that case,
252 // conservatively use the section end symbol to end the line table.
253 if (!EndEntryEmitted)
254 MCOS->emitDwarfLineEndEntry(Section, LastLabel);
255 }
256
257 //
258 // This emits the Dwarf file and the line tables.
259 //
emit(MCStreamer * MCOS,MCDwarfLineTableParams Params)260 void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
261 MCContext &context = MCOS->getContext();
262
263 auto &LineTables = context.getMCDwarfLineTables();
264
265 // Bail out early so we don't switch to the debug_line section needlessly and
266 // in doing so create an unnecessary (if empty) section.
267 if (LineTables.empty())
268 return;
269
270 // In a v5 non-split line table, put the strings in a separate section.
271 std::optional<MCDwarfLineStr> LineStr;
272 if (context.getDwarfVersion() >= 5)
273 LineStr.emplace(context);
274
275 // Switch to the section where the table will be emitted into.
276 MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection());
277
278 // Handle the rest of the Compile Units.
279 for (const auto &CUIDTablePair : LineTables) {
280 CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
281 }
282
283 if (LineStr)
284 LineStr->emitSection(MCOS);
285 }
286
Emit(MCStreamer & MCOS,MCDwarfLineTableParams Params,MCSection * Section) const287 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
288 MCSection *Section) const {
289 if (!HasSplitLineTable)
290 return;
291 std::optional<MCDwarfLineStr> NoLineStr(std::nullopt);
292 MCOS.switchSection(Section);
293 MCOS.emitLabel(Header.Emit(&MCOS, Params, std::nullopt, NoLineStr).second);
294 }
295
296 std::pair<MCSymbol *, MCSymbol *>
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,std::optional<MCDwarfLineStr> & LineStr) const297 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
298 std::optional<MCDwarfLineStr> &LineStr) const {
299 static const char StandardOpcodeLengths[] = {
300 0, // length of DW_LNS_copy
301 1, // length of DW_LNS_advance_pc
302 1, // length of DW_LNS_advance_line
303 1, // length of DW_LNS_set_file
304 1, // length of DW_LNS_set_column
305 0, // length of DW_LNS_negate_stmt
306 0, // length of DW_LNS_set_basic_block
307 0, // length of DW_LNS_const_add_pc
308 1, // length of DW_LNS_fixed_advance_pc
309 0, // length of DW_LNS_set_prologue_end
310 0, // length of DW_LNS_set_epilogue_begin
311 1 // DW_LNS_set_isa
312 };
313 assert(std::size(StandardOpcodeLengths) >=
314 (Params.DWARF2LineOpcodeBase - 1U));
315 return Emit(MCOS, Params,
316 ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
317 LineStr);
318 }
319
forceExpAbs(MCStreamer & OS,const MCExpr * Expr)320 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
321 MCContext &Context = OS.getContext();
322 assert(!isa<MCSymbolRefExpr>(Expr));
323 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
324 return Expr;
325
326 MCSymbol *ABS = Context.createTempSymbol();
327 OS.emitAssignment(ABS, Expr);
328 return MCSymbolRefExpr::create(ABS, Context);
329 }
330
emitAbsValue(MCStreamer & OS,const MCExpr * Value,unsigned Size)331 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
332 const MCExpr *ABS = forceExpAbs(OS, Value);
333 OS.emitValue(ABS, Size);
334 }
335
emitSection(MCStreamer * MCOS)336 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
337 // Switch to the .debug_line_str section.
338 MCOS->switchSection(
339 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
340 SmallString<0> Data = getFinalizedData();
341 MCOS->emitBinaryData(Data.str());
342 }
343
getFinalizedData()344 SmallString<0> MCDwarfLineStr::getFinalizedData() {
345 // Emit the strings without perturbing the offsets we used.
346 if (!LineStrings.isFinalized())
347 LineStrings.finalizeInOrder();
348 SmallString<0> Data;
349 Data.resize(LineStrings.getSize());
350 LineStrings.write((uint8_t *)Data.data());
351 return Data;
352 }
353
addString(StringRef Path)354 size_t MCDwarfLineStr::addString(StringRef Path) {
355 return LineStrings.add(Path);
356 }
357
emitRef(MCStreamer * MCOS,StringRef Path)358 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
359 int RefSize =
360 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
361 size_t Offset = addString(Path);
362 if (UseRelocs) {
363 MCContext &Ctx = MCOS->getContext();
364 if (Ctx.getAsmInfo()->needsDwarfSectionOffsetDirective()) {
365 MCOS->emitCOFFSecRel32(LineStrLabel, Offset);
366 } else {
367 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset),
368 RefSize);
369 }
370 } else
371 MCOS->emitIntValue(Offset, RefSize);
372 }
373
emitV2FileDirTables(MCStreamer * MCOS) const374 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
375 // First the directory table.
376 for (auto &Dir : MCDwarfDirs) {
377 MCOS->emitBytes(Dir); // The DirectoryName, and...
378 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
379 }
380 MCOS->emitInt8(0); // Terminate the directory list.
381
382 // Second the file table.
383 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
384 assert(!MCDwarfFiles[i].Name.empty());
385 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
386 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
387 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
388 MCOS->emitInt8(0); // Last modification timestamp (always 0).
389 MCOS->emitInt8(0); // File size (always 0).
390 }
391 MCOS->emitInt8(0); // Terminate the file list.
392 }
393
emitOneV5FileEntry(MCStreamer * MCOS,const MCDwarfFile & DwarfFile,bool EmitMD5,bool HasAnySource,std::optional<MCDwarfLineStr> & LineStr)394 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
395 bool EmitMD5, bool HasAnySource,
396 std::optional<MCDwarfLineStr> &LineStr) {
397 assert(!DwarfFile.Name.empty());
398 if (LineStr)
399 LineStr->emitRef(MCOS, DwarfFile.Name);
400 else {
401 MCOS->emitBytes(DwarfFile.Name); // FileName and...
402 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
403 }
404 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
405 if (EmitMD5) {
406 const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
407 MCOS->emitBinaryData(
408 StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));
409 }
410 if (HasAnySource) {
411 if (LineStr)
412 LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef()));
413 else {
414 MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and...
415 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
416 }
417 }
418 }
419
emitV5FileDirTables(MCStreamer * MCOS,std::optional<MCDwarfLineStr> & LineStr) const420 void MCDwarfLineTableHeader::emitV5FileDirTables(
421 MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const {
422 // The directory format, which is just a list of the directory paths. In a
423 // non-split object, these are references to .debug_line_str; in a split
424 // object, they are inline strings.
425 MCOS->emitInt8(1);
426 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
427 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
428 : dwarf::DW_FORM_string);
429 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
430 // Try not to emit an empty compilation directory.
431 SmallString<256> Dir;
432 StringRef CompDir = MCOS->getContext().getCompilationDir();
433 if (!CompilationDir.empty()) {
434 Dir = CompilationDir;
435 MCOS->getContext().remapDebugPath(Dir);
436 CompDir = Dir.str();
437 if (LineStr)
438 CompDir = LineStr->getSaver().save(CompDir);
439 }
440 if (LineStr) {
441 // Record path strings, emit references here.
442 LineStr->emitRef(MCOS, CompDir);
443 for (const auto &Dir : MCDwarfDirs)
444 LineStr->emitRef(MCOS, Dir);
445 } else {
446 // The list of directory paths. Compilation directory comes first.
447 MCOS->emitBytes(CompDir);
448 MCOS->emitBytes(StringRef("\0", 1));
449 for (const auto &Dir : MCDwarfDirs) {
450 MCOS->emitBytes(Dir); // The DirectoryName, and...
451 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
452 }
453 }
454
455 // The file format, which is the inline null-terminated filename and a
456 // directory index. We don't track file size/timestamp so don't emit them
457 // in the v5 table. Emit MD5 checksums and source if we have them.
458 uint64_t Entries = 2;
459 if (HasAllMD5)
460 Entries += 1;
461 if (HasAnySource)
462 Entries += 1;
463 MCOS->emitInt8(Entries);
464 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
465 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
466 : dwarf::DW_FORM_string);
467 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
468 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
469 if (HasAllMD5) {
470 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
471 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
472 }
473 if (HasAnySource) {
474 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
475 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
476 : dwarf::DW_FORM_string);
477 }
478 // Then the counted list of files. The root file is file #0, then emit the
479 // files as provide by .file directives.
480 // MCDwarfFiles has an unused element [0] so use size() not size()+1.
481 // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
482 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
483 // To accommodate assembler source written for DWARF v4 but trying to emit
484 // v5: If we didn't see a root file explicitly, replicate file #1.
485 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
486 "No root file and no .file directives");
487 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
488 HasAllMD5, HasAnySource, LineStr);
489 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
490 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasAnySource, LineStr);
491 }
492
493 std::pair<MCSymbol *, MCSymbol *>
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,ArrayRef<char> StandardOpcodeLengths,std::optional<MCDwarfLineStr> & LineStr) const494 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
495 ArrayRef<char> StandardOpcodeLengths,
496 std::optional<MCDwarfLineStr> &LineStr) const {
497 MCContext &context = MCOS->getContext();
498
499 // Create a symbol at the beginning of the line table.
500 MCSymbol *LineStartSym = Label;
501 if (!LineStartSym)
502 LineStartSym = context.createTempSymbol();
503
504 // Set the value of the symbol, as we are at the start of the line table.
505 MCOS->emitDwarfLineStartLabel(LineStartSym);
506
507 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
508
509 MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
510
511 // Next 2 bytes is the Version.
512 unsigned LineTableVersion = context.getDwarfVersion();
513 MCOS->emitInt16(LineTableVersion);
514
515 // In v5, we get address info next.
516 if (LineTableVersion >= 5) {
517 MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
518 MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
519 }
520
521 // Create symbols for the start/end of the prologue.
522 MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");
523 MCSymbol *ProEndSym = context.createTempSymbol("prologue_end");
524
525 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
526 // actually the length from after the length word, to the end of the prologue.
527 MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
528
529 MCOS->emitLabel(ProStartSym);
530
531 // Parameters of the state machine, are next.
532 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
533 // maximum_operations_per_instruction
534 // For non-VLIW architectures this field is always 1.
535 // FIXME: VLIW architectures need to update this field accordingly.
536 if (LineTableVersion >= 4)
537 MCOS->emitInt8(1);
538 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
539 MCOS->emitInt8(Params.DWARF2LineBase);
540 MCOS->emitInt8(Params.DWARF2LineRange);
541 MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
542
543 // Standard opcode lengths
544 for (char Length : StandardOpcodeLengths)
545 MCOS->emitInt8(Length);
546
547 // Put out the directory and file tables. The formats vary depending on
548 // the version.
549 if (LineTableVersion >= 5)
550 emitV5FileDirTables(MCOS, LineStr);
551 else
552 emitV2FileDirTables(MCOS);
553
554 // This is the end of the prologue, so set the value of the symbol at the
555 // end of the prologue (that was used in a previous expression).
556 MCOS->emitLabel(ProEndSym);
557
558 return std::make_pair(LineStartSym, LineEndSym);
559 }
560
emitCU(MCStreamer * MCOS,MCDwarfLineTableParams Params,std::optional<MCDwarfLineStr> & LineStr) const561 void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
562 std::optional<MCDwarfLineStr> &LineStr) const {
563 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
564
565 // Put out the line tables.
566 for (const auto &LineSec : MCLineSections.getMCLineEntries())
567 emitOne(MCOS, LineSec.first, LineSec.second);
568
569 // This is the end of the section, so set the value of the symbol at the end
570 // of this section (that was used in a previous expression).
571 MCOS->emitLabel(LineEndSym);
572 }
573
574 Expected<unsigned>
tryGetFile(StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,uint16_t DwarfVersion,unsigned FileNumber)575 MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,
576 std::optional<MD5::MD5Result> Checksum,
577 std::optional<StringRef> Source,
578 uint16_t DwarfVersion, unsigned FileNumber) {
579 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
580 FileNumber);
581 }
582
isRootFile(const MCDwarfFile & RootFile,StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum)583 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
584 StringRef &FileName,
585 std::optional<MD5::MD5Result> Checksum) {
586 if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
587 return false;
588 return RootFile.Checksum == Checksum;
589 }
590
591 Expected<unsigned>
tryGetFile(StringRef & Directory,StringRef & FileName,std::optional<MD5::MD5Result> Checksum,std::optional<StringRef> Source,uint16_t DwarfVersion,unsigned FileNumber)592 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,
593 std::optional<MD5::MD5Result> Checksum,
594 std::optional<StringRef> Source,
595 uint16_t DwarfVersion, unsigned FileNumber) {
596 if (Directory == CompilationDir)
597 Directory = "";
598 if (FileName.empty()) {
599 FileName = "<stdin>";
600 Directory = "";
601 }
602 assert(!FileName.empty());
603 // Keep track of whether any or all files have an MD5 checksum.
604 // If any files have embedded source, they all must.
605 if (MCDwarfFiles.empty()) {
606 trackMD5Usage(Checksum.has_value());
607 HasAnySource |= Source.has_value();
608 }
609 if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
610 return 0;
611 if (FileNumber == 0) {
612 // File numbers start with 1 and/or after any file numbers
613 // allocated by inline-assembler .file directives.
614 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
615 SmallString<256> Buffer;
616 auto IterBool = SourceIdMap.insert(
617 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
618 FileNumber));
619 if (!IterBool.second)
620 return IterBool.first->second;
621 }
622 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
623 if (FileNumber >= MCDwarfFiles.size())
624 MCDwarfFiles.resize(FileNumber + 1);
625
626 // Get the new MCDwarfFile slot for this FileNumber.
627 MCDwarfFile &File = MCDwarfFiles[FileNumber];
628
629 // It is an error to see the same number more than once.
630 if (!File.Name.empty())
631 return make_error<StringError>("file number already allocated",
632 inconvertibleErrorCode());
633
634 if (Directory.empty()) {
635 // Separate the directory part from the basename of the FileName.
636 StringRef tFileName = sys::path::filename(FileName);
637 if (!tFileName.empty()) {
638 Directory = sys::path::parent_path(FileName);
639 if (!Directory.empty())
640 FileName = tFileName;
641 }
642 }
643
644 // Find or make an entry in the MCDwarfDirs vector for this Directory.
645 // Capture directory name.
646 unsigned DirIndex;
647 if (Directory.empty()) {
648 // For FileNames with no directories a DirIndex of 0 is used.
649 DirIndex = 0;
650 } else {
651 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
652 if (DirIndex >= MCDwarfDirs.size())
653 MCDwarfDirs.push_back(std::string(Directory));
654 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
655 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
656 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
657 // are stored at MCDwarfFiles[FileNumber].Name .
658 DirIndex++;
659 }
660
661 File.Name = std::string(FileName);
662 File.DirIndex = DirIndex;
663 File.Checksum = Checksum;
664 trackMD5Usage(Checksum.has_value());
665 File.Source = Source;
666 if (Source.has_value())
667 HasAnySource = true;
668
669 // return the allocated FileNumber.
670 return FileNumber;
671 }
672
673 /// Utility function to emit the encoding to a streamer.
Emit(MCStreamer * MCOS,MCDwarfLineTableParams Params,int64_t LineDelta,uint64_t AddrDelta)674 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
675 int64_t LineDelta, uint64_t AddrDelta) {
676 MCContext &Context = MCOS->getContext();
677 SmallString<256> Tmp;
678 MCDwarfLineAddr::encode(Context, Params, LineDelta, AddrDelta, Tmp);
679 MCOS->emitBytes(Tmp);
680 }
681
682 /// Given a special op, return the address skip amount (in units of
683 /// DWARF2_LINE_MIN_INSN_LENGTH).
SpecialAddr(MCDwarfLineTableParams Params,uint64_t op)684 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
685 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
686 }
687
688 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
encode(MCContext & Context,MCDwarfLineTableParams Params,int64_t LineDelta,uint64_t AddrDelta,SmallVectorImpl<char> & Out)689 void MCDwarfLineAddr::encode(MCContext &Context, MCDwarfLineTableParams Params,
690 int64_t LineDelta, uint64_t AddrDelta,
691 SmallVectorImpl<char> &Out) {
692 uint8_t Buf[16];
693 uint64_t Temp, Opcode;
694 bool NeedCopy = false;
695
696 // The maximum address skip amount that can be encoded with a special op.
697 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
698
699 // Scale the address delta by the minimum instruction length.
700 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
701
702 // A LineDelta of INT64_MAX is a signal that this is actually a
703 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
704 // end_sequence to emit the matrix entry.
705 if (LineDelta == INT64_MAX) {
706 if (AddrDelta == MaxSpecialAddrDelta)
707 Out.push_back(dwarf::DW_LNS_const_add_pc);
708 else if (AddrDelta) {
709 Out.push_back(dwarf::DW_LNS_advance_pc);
710 Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
711 }
712 Out.push_back(dwarf::DW_LNS_extended_op);
713 Out.push_back(1);
714 Out.push_back(dwarf::DW_LNE_end_sequence);
715 return;
716 }
717
718 // Bias the line delta by the base.
719 Temp = LineDelta - Params.DWARF2LineBase;
720
721 // If the line increment is out of range of a special opcode, we must encode
722 // it with DW_LNS_advance_line.
723 if (Temp >= Params.DWARF2LineRange ||
724 Temp + Params.DWARF2LineOpcodeBase > 255) {
725 Out.push_back(dwarf::DW_LNS_advance_line);
726 Out.append(Buf, Buf + encodeSLEB128(LineDelta, Buf));
727
728 LineDelta = 0;
729 Temp = 0 - Params.DWARF2LineBase;
730 NeedCopy = true;
731 }
732
733 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
734 if (LineDelta == 0 && AddrDelta == 0) {
735 Out.push_back(dwarf::DW_LNS_copy);
736 return;
737 }
738
739 // Bias the opcode by the special opcode base.
740 Temp += Params.DWARF2LineOpcodeBase;
741
742 // Avoid overflow when addr_delta is large.
743 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
744 // Try using a special opcode.
745 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
746 if (Opcode <= 255) {
747 Out.push_back(Opcode);
748 return;
749 }
750
751 // Try using DW_LNS_const_add_pc followed by special op.
752 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
753 if (Opcode <= 255) {
754 Out.push_back(dwarf::DW_LNS_const_add_pc);
755 Out.push_back(Opcode);
756 return;
757 }
758 }
759
760 // Otherwise use DW_LNS_advance_pc.
761 Out.push_back(dwarf::DW_LNS_advance_pc);
762 Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
763
764 if (NeedCopy)
765 Out.push_back(dwarf::DW_LNS_copy);
766 else {
767 assert(Temp <= 255 && "Buggy special opcode encoding.");
768 Out.push_back(Temp);
769 }
770 }
771
772 // Utility function to write a tuple for .debug_abbrev.
EmitAbbrev(MCStreamer * MCOS,uint64_t Name,uint64_t Form)773 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
774 MCOS->emitULEB128IntValue(Name);
775 MCOS->emitULEB128IntValue(Form);
776 }
777
778 // When generating dwarf for assembly source files this emits
779 // the data for .debug_abbrev section which contains three DIEs.
EmitGenDwarfAbbrev(MCStreamer * MCOS)780 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
781 MCContext &context = MCOS->getContext();
782 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
783
784 // DW_TAG_compile_unit DIE abbrev (1).
785 MCOS->emitULEB128IntValue(1);
786 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
787 MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
788 dwarf::Form SecOffsetForm =
789 context.getDwarfVersion() >= 4
790 ? dwarf::DW_FORM_sec_offset
791 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
792 : dwarf::DW_FORM_data4);
793 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
794 if (context.getGenDwarfSectionSyms().size() > 1 &&
795 context.getDwarfVersion() >= 3) {
796 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
797 } else {
798 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
799 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
800 }
801 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
802 if (!context.getCompilationDir().empty())
803 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
804 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
805 if (!DwarfDebugFlags.empty())
806 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
807 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
808 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
809 EmitAbbrev(MCOS, 0, 0);
810
811 // DW_TAG_label DIE abbrev (2).
812 MCOS->emitULEB128IntValue(2);
813 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
814 MCOS->emitInt8(dwarf::DW_CHILDREN_no);
815 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
816 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
817 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
818 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
819 EmitAbbrev(MCOS, 0, 0);
820
821 // Terminate the abbreviations for this compilation unit.
822 MCOS->emitInt8(0);
823 }
824
825 // When generating dwarf for assembly source files this emits the data for
826 // .debug_aranges section. This section contains a header and a table of pairs
827 // of PointerSize'ed values for the address and size of section(s) with line
828 // table entries.
EmitGenDwarfAranges(MCStreamer * MCOS,const MCSymbol * InfoSectionSymbol)829 static void EmitGenDwarfAranges(MCStreamer *MCOS,
830 const MCSymbol *InfoSectionSymbol) {
831 MCContext &context = MCOS->getContext();
832
833 auto &Sections = context.getGenDwarfSectionSyms();
834
835 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
836
837 unsigned UnitLengthBytes =
838 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
839 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
840
841 // This will be the length of the .debug_aranges section, first account for
842 // the size of each item in the header (see below where we emit these items).
843 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
844
845 // Figure the padding after the header before the table of address and size
846 // pairs who's values are PointerSize'ed.
847 const MCAsmInfo *asmInfo = context.getAsmInfo();
848 int AddrSize = asmInfo->getCodePointerSize();
849 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
850 if (Pad == 2 * AddrSize)
851 Pad = 0;
852 Length += Pad;
853
854 // Add the size of the pair of PointerSize'ed values for the address and size
855 // of each section we have in the table.
856 Length += 2 * AddrSize * Sections.size();
857 // And the pair of terminating zeros.
858 Length += 2 * AddrSize;
859
860 // Emit the header for this section.
861 if (context.getDwarfFormat() == dwarf::DWARF64)
862 // The DWARF64 mark.
863 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
864 // The 4 (8 for DWARF64) byte length not including the length of the unit
865 // length field itself.
866 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
867 // The 2 byte version, which is 2.
868 MCOS->emitInt16(2);
869 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
870 // from the start of the .debug_info.
871 if (InfoSectionSymbol)
872 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
873 asmInfo->needsDwarfSectionOffsetDirective());
874 else
875 MCOS->emitIntValue(0, OffsetSize);
876 // The 1 byte size of an address.
877 MCOS->emitInt8(AddrSize);
878 // The 1 byte size of a segment descriptor, we use a value of zero.
879 MCOS->emitInt8(0);
880 // Align the header with the padding if needed, before we put out the table.
881 for(int i = 0; i < Pad; i++)
882 MCOS->emitInt8(0);
883
884 // Now emit the table of pairs of PointerSize'ed values for the section
885 // addresses and sizes.
886 for (MCSection *Sec : Sections) {
887 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
888 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
889 assert(StartSymbol && "StartSymbol must not be NULL");
890 assert(EndSymbol && "EndSymbol must not be NULL");
891
892 const MCExpr *Addr = MCSymbolRefExpr::create(
893 StartSymbol, MCSymbolRefExpr::VK_None, context);
894 const MCExpr *Size =
895 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
896 MCOS->emitValue(Addr, AddrSize);
897 emitAbsValue(*MCOS, Size, AddrSize);
898 }
899
900 // And finally the pair of terminating zeros.
901 MCOS->emitIntValue(0, AddrSize);
902 MCOS->emitIntValue(0, AddrSize);
903 }
904
905 // When generating dwarf for assembly source files this emits the data for
906 // .debug_info section which contains three parts. The header, the compile_unit
907 // DIE and a list of label DIEs.
EmitGenDwarfInfo(MCStreamer * MCOS,const MCSymbol * AbbrevSectionSymbol,const MCSymbol * LineSectionSymbol,const MCSymbol * RangesSymbol)908 static void EmitGenDwarfInfo(MCStreamer *MCOS,
909 const MCSymbol *AbbrevSectionSymbol,
910 const MCSymbol *LineSectionSymbol,
911 const MCSymbol *RangesSymbol) {
912 MCContext &context = MCOS->getContext();
913
914 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
915
916 // Create a symbol at the start and end of this section used in here for the
917 // expression to calculate the length in the header.
918 MCSymbol *InfoStart = context.createTempSymbol();
919 MCOS->emitLabel(InfoStart);
920 MCSymbol *InfoEnd = context.createTempSymbol();
921
922 // First part: the header.
923
924 unsigned UnitLengthBytes =
925 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
926 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
927
928 if (context.getDwarfFormat() == dwarf::DWARF64)
929 // Emit DWARF64 mark.
930 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
931
932 // The 4 (8 for DWARF64) byte total length of the information for this
933 // compilation unit, not including the unit length field itself.
934 const MCExpr *Length =
935 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
936 emitAbsValue(*MCOS, Length, OffsetSize);
937
938 // The 2 byte DWARF version.
939 MCOS->emitInt16(context.getDwarfVersion());
940
941 // The DWARF v5 header has unit type, address size, abbrev offset.
942 // Earlier versions have abbrev offset, address size.
943 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
944 int AddrSize = AsmInfo.getCodePointerSize();
945 if (context.getDwarfVersion() >= 5) {
946 MCOS->emitInt8(dwarf::DW_UT_compile);
947 MCOS->emitInt8(AddrSize);
948 }
949 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
950 // the .debug_abbrev.
951 if (AbbrevSectionSymbol)
952 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
953 AsmInfo.needsDwarfSectionOffsetDirective());
954 else
955 // Since the abbrevs are at the start of the section, the offset is zero.
956 MCOS->emitIntValue(0, OffsetSize);
957 if (context.getDwarfVersion() <= 4)
958 MCOS->emitInt8(AddrSize);
959
960 // Second part: the compile_unit DIE.
961
962 // The DW_TAG_compile_unit DIE abbrev (1).
963 MCOS->emitULEB128IntValue(1);
964
965 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
966 // .debug_line section.
967 if (LineSectionSymbol)
968 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
969 AsmInfo.needsDwarfSectionOffsetDirective());
970 else
971 // The line table is at the start of the section, so the offset is zero.
972 MCOS->emitIntValue(0, OffsetSize);
973
974 if (RangesSymbol) {
975 // There are multiple sections containing code, so we must use
976 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
977 // start of the .debug_ranges/.debug_rnglists.
978 MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
979 } else {
980 // If we only have one non-empty code section, we can use the simpler
981 // AT_low_pc and AT_high_pc attributes.
982
983 // Find the first (and only) non-empty text section
984 auto &Sections = context.getGenDwarfSectionSyms();
985 const auto TextSection = Sections.begin();
986 assert(TextSection != Sections.end() && "No text section found");
987
988 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
989 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
990 assert(StartSymbol && "StartSymbol must not be NULL");
991 assert(EndSymbol && "EndSymbol must not be NULL");
992
993 // AT_low_pc, the first address of the default .text section.
994 const MCExpr *Start = MCSymbolRefExpr::create(
995 StartSymbol, MCSymbolRefExpr::VK_None, context);
996 MCOS->emitValue(Start, AddrSize);
997
998 // AT_high_pc, the last address of the default .text section.
999 const MCExpr *End = MCSymbolRefExpr::create(
1000 EndSymbol, MCSymbolRefExpr::VK_None, context);
1001 MCOS->emitValue(End, AddrSize);
1002 }
1003
1004 // AT_name, the name of the source file. Reconstruct from the first directory
1005 // and file table entries.
1006 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
1007 if (MCDwarfDirs.size() > 0) {
1008 MCOS->emitBytes(MCDwarfDirs[0]);
1009 MCOS->emitBytes(sys::path::get_separator());
1010 }
1011 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
1012 // MCDwarfFiles might be empty if we have an empty source file.
1013 // If it's not empty, [0] is unused and [1] is the first actual file.
1014 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1015 const MCDwarfFile &RootFile =
1016 MCDwarfFiles.empty()
1017 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1018 : MCDwarfFiles[1];
1019 MCOS->emitBytes(RootFile.Name);
1020 MCOS->emitInt8(0); // NULL byte to terminate the string.
1021
1022 // AT_comp_dir, the working directory the assembly was done in.
1023 if (!context.getCompilationDir().empty()) {
1024 MCOS->emitBytes(context.getCompilationDir());
1025 MCOS->emitInt8(0); // NULL byte to terminate the string.
1026 }
1027
1028 // AT_APPLE_flags, the command line arguments of the assembler tool.
1029 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1030 if (!DwarfDebugFlags.empty()){
1031 MCOS->emitBytes(DwarfDebugFlags);
1032 MCOS->emitInt8(0); // NULL byte to terminate the string.
1033 }
1034
1035 // AT_producer, the version of the assembler tool.
1036 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1037 if (!DwarfDebugProducer.empty())
1038 MCOS->emitBytes(DwarfDebugProducer);
1039 else
1040 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1041 MCOS->emitInt8(0); // NULL byte to terminate the string.
1042
1043 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
1044 // draft has no standard code for assembler.
1045 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
1046
1047 // Third part: the list of label DIEs.
1048
1049 // Loop on saved info for dwarf labels and create the DIEs for them.
1050 const std::vector<MCGenDwarfLabelEntry> &Entries =
1051 MCOS->getContext().getMCGenDwarfLabelEntries();
1052 for (const auto &Entry : Entries) {
1053 // The DW_TAG_label DIE abbrev (2).
1054 MCOS->emitULEB128IntValue(2);
1055
1056 // AT_name, of the label without any leading underbar.
1057 MCOS->emitBytes(Entry.getName());
1058 MCOS->emitInt8(0); // NULL byte to terminate the string.
1059
1060 // AT_decl_file, index into the file table.
1061 MCOS->emitInt32(Entry.getFileNumber());
1062
1063 // AT_decl_line, source line number.
1064 MCOS->emitInt32(Entry.getLineNumber());
1065
1066 // AT_low_pc, start address of the label.
1067 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
1068 MCSymbolRefExpr::VK_None, context);
1069 MCOS->emitValue(AT_low_pc, AddrSize);
1070 }
1071
1072 // Add the NULL DIE terminating the Compile Unit DIE's.
1073 MCOS->emitInt8(0);
1074
1075 // Now set the value of the symbol at the end of the info section.
1076 MCOS->emitLabel(InfoEnd);
1077 }
1078
1079 // When generating dwarf for assembly source files this emits the data for
1080 // .debug_ranges section. We only emit one range list, which spans all of the
1081 // executable sections of this file.
emitGenDwarfRanges(MCStreamer * MCOS)1082 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1083 MCContext &context = MCOS->getContext();
1084 auto &Sections = context.getGenDwarfSectionSyms();
1085
1086 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1087 int AddrSize = AsmInfo->getCodePointerSize();
1088 MCSymbol *RangesSymbol;
1089
1090 if (MCOS->getContext().getDwarfVersion() >= 5) {
1091 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
1092 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
1093 MCOS->AddComment("Offset entry count");
1094 MCOS->emitInt32(0);
1095 RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
1096 MCOS->emitLabel(RangesSymbol);
1097 for (MCSection *Sec : Sections) {
1098 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1099 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1100 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1101 StartSymbol, MCSymbolRefExpr::VK_None, context);
1102 const MCExpr *SectionSize =
1103 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1104 MCOS->emitInt8(dwarf::DW_RLE_start_length);
1105 MCOS->emitValue(SectionStartAddr, AddrSize);
1106 MCOS->emitULEB128Value(SectionSize);
1107 }
1108 MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
1109 MCOS->emitLabel(EndSymbol);
1110 } else {
1111 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1112 RangesSymbol = context.createTempSymbol("debug_ranges_start");
1113 MCOS->emitLabel(RangesSymbol);
1114 for (MCSection *Sec : Sections) {
1115 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1116 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1117
1118 // Emit a base address selection entry for the section start.
1119 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1120 StartSymbol, MCSymbolRefExpr::VK_None, context);
1121 MCOS->emitFill(AddrSize, 0xFF);
1122 MCOS->emitValue(SectionStartAddr, AddrSize);
1123
1124 // Emit a range list entry spanning this section.
1125 const MCExpr *SectionSize =
1126 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1127 MCOS->emitIntValue(0, AddrSize);
1128 emitAbsValue(*MCOS, SectionSize, AddrSize);
1129 }
1130
1131 // Emit end of list entry
1132 MCOS->emitIntValue(0, AddrSize);
1133 MCOS->emitIntValue(0, AddrSize);
1134 }
1135
1136 return RangesSymbol;
1137 }
1138
1139 //
1140 // When generating dwarf for assembly source files this emits the Dwarf
1141 // sections.
1142 //
Emit(MCStreamer * MCOS)1143 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1144 MCContext &context = MCOS->getContext();
1145
1146 // Create the dwarf sections in this order (.debug_line already created).
1147 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1148 bool CreateDwarfSectionSymbols =
1149 AsmInfo->doesDwarfUseRelocationsAcrossSections();
1150 MCSymbol *LineSectionSymbol = nullptr;
1151 if (CreateDwarfSectionSymbols)
1152 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
1153 MCSymbol *AbbrevSectionSymbol = nullptr;
1154 MCSymbol *InfoSectionSymbol = nullptr;
1155 MCSymbol *RangesSymbol = nullptr;
1156
1157 // Create end symbols for each section, and remove empty sections
1158 MCOS->getContext().finalizeDwarfSections(*MCOS);
1159
1160 // If there are no sections to generate debug info for, we don't need
1161 // to do anything
1162 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1163 return;
1164
1165 // We only use the .debug_ranges section if we have multiple code sections,
1166 // and we are emitting a DWARF version which supports it.
1167 const bool UseRangesSection =
1168 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1169 MCOS->getContext().getDwarfVersion() >= 3;
1170 CreateDwarfSectionSymbols |= UseRangesSection;
1171
1172 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
1173 if (CreateDwarfSectionSymbols) {
1174 InfoSectionSymbol = context.createTempSymbol();
1175 MCOS->emitLabel(InfoSectionSymbol);
1176 }
1177 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
1178 if (CreateDwarfSectionSymbols) {
1179 AbbrevSectionSymbol = context.createTempSymbol();
1180 MCOS->emitLabel(AbbrevSectionSymbol);
1181 }
1182
1183 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
1184
1185 // Output the data for .debug_aranges section.
1186 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1187
1188 if (UseRangesSection) {
1189 RangesSymbol = emitGenDwarfRanges(MCOS);
1190 assert(RangesSymbol);
1191 }
1192
1193 // Output the data for .debug_abbrev section.
1194 EmitGenDwarfAbbrev(MCOS);
1195
1196 // Output the data for .debug_info section.
1197 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1198 }
1199
1200 //
1201 // When generating dwarf for assembly source files this is called when symbol
1202 // for a label is created. If this symbol is not a temporary and is in the
1203 // section that dwarf is being generated for, save the needed info to create
1204 // a dwarf label.
1205 //
Make(MCSymbol * Symbol,MCStreamer * MCOS,SourceMgr & SrcMgr,SMLoc & Loc)1206 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1207 SourceMgr &SrcMgr, SMLoc &Loc) {
1208 // We won't create dwarf labels for temporary symbols.
1209 if (Symbol->isTemporary())
1210 return;
1211 MCContext &context = MCOS->getContext();
1212 // We won't create dwarf labels for symbols in sections that we are not
1213 // generating debug info for.
1214 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
1215 return;
1216
1217 // The dwarf label's name does not have the symbol name's leading
1218 // underbar if any.
1219 StringRef Name = Symbol->getName();
1220 if (Name.starts_with("_"))
1221 Name = Name.substr(1, Name.size()-1);
1222
1223 // Get the dwarf file number to be used for the dwarf label.
1224 unsigned FileNumber = context.getGenDwarfFileNumber();
1225
1226 // Finding the line number is the expensive part which is why we just don't
1227 // pass it in as for some symbols we won't create a dwarf label.
1228 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1229 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
1230
1231 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1232 // values so that they don't have things like an ARM thumb bit from the
1233 // original symbol. So when used they won't get a low bit set after
1234 // relocation.
1235 MCSymbol *Label = context.createTempSymbol();
1236 MCOS->emitLabel(Label);
1237
1238 // Create and entry for the info and add it to the other entries.
1239 MCOS->getContext().addMCGenDwarfLabelEntry(
1240 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1241 }
1242
getDataAlignmentFactor(MCStreamer & streamer)1243 static int getDataAlignmentFactor(MCStreamer &streamer) {
1244 MCContext &context = streamer.getContext();
1245 const MCAsmInfo *asmInfo = context.getAsmInfo();
1246 int size = asmInfo->getCalleeSaveStackSlotSize();
1247 if (asmInfo->isStackGrowthDirectionUp())
1248 return size;
1249 else
1250 return -size;
1251 }
1252
getSizeForEncoding(MCStreamer & streamer,unsigned symbolEncoding)1253 static unsigned getSizeForEncoding(MCStreamer &streamer,
1254 unsigned symbolEncoding) {
1255 MCContext &context = streamer.getContext();
1256 unsigned format = symbolEncoding & 0x0f;
1257 switch (format) {
1258 default: llvm_unreachable("Unknown Encoding");
1259 case dwarf::DW_EH_PE_absptr:
1260 case dwarf::DW_EH_PE_signed:
1261 return context.getAsmInfo()->getCodePointerSize();
1262 case dwarf::DW_EH_PE_udata2:
1263 case dwarf::DW_EH_PE_sdata2:
1264 return 2;
1265 case dwarf::DW_EH_PE_udata4:
1266 case dwarf::DW_EH_PE_sdata4:
1267 return 4;
1268 case dwarf::DW_EH_PE_udata8:
1269 case dwarf::DW_EH_PE_sdata8:
1270 return 8;
1271 }
1272 }
1273
emitFDESymbol(MCObjectStreamer & streamer,const MCSymbol & symbol,unsigned symbolEncoding,bool isEH)1274 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1275 unsigned symbolEncoding, bool isEH) {
1276 MCContext &context = streamer.getContext();
1277 const MCAsmInfo *asmInfo = context.getAsmInfo();
1278 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1279 symbolEncoding,
1280 streamer);
1281 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1282 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1283 emitAbsValue(streamer, v, size);
1284 else
1285 streamer.emitValue(v, size);
1286 }
1287
EmitPersonality(MCStreamer & streamer,const MCSymbol & symbol,unsigned symbolEncoding)1288 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1289 unsigned symbolEncoding) {
1290 MCContext &context = streamer.getContext();
1291 const MCAsmInfo *asmInfo = context.getAsmInfo();
1292 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1293 symbolEncoding,
1294 streamer);
1295 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1296 streamer.emitValue(v, size);
1297 }
1298
1299 namespace {
1300
1301 class FrameEmitterImpl {
1302 int64_t CFAOffset = 0;
1303 int64_t InitialCFAOffset = 0;
1304 bool IsEH;
1305 MCObjectStreamer &Streamer;
1306
1307 public:
FrameEmitterImpl(bool IsEH,MCObjectStreamer & Streamer)1308 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1309 : IsEH(IsEH), Streamer(Streamer) {}
1310
1311 /// Emit the unwind information in a compact way.
1312 void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1313
1314 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1315 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1316 bool LastInSection, const MCSymbol &SectionStart);
1317 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1318 MCSymbol *BaseLabel);
1319 void emitCFIInstruction(const MCCFIInstruction &Instr);
1320 };
1321
1322 } // end anonymous namespace
1323
emitEncodingByte(MCObjectStreamer & Streamer,unsigned Encoding)1324 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1325 Streamer.emitInt8(Encoding);
1326 }
1327
emitCFIInstruction(const MCCFIInstruction & Instr)1328 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1329 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1330 auto *MRI = Streamer.getContext().getRegisterInfo();
1331
1332 switch (Instr.getOperation()) {
1333 case MCCFIInstruction::OpRegister: {
1334 unsigned Reg1 = Instr.getRegister();
1335 unsigned Reg2 = Instr.getRegister2();
1336 if (!IsEH) {
1337 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
1338 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
1339 }
1340 Streamer.emitInt8(dwarf::DW_CFA_register);
1341 Streamer.emitULEB128IntValue(Reg1);
1342 Streamer.emitULEB128IntValue(Reg2);
1343 return;
1344 }
1345 case MCCFIInstruction::OpWindowSave:
1346 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
1347 return;
1348
1349 case MCCFIInstruction::OpNegateRAState:
1350 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
1351 return;
1352
1353 case MCCFIInstruction::OpUndefined: {
1354 unsigned Reg = Instr.getRegister();
1355 Streamer.emitInt8(dwarf::DW_CFA_undefined);
1356 Streamer.emitULEB128IntValue(Reg);
1357 return;
1358 }
1359 case MCCFIInstruction::OpAdjustCfaOffset:
1360 case MCCFIInstruction::OpDefCfaOffset: {
1361 const bool IsRelative =
1362 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1363
1364 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
1365
1366 if (IsRelative)
1367 CFAOffset += Instr.getOffset();
1368 else
1369 CFAOffset = Instr.getOffset();
1370
1371 Streamer.emitULEB128IntValue(CFAOffset);
1372
1373 return;
1374 }
1375 case MCCFIInstruction::OpDefCfa: {
1376 unsigned Reg = Instr.getRegister();
1377 if (!IsEH)
1378 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1379 Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
1380 Streamer.emitULEB128IntValue(Reg);
1381 CFAOffset = Instr.getOffset();
1382 Streamer.emitULEB128IntValue(CFAOffset);
1383
1384 return;
1385 }
1386 case MCCFIInstruction::OpDefCfaRegister: {
1387 unsigned Reg = Instr.getRegister();
1388 if (!IsEH)
1389 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1390 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
1391 Streamer.emitULEB128IntValue(Reg);
1392
1393 return;
1394 }
1395 // TODO: Implement `_sf` variants if/when they need to be emitted.
1396 case MCCFIInstruction::OpLLVMDefAspaceCfa: {
1397 unsigned Reg = Instr.getRegister();
1398 if (!IsEH)
1399 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1400 Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);
1401 Streamer.emitULEB128IntValue(Reg);
1402 CFAOffset = Instr.getOffset();
1403 Streamer.emitULEB128IntValue(CFAOffset);
1404 Streamer.emitULEB128IntValue(Instr.getAddressSpace());
1405
1406 return;
1407 }
1408 case MCCFIInstruction::OpOffset:
1409 case MCCFIInstruction::OpRelOffset: {
1410 const bool IsRelative =
1411 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1412
1413 unsigned Reg = Instr.getRegister();
1414 if (!IsEH)
1415 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1416
1417 int64_t Offset = Instr.getOffset();
1418 if (IsRelative)
1419 Offset -= CFAOffset;
1420 Offset = Offset / dataAlignmentFactor;
1421
1422 if (Offset < 0) {
1423 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
1424 Streamer.emitULEB128IntValue(Reg);
1425 Streamer.emitSLEB128IntValue(Offset);
1426 } else if (Reg < 64) {
1427 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
1428 Streamer.emitULEB128IntValue(Offset);
1429 } else {
1430 Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
1431 Streamer.emitULEB128IntValue(Reg);
1432 Streamer.emitULEB128IntValue(Offset);
1433 }
1434 return;
1435 }
1436 case MCCFIInstruction::OpRememberState:
1437 Streamer.emitInt8(dwarf::DW_CFA_remember_state);
1438 return;
1439 case MCCFIInstruction::OpRestoreState:
1440 Streamer.emitInt8(dwarf::DW_CFA_restore_state);
1441 return;
1442 case MCCFIInstruction::OpSameValue: {
1443 unsigned Reg = Instr.getRegister();
1444 Streamer.emitInt8(dwarf::DW_CFA_same_value);
1445 Streamer.emitULEB128IntValue(Reg);
1446 return;
1447 }
1448 case MCCFIInstruction::OpRestore: {
1449 unsigned Reg = Instr.getRegister();
1450 if (!IsEH)
1451 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1452 if (Reg < 64) {
1453 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
1454 } else {
1455 Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
1456 Streamer.emitULEB128IntValue(Reg);
1457 }
1458 return;
1459 }
1460 case MCCFIInstruction::OpGnuArgsSize:
1461 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
1462 Streamer.emitULEB128IntValue(Instr.getOffset());
1463 return;
1464
1465 case MCCFIInstruction::OpEscape:
1466 Streamer.emitBytes(Instr.getValues());
1467 return;
1468 case MCCFIInstruction::OpLabel:
1469 Streamer.emitLabel(Instr.getCfiLabel(), Instr.getLoc());
1470 return;
1471 }
1472 llvm_unreachable("Unhandled case in switch");
1473 }
1474
1475 /// Emit frame instructions to describe the layout of the frame.
emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,MCSymbol * BaseLabel)1476 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1477 MCSymbol *BaseLabel) {
1478 for (const MCCFIInstruction &Instr : Instrs) {
1479 MCSymbol *Label = Instr.getLabel();
1480 // Throw out move if the label is invalid.
1481 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1482
1483 // Advance row if new location.
1484 if (BaseLabel && Label) {
1485 MCSymbol *ThisSym = Label;
1486 if (ThisSym != BaseLabel) {
1487 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym, Instr.getLoc());
1488 BaseLabel = ThisSym;
1489 }
1490 }
1491
1492 emitCFIInstruction(Instr);
1493 }
1494 }
1495
1496 /// Emit the unwind information in a compact way.
EmitCompactUnwind(const MCDwarfFrameInfo & Frame)1497 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1498 MCContext &Context = Streamer.getContext();
1499 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1500
1501 // range-start range-length compact-unwind-enc personality-func lsda
1502 // _foo LfooEnd-_foo 0x00000023 0 0
1503 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1504 //
1505 // .section __LD,__compact_unwind,regular,debug
1506 //
1507 // # compact unwind for _foo
1508 // .quad _foo
1509 // .set L1,LfooEnd-_foo
1510 // .long L1
1511 // .long 0x01010001
1512 // .quad 0
1513 // .quad 0
1514 //
1515 // # compact unwind for _bar
1516 // .quad _bar
1517 // .set L2,LbarEnd-_bar
1518 // .long L2
1519 // .long 0x01020011
1520 // .quad __gxx_personality
1521 // .quad except_tab1
1522
1523 uint32_t Encoding = Frame.CompactUnwindEncoding;
1524 if (!Encoding) return;
1525 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1526
1527 // The encoding needs to know we have an LSDA.
1528 if (!DwarfEHFrameOnly && Frame.Lsda)
1529 Encoding |= 0x40000000;
1530
1531 // Range Start
1532 unsigned FDEEncoding = MOFI->getFDEEncoding();
1533 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1534 Streamer.emitSymbolValue(Frame.Begin, Size);
1535
1536 // Range Length
1537 const MCExpr *Range =
1538 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
1539 emitAbsValue(Streamer, Range, 4);
1540
1541 // Compact Encoding
1542 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1543 Streamer.emitIntValue(Encoding, Size);
1544
1545 // Personality Function
1546 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1547 if (!DwarfEHFrameOnly && Frame.Personality)
1548 Streamer.emitSymbolValue(Frame.Personality, Size);
1549 else
1550 Streamer.emitIntValue(0, Size); // No personality fn
1551
1552 // LSDA
1553 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1554 if (!DwarfEHFrameOnly && Frame.Lsda)
1555 Streamer.emitSymbolValue(Frame.Lsda, Size);
1556 else
1557 Streamer.emitIntValue(0, Size); // No LSDA
1558 }
1559
getCIEVersion(bool IsEH,unsigned DwarfVersion)1560 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1561 if (IsEH)
1562 return 1;
1563 switch (DwarfVersion) {
1564 case 2:
1565 return 1;
1566 case 3:
1567 return 3;
1568 case 4:
1569 case 5:
1570 return 4;
1571 }
1572 llvm_unreachable("Unknown version");
1573 }
1574
EmitCIE(const MCDwarfFrameInfo & Frame)1575 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1576 MCContext &context = Streamer.getContext();
1577 const MCRegisterInfo *MRI = context.getRegisterInfo();
1578 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1579
1580 MCSymbol *sectionStart = context.createTempSymbol();
1581 Streamer.emitLabel(sectionStart);
1582
1583 MCSymbol *sectionEnd = context.createTempSymbol();
1584
1585 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1586 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1587 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1588 bool IsDwarf64 = Format == dwarf::DWARF64;
1589
1590 if (IsDwarf64)
1591 // DWARF64 mark
1592 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1593
1594 // Length
1595 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
1596 *sectionEnd, UnitLengthBytes);
1597 emitAbsValue(Streamer, Length, OffsetSize);
1598
1599 // CIE ID
1600 uint64_t CIE_ID =
1601 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1602 Streamer.emitIntValue(CIE_ID, OffsetSize);
1603
1604 // Version
1605 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1606 Streamer.emitInt8(CIEVersion);
1607
1608 if (IsEH) {
1609 SmallString<8> Augmentation;
1610 Augmentation += "z";
1611 if (Frame.Personality)
1612 Augmentation += "P";
1613 if (Frame.Lsda)
1614 Augmentation += "L";
1615 Augmentation += "R";
1616 if (Frame.IsSignalFrame)
1617 Augmentation += "S";
1618 if (Frame.IsBKeyFrame)
1619 Augmentation += "B";
1620 if (Frame.IsMTETaggedFrame)
1621 Augmentation += "G";
1622 Streamer.emitBytes(Augmentation);
1623 }
1624 Streamer.emitInt8(0);
1625
1626 if (CIEVersion >= 4) {
1627 // Address Size
1628 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
1629
1630 // Segment Descriptor Size
1631 Streamer.emitInt8(0);
1632 }
1633
1634 // Code Alignment Factor
1635 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1636
1637 // Data Alignment Factor
1638 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1639
1640 // Return Address Register
1641 unsigned RAReg = Frame.RAReg;
1642 if (RAReg == static_cast<unsigned>(INT_MAX))
1643 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
1644
1645 if (CIEVersion == 1) {
1646 assert(RAReg <= 255 &&
1647 "DWARF 2 encodes return_address_register in one byte");
1648 Streamer.emitInt8(RAReg);
1649 } else {
1650 Streamer.emitULEB128IntValue(RAReg);
1651 }
1652
1653 // Augmentation Data Length (optional)
1654 unsigned augmentationLength = 0;
1655 if (IsEH) {
1656 if (Frame.Personality) {
1657 // Personality Encoding
1658 augmentationLength += 1;
1659 // Personality
1660 augmentationLength +=
1661 getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
1662 }
1663 if (Frame.Lsda)
1664 augmentationLength += 1;
1665 // Encoding of the FDE pointers
1666 augmentationLength += 1;
1667
1668 Streamer.emitULEB128IntValue(augmentationLength);
1669
1670 // Augmentation Data (optional)
1671 if (Frame.Personality) {
1672 // Personality Encoding
1673 emitEncodingByte(Streamer, Frame.PersonalityEncoding);
1674 // Personality
1675 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
1676 }
1677
1678 if (Frame.Lsda)
1679 emitEncodingByte(Streamer, Frame.LsdaEncoding);
1680
1681 // Encoding of the FDE pointers
1682 emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1683 }
1684
1685 // Initial Instructions
1686
1687 const MCAsmInfo *MAI = context.getAsmInfo();
1688 if (!Frame.IsSimple) {
1689 const std::vector<MCCFIInstruction> &Instructions =
1690 MAI->getInitialFrameState();
1691 emitCFIInstructions(Instructions, nullptr);
1692 }
1693
1694 InitialCFAOffset = CFAOffset;
1695
1696 // Padding
1697 Streamer.emitValueToAlignment(Align(IsEH ? 4 : MAI->getCodePointerSize()));
1698
1699 Streamer.emitLabel(sectionEnd);
1700 return *sectionStart;
1701 }
1702
EmitFDE(const MCSymbol & cieStart,const MCDwarfFrameInfo & frame,bool LastInSection,const MCSymbol & SectionStart)1703 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1704 const MCDwarfFrameInfo &frame,
1705 bool LastInSection,
1706 const MCSymbol &SectionStart) {
1707 MCContext &context = Streamer.getContext();
1708 MCSymbol *fdeStart = context.createTempSymbol();
1709 MCSymbol *fdeEnd = context.createTempSymbol();
1710 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1711
1712 CFAOffset = InitialCFAOffset;
1713
1714 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1715 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1716
1717 if (Format == dwarf::DWARF64)
1718 // DWARF64 mark
1719 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1720
1721 // Length
1722 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
1723 emitAbsValue(Streamer, Length, OffsetSize);
1724
1725 Streamer.emitLabel(fdeStart);
1726
1727 // CIE Pointer
1728 const MCAsmInfo *asmInfo = context.getAsmInfo();
1729 if (IsEH) {
1730 const MCExpr *offset =
1731 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
1732 emitAbsValue(Streamer, offset, OffsetSize);
1733 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1734 const MCExpr *offset =
1735 makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
1736 emitAbsValue(Streamer, offset, OffsetSize);
1737 } else {
1738 Streamer.emitSymbolValue(&cieStart, OffsetSize,
1739 asmInfo->needsDwarfSectionOffsetDirective());
1740 }
1741
1742 // PC Begin
1743 unsigned PCEncoding =
1744 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1745 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1746 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1747
1748 // PC Range
1749 const MCExpr *Range =
1750 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
1751 emitAbsValue(Streamer, Range, PCSize);
1752
1753 if (IsEH) {
1754 // Augmentation Data Length
1755 unsigned augmentationLength = 0;
1756
1757 if (frame.Lsda)
1758 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1759
1760 Streamer.emitULEB128IntValue(augmentationLength);
1761
1762 // Augmentation Data
1763 if (frame.Lsda)
1764 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1765 }
1766
1767 // Call Frame Instructions
1768 emitCFIInstructions(frame.Instructions, frame.Begin);
1769
1770 // Padding
1771 // The size of a .eh_frame section has to be a multiple of the alignment
1772 // since a null CIE is interpreted as the end. Old systems overaligned
1773 // .eh_frame, so we do too and account for it in the last FDE.
1774 unsigned Alignment = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1775 Streamer.emitValueToAlignment(Align(Alignment));
1776
1777 Streamer.emitLabel(fdeEnd);
1778 }
1779
1780 namespace {
1781
1782 struct CIEKey {
1783 CIEKey() = default;
1784
CIEKey__anon9ac4b6f30311::CIEKey1785 explicit CIEKey(const MCDwarfFrameInfo &Frame)
1786 : Personality(Frame.Personality),
1787 PersonalityEncoding(Frame.PersonalityEncoding),
1788 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
1789 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1790 IsBKeyFrame(Frame.IsBKeyFrame),
1791 IsMTETaggedFrame(Frame.IsMTETaggedFrame) {}
1792
PersonalityName__anon9ac4b6f30311::CIEKey1793 StringRef PersonalityName() const {
1794 if (!Personality)
1795 return StringRef();
1796 return Personality->getName();
1797 }
1798
operator <__anon9ac4b6f30311::CIEKey1799 bool operator<(const CIEKey &Other) const {
1800 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1801 IsSignalFrame, IsSimple, RAReg, IsBKeyFrame,
1802 IsMTETaggedFrame) <
1803 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
1804 Other.LsdaEncoding, Other.IsSignalFrame,
1805 Other.IsSimple, Other.RAReg, Other.IsBKeyFrame,
1806 Other.IsMTETaggedFrame);
1807 }
1808
operator ==__anon9ac4b6f30311::CIEKey1809 bool operator==(const CIEKey &Other) const {
1810 return Personality == Other.Personality &&
1811 PersonalityEncoding == Other.PersonalityEncoding &&
1812 LsdaEncoding == Other.LsdaEncoding &&
1813 IsSignalFrame == Other.IsSignalFrame && IsSimple == Other.IsSimple &&
1814 RAReg == Other.RAReg && IsBKeyFrame == Other.IsBKeyFrame &&
1815 IsMTETaggedFrame == Other.IsMTETaggedFrame;
1816 }
operator !=__anon9ac4b6f30311::CIEKey1817 bool operator!=(const CIEKey &Other) const { return !(*this == Other); }
1818
1819 const MCSymbol *Personality = nullptr;
1820 unsigned PersonalityEncoding = 0;
1821 unsigned LsdaEncoding = -1;
1822 bool IsSignalFrame = false;
1823 bool IsSimple = false;
1824 unsigned RAReg = static_cast<unsigned>(UINT_MAX);
1825 bool IsBKeyFrame = false;
1826 bool IsMTETaggedFrame = false;
1827 };
1828
1829 } // end anonymous namespace
1830
Emit(MCObjectStreamer & Streamer,MCAsmBackend * MAB,bool IsEH)1831 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1832 bool IsEH) {
1833 MCContext &Context = Streamer.getContext();
1834 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1835 const MCAsmInfo *AsmInfo = Context.getAsmInfo();
1836 FrameEmitterImpl Emitter(IsEH, Streamer);
1837 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1838
1839 // Emit the compact unwind info if available.
1840 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1841 if (IsEH && MOFI->getCompactUnwindSection()) {
1842 Streamer.generateCompactUnwindEncodings(MAB);
1843 bool SectionEmitted = false;
1844 for (const MCDwarfFrameInfo &Frame : FrameArray) {
1845 if (Frame.CompactUnwindEncoding == 0) continue;
1846 if (!SectionEmitted) {
1847 Streamer.switchSection(MOFI->getCompactUnwindSection());
1848 Streamer.emitValueToAlignment(Align(AsmInfo->getCodePointerSize()));
1849 SectionEmitted = true;
1850 }
1851 NeedsEHFrameSection |=
1852 Frame.CompactUnwindEncoding ==
1853 MOFI->getCompactUnwindDwarfEHFrameOnly();
1854 Emitter.EmitCompactUnwind(Frame);
1855 }
1856 }
1857
1858 // Compact unwind information can be emitted in the eh_frame section or the
1859 // debug_frame section. Skip emitting FDEs and CIEs when the compact unwind
1860 // doesn't need an eh_frame section and the emission location is the eh_frame
1861 // section.
1862 if (!NeedsEHFrameSection && IsEH) return;
1863
1864 MCSection &Section =
1865 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1866 : *MOFI->getDwarfFrameSection();
1867
1868 Streamer.switchSection(&Section);
1869 MCSymbol *SectionStart = Context.createTempSymbol();
1870 Streamer.emitLabel(SectionStart);
1871
1872 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1873 // Sort the FDEs by their corresponding CIE before we emit them.
1874 // This isn't technically necessary according to the DWARF standard,
1875 // but the Android libunwindstack rejects eh_frame sections where
1876 // an FDE refers to a CIE other than the closest previous CIE.
1877 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
1878 llvm::stable_sort(FrameArrayX,
1879 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
1880 return CIEKey(X) < CIEKey(Y);
1881 });
1882 CIEKey LastKey;
1883 const MCSymbol *LastCIEStart = nullptr;
1884 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
1885 const MCDwarfFrameInfo &Frame = *I;
1886 ++I;
1887 if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1888 MOFI->getCompactUnwindDwarfEHFrameOnly() && IsEH)
1889 // CIEs and FDEs can be emitted in either the eh_frame section or the
1890 // debug_frame section, on some platforms (e.g. AArch64) the target object
1891 // file supports emitting a compact_unwind section without an associated
1892 // eh_frame section. If the eh_frame section is not needed, and the
1893 // location where the CIEs and FDEs are to be emitted is the eh_frame
1894 // section, do not emit anything.
1895 continue;
1896
1897 CIEKey Key(Frame);
1898 if (!LastCIEStart || (IsEH && Key != LastKey)) {
1899 LastKey = Key;
1900 LastCIEStart = &Emitter.EmitCIE(Frame);
1901 }
1902
1903 Emitter.EmitFDE(*LastCIEStart, Frame, I == E, *SectionStart);
1904 }
1905 }
1906
encodeAdvanceLoc(MCContext & Context,uint64_t AddrDelta,SmallVectorImpl<char> & Out)1907 void MCDwarfFrameEmitter::encodeAdvanceLoc(MCContext &Context,
1908 uint64_t AddrDelta,
1909 SmallVectorImpl<char> &Out) {
1910 // Scale the address delta by the minimum instruction length.
1911 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1912 if (AddrDelta == 0)
1913 return;
1914
1915 llvm::endianness E = Context.getAsmInfo()->isLittleEndian()
1916 ? llvm::endianness::little
1917 : llvm::endianness::big;
1918
1919 if (isUIntN(6, AddrDelta)) {
1920 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1921 Out.push_back(Opcode);
1922 } else if (isUInt<8>(AddrDelta)) {
1923 Out.push_back(dwarf::DW_CFA_advance_loc1);
1924 Out.push_back(AddrDelta);
1925 } else if (isUInt<16>(AddrDelta)) {
1926 Out.push_back(dwarf::DW_CFA_advance_loc2);
1927 support::endian::write<uint16_t>(Out, AddrDelta, E);
1928 } else {
1929 assert(isUInt<32>(AddrDelta));
1930 Out.push_back(dwarf::DW_CFA_advance_loc4);
1931 support::endian::write<uint32_t>(Out, AddrDelta, E);
1932 }
1933 }
1934