MCDwarf.cpp 69 KB

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