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