MCDwarf.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/MC/MCDwarf.h"
  10. #include "llvm/ADT/Hashing.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/ADT/SmallString.h"
  13. #include "llvm/ADT/Twine.h"
  14. #include "llvm/Config/config.h"
  15. #include "llvm/MC/MCAsmInfo.h"
  16. #include "llvm/MC/MCContext.h"
  17. #include "llvm/MC/MCExpr.h"
  18. #include "llvm/MC/MCObjectFileInfo.h"
  19. #include "llvm/MC/MCObjectStreamer.h"
  20. #include "llvm/MC/MCRegisterInfo.h"
  21. #include "llvm/MC/MCSection.h"
  22. #include "llvm/MC/MCSymbol.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/LEB128.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/Support/SourceMgr.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace llvm;
  30. // Given a special op, return the address skip amount (in units of
  31. // DWARF2_LINE_MIN_INSN_LENGTH.
  32. #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
  33. // The maximum address skip amount that can be encoded with a special op.
  34. #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
  35. // First special line opcode - leave room for the standard opcodes.
  36. // Note: If you want to change this, you'll have to update the
  37. // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
  38. #define DWARF2_LINE_OPCODE_BASE 13
  39. // Minimum line offset in a special line info. opcode. This value
  40. // was chosen to give a reasonable range of values.
  41. #define DWARF2_LINE_BASE -5
  42. // Range of line offsets in a special line info. opcode.
  43. #define DWARF2_LINE_RANGE 14
  44. static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
  45. unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
  46. if (MinInsnLength == 1)
  47. return AddrDelta;
  48. if (AddrDelta % MinInsnLength != 0) {
  49. // TODO: report this error, but really only once.
  50. ;
  51. }
  52. return AddrDelta / MinInsnLength;
  53. }
  54. //
  55. // This is called when an instruction is assembled into the specified section
  56. // and if there is information from the last .loc directive that has yet to have
  57. // a line entry made for it is made.
  58. //
  59. void MCLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
  60. if (!MCOS->getContext().getDwarfLocSeen())
  61. return;
  62. // Create a symbol at in the current section for use in the line entry.
  63. MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
  64. // Set the value of the symbol to use for the MCLineEntry.
  65. MCOS->EmitLabel(LineSym);
  66. // Get the current .loc info saved in the context.
  67. const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
  68. // Create a (local) line entry with the symbol and the current .loc info.
  69. MCLineEntry LineEntry(LineSym, DwarfLoc);
  70. // clear DwarfLocSeen saying the current .loc info is now used.
  71. MCOS->getContext().clearDwarfLocSeen();
  72. // Add the line entry to this section's entries.
  73. MCOS->getContext()
  74. .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
  75. .getMCLineSections()
  76. .addLineEntry(LineEntry, Section);
  77. }
  78. //
  79. // This helper routine returns an expression of End - Start + IntVal .
  80. //
  81. static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
  82. const MCSymbol &Start,
  83. const MCSymbol &End,
  84. int IntVal) {
  85. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  86. const MCExpr *Res =
  87. MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
  88. const MCExpr *RHS =
  89. MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
  90. const MCExpr *Res1 =
  91. MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
  92. const MCExpr *Res2 =
  93. MCConstantExpr::create(IntVal, MCOS.getContext());
  94. const MCExpr *Res3 =
  95. MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
  96. return Res3;
  97. }
  98. //
  99. // This emits the Dwarf line table for the specified section from the entries
  100. // in the LineSection.
  101. //
  102. static inline void
  103. EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
  104. const MCLineSection::MCLineEntryCollection &LineEntries) {
  105. unsigned FileNum = 1;
  106. unsigned LastLine = 1;
  107. unsigned Column = 0;
  108. unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
  109. unsigned Isa = 0;
  110. unsigned Discriminator = 0;
  111. MCSymbol *LastLabel = nullptr;
  112. // Loop through each MCLineEntry and encode the dwarf line number table.
  113. for (auto it = LineEntries.begin(),
  114. ie = LineEntries.end();
  115. it != ie; ++it) {
  116. if (FileNum != it->getFileNum()) {
  117. FileNum = it->getFileNum();
  118. MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
  119. MCOS->EmitULEB128IntValue(FileNum);
  120. }
  121. if (Column != it->getColumn()) {
  122. Column = it->getColumn();
  123. MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
  124. MCOS->EmitULEB128IntValue(Column);
  125. }
  126. if (Discriminator != it->getDiscriminator()) {
  127. Discriminator = it->getDiscriminator();
  128. unsigned Size = getULEB128Size(Discriminator);
  129. MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
  130. MCOS->EmitULEB128IntValue(Size + 1);
  131. MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
  132. MCOS->EmitULEB128IntValue(Discriminator);
  133. }
  134. if (Isa != it->getIsa()) {
  135. Isa = it->getIsa();
  136. MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
  137. MCOS->EmitULEB128IntValue(Isa);
  138. }
  139. if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
  140. Flags = it->getFlags();
  141. MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
  142. }
  143. if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
  144. MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
  145. if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
  146. MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
  147. if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
  148. MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
  149. int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
  150. MCSymbol *Label = it->getLabel();
  151. // At this point we want to emit/create the sequence to encode the delta in
  152. // line numbers and the increment of the address from the previous Label
  153. // and the current Label.
  154. const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
  155. MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
  156. asmInfo->getPointerSize());
  157. LastLine = it->getLine();
  158. LastLabel = Label;
  159. }
  160. // Emit a DW_LNE_end_sequence for the end of the section.
  161. // Use the section end label to compute the address delta and use INT64_MAX
  162. // as the line delta which is the signal that this is actually a
  163. // DW_LNE_end_sequence.
  164. MCSymbol *SectionEnd = MCOS->endSection(Section);
  165. // Switch back the dwarf line section, in case endSection had to switch the
  166. // section.
  167. MCContext &Ctx = MCOS->getContext();
  168. MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
  169. const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
  170. MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
  171. AsmInfo->getPointerSize());
  172. }
  173. //
  174. // This emits the Dwarf file and the line tables.
  175. //
  176. void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
  177. MCContext &context = MCOS->getContext();
  178. auto &LineTables = context.getMCDwarfLineTables();
  179. // Bail out early so we don't switch to the debug_line section needlessly and
  180. // in doing so create an unnecessary (if empty) section.
  181. if (LineTables.empty())
  182. return;
  183. // Switch to the section where the table will be emitted into.
  184. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
  185. // Handle the rest of the Compile Units.
  186. for (const auto &CUIDTablePair : LineTables)
  187. CUIDTablePair.second.EmitCU(MCOS);
  188. }
  189. void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
  190. MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
  191. }
  192. std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
  193. static const char StandardOpcodeLengths[] = {
  194. 0, // length of DW_LNS_copy
  195. 1, // length of DW_LNS_advance_pc
  196. 1, // length of DW_LNS_advance_line
  197. 1, // length of DW_LNS_set_file
  198. 1, // length of DW_LNS_set_column
  199. 0, // length of DW_LNS_negate_stmt
  200. 0, // length of DW_LNS_set_basic_block
  201. 0, // length of DW_LNS_const_add_pc
  202. 1, // length of DW_LNS_fixed_advance_pc
  203. 0, // length of DW_LNS_set_prologue_end
  204. 0, // length of DW_LNS_set_epilogue_begin
  205. 1 // DW_LNS_set_isa
  206. };
  207. assert(array_lengthof(StandardOpcodeLengths) ==
  208. (DWARF2_LINE_OPCODE_BASE - 1));
  209. return Emit(MCOS, StandardOpcodeLengths);
  210. }
  211. static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
  212. MCContext &Context = OS.getContext();
  213. assert(!isa<MCSymbolRefExpr>(Expr));
  214. if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
  215. return Expr;
  216. MCSymbol *ABS = Context.createTempSymbol();
  217. OS.EmitAssignment(ABS, Expr);
  218. return MCSymbolRefExpr::create(ABS, Context);
  219. }
  220. static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
  221. const MCExpr *ABS = forceExpAbs(OS, Value);
  222. OS.EmitValue(ABS, Size);
  223. }
  224. std::pair<MCSymbol *, MCSymbol *>
  225. MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
  226. ArrayRef<char> StandardOpcodeLengths) const {
  227. MCContext &context = MCOS->getContext();
  228. // Create a symbol at the beginning of the line table.
  229. MCSymbol *LineStartSym = Label;
  230. if (!LineStartSym)
  231. LineStartSym = context.createTempSymbol();
  232. // Set the value of the symbol, as we are at the start of the line table.
  233. MCOS->EmitLabel(LineStartSym);
  234. // Create a symbol for the end of the section (to be set when we get there).
  235. MCSymbol *LineEndSym = context.createTempSymbol();
  236. // The first 4 bytes is the total length of the information for this
  237. // compilation unit (not including these 4 bytes for the length).
  238. emitAbsValue(*MCOS,
  239. MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
  240. // Next 2 bytes is the Version, which is Dwarf 2.
  241. MCOS->EmitIntValue(2, 2);
  242. // Create a symbol for the end of the prologue (to be set when we get there).
  243. MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
  244. // Length of the prologue, is the next 4 bytes. Which is the start of the
  245. // section to the end of the prologue. Not including the 4 bytes for the
  246. // total length, the 2 bytes for the version, and these 4 bytes for the
  247. // length of the prologue.
  248. emitAbsValue(
  249. *MCOS,
  250. MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
  251. // Parameters of the state machine, are next.
  252. MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
  253. MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
  254. MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
  255. MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
  256. MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
  257. // Standard opcode lengths
  258. for (char Length : StandardOpcodeLengths)
  259. MCOS->EmitIntValue(Length, 1);
  260. // Put out the directory and file tables.
  261. // First the directory table.
  262. for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
  263. MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
  264. MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
  265. }
  266. MCOS->EmitIntValue(0, 1); // Terminate the directory list
  267. // Second the file table.
  268. for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
  269. assert(!MCDwarfFiles[i].Name.empty());
  270. MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
  271. MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
  272. // the Directory num
  273. MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
  274. MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
  275. MCOS->EmitIntValue(0, 1); // filesize (always 0)
  276. }
  277. MCOS->EmitIntValue(0, 1); // Terminate the file list
  278. // This is the end of the prologue, so set the value of the symbol at the
  279. // end of the prologue (that was used in a previous expression).
  280. MCOS->EmitLabel(ProEndSym);
  281. return std::make_pair(LineStartSym, LineEndSym);
  282. }
  283. void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
  284. MCSymbol *LineEndSym = Header.Emit(MCOS).second;
  285. // Put out the line tables.
  286. for (const auto &LineSec : MCLineSections.getMCLineEntries())
  287. EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
  288. // This is the end of the section, so set the value of the symbol at the end
  289. // of this section (that was used in a previous expression).
  290. MCOS->EmitLabel(LineEndSym);
  291. }
  292. unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
  293. unsigned FileNumber) {
  294. return Header.getFile(Directory, FileName, FileNumber);
  295. }
  296. unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
  297. StringRef &FileName,
  298. unsigned FileNumber) {
  299. if (Directory == CompilationDir)
  300. Directory = "";
  301. if (FileName.empty()) {
  302. FileName = "<stdin>";
  303. Directory = "";
  304. }
  305. assert(!FileName.empty());
  306. if (FileNumber == 0) {
  307. FileNumber = SourceIdMap.size() + 1;
  308. assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
  309. "Don't mix autonumbered and explicit numbered line table usage");
  310. SmallString<256> Buffer;
  311. auto IterBool = SourceIdMap.insert(
  312. std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
  313. FileNumber));
  314. if (!IterBool.second)
  315. return IterBool.first->second;
  316. }
  317. // Make space for this FileNumber in the MCDwarfFiles vector if needed.
  318. MCDwarfFiles.resize(FileNumber + 1);
  319. // Get the new MCDwarfFile slot for this FileNumber.
  320. MCDwarfFile &File = MCDwarfFiles[FileNumber];
  321. // It is an error to use see the same number more than once.
  322. if (!File.Name.empty())
  323. return 0;
  324. if (Directory.empty()) {
  325. // Separate the directory part from the basename of the FileName.
  326. StringRef tFileName = sys::path::filename(FileName);
  327. if (!tFileName.empty()) {
  328. Directory = sys::path::parent_path(FileName);
  329. if (!Directory.empty())
  330. FileName = tFileName;
  331. }
  332. }
  333. // Find or make an entry in the MCDwarfDirs vector for this Directory.
  334. // Capture directory name.
  335. unsigned DirIndex;
  336. if (Directory.empty()) {
  337. // For FileNames with no directories a DirIndex of 0 is used.
  338. DirIndex = 0;
  339. } else {
  340. DirIndex = 0;
  341. for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
  342. if (Directory == MCDwarfDirs[DirIndex])
  343. break;
  344. }
  345. if (DirIndex >= MCDwarfDirs.size())
  346. MCDwarfDirs.push_back(Directory);
  347. // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
  348. // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
  349. // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
  350. // are stored at MCDwarfFiles[FileNumber].Name .
  351. DirIndex++;
  352. }
  353. File.Name = FileName;
  354. File.DirIndex = DirIndex;
  355. // return the allocated FileNumber.
  356. return FileNumber;
  357. }
  358. /// Utility function to emit the encoding to a streamer.
  359. void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
  360. uint64_t AddrDelta) {
  361. MCContext &Context = MCOS->getContext();
  362. SmallString<256> Tmp;
  363. raw_svector_ostream OS(Tmp);
  364. MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
  365. MCOS->EmitBytes(OS.str());
  366. }
  367. /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
  368. void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
  369. uint64_t AddrDelta, raw_ostream &OS) {
  370. uint64_t Temp, Opcode;
  371. bool NeedCopy = false;
  372. // Scale the address delta by the minimum instruction length.
  373. AddrDelta = ScaleAddrDelta(Context, AddrDelta);
  374. // A LineDelta of INT64_MAX is a signal that this is actually a
  375. // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
  376. // end_sequence to emit the matrix entry.
  377. if (LineDelta == INT64_MAX) {
  378. if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
  379. OS << char(dwarf::DW_LNS_const_add_pc);
  380. else if (AddrDelta) {
  381. OS << char(dwarf::DW_LNS_advance_pc);
  382. encodeULEB128(AddrDelta, OS);
  383. }
  384. OS << char(dwarf::DW_LNS_extended_op);
  385. OS << char(1);
  386. OS << char(dwarf::DW_LNE_end_sequence);
  387. return;
  388. }
  389. // Bias the line delta by the base.
  390. Temp = LineDelta - DWARF2_LINE_BASE;
  391. // If the line increment is out of range of a special opcode, we must encode
  392. // it with DW_LNS_advance_line.
  393. if (Temp >= DWARF2_LINE_RANGE) {
  394. OS << char(dwarf::DW_LNS_advance_line);
  395. encodeSLEB128(LineDelta, OS);
  396. LineDelta = 0;
  397. Temp = 0 - DWARF2_LINE_BASE;
  398. NeedCopy = true;
  399. }
  400. // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
  401. if (LineDelta == 0 && AddrDelta == 0) {
  402. OS << char(dwarf::DW_LNS_copy);
  403. return;
  404. }
  405. // Bias the opcode by the special opcode base.
  406. Temp += DWARF2_LINE_OPCODE_BASE;
  407. // Avoid overflow when addr_delta is large.
  408. if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
  409. // Try using a special opcode.
  410. Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
  411. if (Opcode <= 255) {
  412. OS << char(Opcode);
  413. return;
  414. }
  415. // Try using DW_LNS_const_add_pc followed by special op.
  416. Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
  417. if (Opcode <= 255) {
  418. OS << char(dwarf::DW_LNS_const_add_pc);
  419. OS << char(Opcode);
  420. return;
  421. }
  422. }
  423. // Otherwise use DW_LNS_advance_pc.
  424. OS << char(dwarf::DW_LNS_advance_pc);
  425. encodeULEB128(AddrDelta, OS);
  426. if (NeedCopy)
  427. OS << char(dwarf::DW_LNS_copy);
  428. else
  429. OS << char(Temp);
  430. }
  431. // Utility function to write a tuple for .debug_abbrev.
  432. static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
  433. MCOS->EmitULEB128IntValue(Name);
  434. MCOS->EmitULEB128IntValue(Form);
  435. }
  436. // When generating dwarf for assembly source files this emits
  437. // the data for .debug_abbrev section which contains three DIEs.
  438. static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
  439. MCContext &context = MCOS->getContext();
  440. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
  441. // DW_TAG_compile_unit DIE abbrev (1).
  442. MCOS->EmitULEB128IntValue(1);
  443. MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
  444. MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
  445. EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
  446. if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
  447. MCOS->getContext().getDwarfVersion() >= 3) {
  448. EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
  449. } else {
  450. EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
  451. EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
  452. }
  453. EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
  454. if (!context.getCompilationDir().empty())
  455. EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
  456. StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
  457. if (!DwarfDebugFlags.empty())
  458. EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
  459. EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
  460. EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
  461. EmitAbbrev(MCOS, 0, 0);
  462. // DW_TAG_label DIE abbrev (2).
  463. MCOS->EmitULEB128IntValue(2);
  464. MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
  465. MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
  466. EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
  467. EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
  468. EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
  469. EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
  470. EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
  471. EmitAbbrev(MCOS, 0, 0);
  472. // DW_TAG_unspecified_parameters DIE abbrev (3).
  473. MCOS->EmitULEB128IntValue(3);
  474. MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
  475. MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
  476. EmitAbbrev(MCOS, 0, 0);
  477. // Terminate the abbreviations for this compilation unit.
  478. MCOS->EmitIntValue(0, 1);
  479. }
  480. // When generating dwarf for assembly source files this emits the data for
  481. // .debug_aranges section. This section contains a header and a table of pairs
  482. // of PointerSize'ed values for the address and size of section(s) with line
  483. // table entries.
  484. static void EmitGenDwarfAranges(MCStreamer *MCOS,
  485. const MCSymbol *InfoSectionSymbol) {
  486. MCContext &context = MCOS->getContext();
  487. auto &Sections = context.getGenDwarfSectionSyms();
  488. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
  489. // This will be the length of the .debug_aranges section, first account for
  490. // the size of each item in the header (see below where we emit these items).
  491. int Length = 4 + 2 + 4 + 1 + 1;
  492. // Figure the padding after the header before the table of address and size
  493. // pairs who's values are PointerSize'ed.
  494. const MCAsmInfo *asmInfo = context.getAsmInfo();
  495. int AddrSize = asmInfo->getPointerSize();
  496. int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
  497. if (Pad == 2 * AddrSize)
  498. Pad = 0;
  499. Length += Pad;
  500. // Add the size of the pair of PointerSize'ed values for the address and size
  501. // of each section we have in the table.
  502. Length += 2 * AddrSize * Sections.size();
  503. // And the pair of terminating zeros.
  504. Length += 2 * AddrSize;
  505. // Emit the header for this section.
  506. // The 4 byte length not including the 4 byte value for the length.
  507. MCOS->EmitIntValue(Length - 4, 4);
  508. // The 2 byte version, which is 2.
  509. MCOS->EmitIntValue(2, 2);
  510. // The 4 byte offset to the compile unit in the .debug_info from the start
  511. // of the .debug_info.
  512. if (InfoSectionSymbol)
  513. MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
  514. asmInfo->needsDwarfSectionOffsetDirective());
  515. else
  516. MCOS->EmitIntValue(0, 4);
  517. // The 1 byte size of an address.
  518. MCOS->EmitIntValue(AddrSize, 1);
  519. // The 1 byte size of a segment descriptor, we use a value of zero.
  520. MCOS->EmitIntValue(0, 1);
  521. // Align the header with the padding if needed, before we put out the table.
  522. for(int i = 0; i < Pad; i++)
  523. MCOS->EmitIntValue(0, 1);
  524. // Now emit the table of pairs of PointerSize'ed values for the section
  525. // addresses and sizes.
  526. for (MCSection *Sec : Sections) {
  527. const MCSymbol *StartSymbol = Sec->getBeginSymbol();
  528. MCSymbol *EndSymbol = Sec->getEndSymbol(context);
  529. assert(StartSymbol && "StartSymbol must not be NULL");
  530. assert(EndSymbol && "EndSymbol must not be NULL");
  531. const MCExpr *Addr = MCSymbolRefExpr::create(
  532. StartSymbol, MCSymbolRefExpr::VK_None, context);
  533. const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
  534. *StartSymbol, *EndSymbol, 0);
  535. MCOS->EmitValue(Addr, AddrSize);
  536. emitAbsValue(*MCOS, Size, AddrSize);
  537. }
  538. // And finally the pair of terminating zeros.
  539. MCOS->EmitIntValue(0, AddrSize);
  540. MCOS->EmitIntValue(0, AddrSize);
  541. }
  542. // When generating dwarf for assembly source files this emits the data for
  543. // .debug_info section which contains three parts. The header, the compile_unit
  544. // DIE and a list of label DIEs.
  545. static void EmitGenDwarfInfo(MCStreamer *MCOS,
  546. const MCSymbol *AbbrevSectionSymbol,
  547. const MCSymbol *LineSectionSymbol,
  548. const MCSymbol *RangesSectionSymbol) {
  549. MCContext &context = MCOS->getContext();
  550. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
  551. // Create a symbol at the start and end of this section used in here for the
  552. // expression to calculate the length in the header.
  553. MCSymbol *InfoStart = context.createTempSymbol();
  554. MCOS->EmitLabel(InfoStart);
  555. MCSymbol *InfoEnd = context.createTempSymbol();
  556. // First part: the header.
  557. // The 4 byte total length of the information for this compilation unit, not
  558. // including these 4 bytes.
  559. const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
  560. emitAbsValue(*MCOS, Length, 4);
  561. // The 2 byte DWARF version.
  562. MCOS->EmitIntValue(context.getDwarfVersion(), 2);
  563. const MCAsmInfo &AsmInfo = *context.getAsmInfo();
  564. // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
  565. // it is at the start of that section so this is zero.
  566. if (AbbrevSectionSymbol == nullptr)
  567. MCOS->EmitIntValue(0, 4);
  568. else
  569. MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
  570. AsmInfo.needsDwarfSectionOffsetDirective());
  571. const MCAsmInfo *asmInfo = context.getAsmInfo();
  572. int AddrSize = asmInfo->getPointerSize();
  573. // The 1 byte size of an address.
  574. MCOS->EmitIntValue(AddrSize, 1);
  575. // Second part: the compile_unit DIE.
  576. // The DW_TAG_compile_unit DIE abbrev (1).
  577. MCOS->EmitULEB128IntValue(1);
  578. // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
  579. // which is at the start of that section so this is zero.
  580. if (LineSectionSymbol)
  581. MCOS->EmitSymbolValue(LineSectionSymbol, 4,
  582. AsmInfo.needsDwarfSectionOffsetDirective());
  583. else
  584. MCOS->EmitIntValue(0, 4);
  585. if (RangesSectionSymbol) {
  586. // There are multiple sections containing code, so we must use the
  587. // .debug_ranges sections.
  588. // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
  589. // to the address range list for this compilation unit.
  590. MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
  591. } else {
  592. // If we only have one non-empty code section, we can use the simpler
  593. // AT_low_pc and AT_high_pc attributes.
  594. // Find the first (and only) non-empty text section
  595. auto &Sections = context.getGenDwarfSectionSyms();
  596. const auto TextSection = Sections.begin();
  597. assert(TextSection != Sections.end() && "No text section found");
  598. MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
  599. MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
  600. assert(StartSymbol && "StartSymbol must not be NULL");
  601. assert(EndSymbol && "EndSymbol must not be NULL");
  602. // AT_low_pc, the first address of the default .text section.
  603. const MCExpr *Start = MCSymbolRefExpr::create(
  604. StartSymbol, MCSymbolRefExpr::VK_None, context);
  605. MCOS->EmitValue(Start, AddrSize);
  606. // AT_high_pc, the last address of the default .text section.
  607. const MCExpr *End = MCSymbolRefExpr::create(
  608. EndSymbol, MCSymbolRefExpr::VK_None, context);
  609. MCOS->EmitValue(End, AddrSize);
  610. }
  611. // AT_name, the name of the source file. Reconstruct from the first directory
  612. // and file table entries.
  613. const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
  614. if (MCDwarfDirs.size() > 0) {
  615. MCOS->EmitBytes(MCDwarfDirs[0]);
  616. MCOS->EmitBytes(sys::path::get_separator());
  617. }
  618. const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
  619. MCOS->getContext().getMCDwarfFiles();
  620. MCOS->EmitBytes(MCDwarfFiles[1].Name);
  621. MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
  622. // AT_comp_dir, the working directory the assembly was done in.
  623. if (!context.getCompilationDir().empty()) {
  624. MCOS->EmitBytes(context.getCompilationDir());
  625. MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
  626. }
  627. // AT_APPLE_flags, the command line arguments of the assembler tool.
  628. StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
  629. if (!DwarfDebugFlags.empty()){
  630. MCOS->EmitBytes(DwarfDebugFlags);
  631. MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
  632. }
  633. // AT_producer, the version of the assembler tool.
  634. StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
  635. if (!DwarfDebugProducer.empty())
  636. MCOS->EmitBytes(DwarfDebugProducer);
  637. else
  638. MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
  639. MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
  640. // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
  641. // draft has no standard code for assembler.
  642. MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
  643. // Third part: the list of label DIEs.
  644. // Loop on saved info for dwarf labels and create the DIEs for them.
  645. const std::vector<MCGenDwarfLabelEntry> &Entries =
  646. MCOS->getContext().getMCGenDwarfLabelEntries();
  647. for (const auto &Entry : Entries) {
  648. // The DW_TAG_label DIE abbrev (2).
  649. MCOS->EmitULEB128IntValue(2);
  650. // AT_name, of the label without any leading underbar.
  651. MCOS->EmitBytes(Entry.getName());
  652. MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
  653. // AT_decl_file, index into the file table.
  654. MCOS->EmitIntValue(Entry.getFileNumber(), 4);
  655. // AT_decl_line, source line number.
  656. MCOS->EmitIntValue(Entry.getLineNumber(), 4);
  657. // AT_low_pc, start address of the label.
  658. const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
  659. MCSymbolRefExpr::VK_None, context);
  660. MCOS->EmitValue(AT_low_pc, AddrSize);
  661. // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
  662. MCOS->EmitIntValue(0, 1);
  663. // The DW_TAG_unspecified_parameters DIE abbrev (3).
  664. MCOS->EmitULEB128IntValue(3);
  665. // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
  666. MCOS->EmitIntValue(0, 1);
  667. }
  668. // Add the NULL DIE terminating the Compile Unit DIE's.
  669. MCOS->EmitIntValue(0, 1);
  670. // Now set the value of the symbol at the end of the info section.
  671. MCOS->EmitLabel(InfoEnd);
  672. }
  673. // When generating dwarf for assembly source files this emits the data for
  674. // .debug_ranges section. We only emit one range list, which spans all of the
  675. // executable sections of this file.
  676. static void EmitGenDwarfRanges(MCStreamer *MCOS) {
  677. MCContext &context = MCOS->getContext();
  678. auto &Sections = context.getGenDwarfSectionSyms();
  679. const MCAsmInfo *AsmInfo = context.getAsmInfo();
  680. int AddrSize = AsmInfo->getPointerSize();
  681. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
  682. for (MCSection *Sec : Sections) {
  683. const MCSymbol *StartSymbol = Sec->getBeginSymbol();
  684. MCSymbol *EndSymbol = Sec->getEndSymbol(context);
  685. assert(StartSymbol && "StartSymbol must not be NULL");
  686. assert(EndSymbol && "EndSymbol must not be NULL");
  687. // Emit a base address selection entry for the start of this section
  688. const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
  689. StartSymbol, MCSymbolRefExpr::VK_None, context);
  690. MCOS->EmitFill(AddrSize, 0xFF);
  691. MCOS->EmitValue(SectionStartAddr, AddrSize);
  692. // Emit a range list entry spanning this section
  693. const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
  694. *StartSymbol, *EndSymbol, 0);
  695. MCOS->EmitIntValue(0, AddrSize);
  696. emitAbsValue(*MCOS, SectionSize, AddrSize);
  697. }
  698. // Emit end of list entry
  699. MCOS->EmitIntValue(0, AddrSize);
  700. MCOS->EmitIntValue(0, AddrSize);
  701. }
  702. //
  703. // When generating dwarf for assembly source files this emits the Dwarf
  704. // sections.
  705. //
  706. void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
  707. MCContext &context = MCOS->getContext();
  708. // Create the dwarf sections in this order (.debug_line already created).
  709. const MCAsmInfo *AsmInfo = context.getAsmInfo();
  710. bool CreateDwarfSectionSymbols =
  711. AsmInfo->doesDwarfUseRelocationsAcrossSections();
  712. MCSymbol *LineSectionSymbol = nullptr;
  713. if (CreateDwarfSectionSymbols)
  714. LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
  715. MCSymbol *AbbrevSectionSymbol = nullptr;
  716. MCSymbol *InfoSectionSymbol = nullptr;
  717. MCSymbol *RangesSectionSymbol = NULL;
  718. // Create end symbols for each section, and remove empty sections
  719. MCOS->getContext().finalizeDwarfSections(*MCOS);
  720. // If there are no sections to generate debug info for, we don't need
  721. // to do anything
  722. if (MCOS->getContext().getGenDwarfSectionSyms().empty())
  723. return;
  724. // We only use the .debug_ranges section if we have multiple code sections,
  725. // and we are emitting a DWARF version which supports it.
  726. const bool UseRangesSection =
  727. MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
  728. MCOS->getContext().getDwarfVersion() >= 3;
  729. CreateDwarfSectionSymbols |= UseRangesSection;
  730. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
  731. if (CreateDwarfSectionSymbols) {
  732. InfoSectionSymbol = context.createTempSymbol();
  733. MCOS->EmitLabel(InfoSectionSymbol);
  734. }
  735. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
  736. if (CreateDwarfSectionSymbols) {
  737. AbbrevSectionSymbol = context.createTempSymbol();
  738. MCOS->EmitLabel(AbbrevSectionSymbol);
  739. }
  740. if (UseRangesSection) {
  741. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
  742. if (CreateDwarfSectionSymbols) {
  743. RangesSectionSymbol = context.createTempSymbol();
  744. MCOS->EmitLabel(RangesSectionSymbol);
  745. }
  746. }
  747. assert((RangesSectionSymbol != NULL) || !UseRangesSection);
  748. MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
  749. // Output the data for .debug_aranges section.
  750. EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
  751. if (UseRangesSection)
  752. EmitGenDwarfRanges(MCOS);
  753. // Output the data for .debug_abbrev section.
  754. EmitGenDwarfAbbrev(MCOS);
  755. // Output the data for .debug_info section.
  756. EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
  757. RangesSectionSymbol);
  758. }
  759. //
  760. // When generating dwarf for assembly source files this is called when symbol
  761. // for a label is created. If this symbol is not a temporary and is in the
  762. // section that dwarf is being generated for, save the needed info to create
  763. // a dwarf label.
  764. //
  765. void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
  766. SourceMgr &SrcMgr, SMLoc &Loc) {
  767. // We won't create dwarf labels for temporary symbols.
  768. if (Symbol->isTemporary())
  769. return;
  770. MCContext &context = MCOS->getContext();
  771. // We won't create dwarf labels for symbols in sections that we are not
  772. // generating debug info for.
  773. if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
  774. return;
  775. // The dwarf label's name does not have the symbol name's leading
  776. // underbar if any.
  777. StringRef Name = Symbol->getName();
  778. if (Name.startswith("_"))
  779. Name = Name.substr(1, Name.size()-1);
  780. // Get the dwarf file number to be used for the dwarf label.
  781. unsigned FileNumber = context.getGenDwarfFileNumber();
  782. // Finding the line number is the expensive part which is why we just don't
  783. // pass it in as for some symbols we won't create a dwarf label.
  784. unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
  785. unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
  786. // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
  787. // values so that they don't have things like an ARM thumb bit from the
  788. // original symbol. So when used they won't get a low bit set after
  789. // relocation.
  790. MCSymbol *Label = context.createTempSymbol();
  791. MCOS->EmitLabel(Label);
  792. // Create and entry for the info and add it to the other entries.
  793. MCOS->getContext().addMCGenDwarfLabelEntry(
  794. MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
  795. }
  796. static int getDataAlignmentFactor(MCStreamer &streamer) {
  797. MCContext &context = streamer.getContext();
  798. const MCAsmInfo *asmInfo = context.getAsmInfo();
  799. int size = asmInfo->getCalleeSaveStackSlotSize();
  800. if (asmInfo->isStackGrowthDirectionUp())
  801. return size;
  802. else
  803. return -size;
  804. }
  805. static unsigned getSizeForEncoding(MCStreamer &streamer,
  806. unsigned symbolEncoding) {
  807. MCContext &context = streamer.getContext();
  808. unsigned format = symbolEncoding & 0x0f;
  809. switch (format) {
  810. default: llvm_unreachable("Unknown Encoding");
  811. case dwarf::DW_EH_PE_absptr:
  812. case dwarf::DW_EH_PE_signed:
  813. return context.getAsmInfo()->getPointerSize();
  814. case dwarf::DW_EH_PE_udata2:
  815. case dwarf::DW_EH_PE_sdata2:
  816. return 2;
  817. case dwarf::DW_EH_PE_udata4:
  818. case dwarf::DW_EH_PE_sdata4:
  819. return 4;
  820. case dwarf::DW_EH_PE_udata8:
  821. case dwarf::DW_EH_PE_sdata8:
  822. return 8;
  823. }
  824. }
  825. static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
  826. unsigned symbolEncoding, bool isEH) {
  827. MCContext &context = streamer.getContext();
  828. const MCAsmInfo *asmInfo = context.getAsmInfo();
  829. const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
  830. symbolEncoding,
  831. streamer);
  832. unsigned size = getSizeForEncoding(streamer, symbolEncoding);
  833. if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
  834. emitAbsValue(streamer, v, size);
  835. else
  836. streamer.EmitValue(v, size);
  837. }
  838. static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
  839. unsigned symbolEncoding) {
  840. MCContext &context = streamer.getContext();
  841. const MCAsmInfo *asmInfo = context.getAsmInfo();
  842. const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
  843. symbolEncoding,
  844. streamer);
  845. unsigned size = getSizeForEncoding(streamer, symbolEncoding);
  846. streamer.EmitValue(v, size);
  847. }
  848. namespace {
  849. class FrameEmitterImpl {
  850. int CFAOffset;
  851. int InitialCFAOffset;
  852. bool IsEH;
  853. const MCSymbol *SectionStart;
  854. public:
  855. FrameEmitterImpl(bool isEH)
  856. : CFAOffset(0), InitialCFAOffset(0), IsEH(isEH), SectionStart(nullptr) {
  857. }
  858. void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
  859. /// Emit the unwind information in a compact way.
  860. void EmitCompactUnwind(MCObjectStreamer &streamer,
  861. const MCDwarfFrameInfo &frame);
  862. const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
  863. const MCSymbol *personality,
  864. unsigned personalityEncoding,
  865. const MCSymbol *lsda,
  866. bool IsSignalFrame,
  867. unsigned lsdaEncoding,
  868. bool IsSimple);
  869. MCSymbol *EmitFDE(MCObjectStreamer &streamer,
  870. const MCSymbol &cieStart,
  871. const MCDwarfFrameInfo &frame);
  872. void EmitCFIInstructions(MCObjectStreamer &streamer,
  873. ArrayRef<MCCFIInstruction> Instrs,
  874. MCSymbol *BaseLabel);
  875. void EmitCFIInstruction(MCObjectStreamer &Streamer,
  876. const MCCFIInstruction &Instr);
  877. };
  878. } // end anonymous namespace
  879. static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
  880. Streamer.EmitIntValue(Encoding, 1);
  881. }
  882. void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
  883. const MCCFIInstruction &Instr) {
  884. int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
  885. auto *MRI = Streamer.getContext().getRegisterInfo();
  886. switch (Instr.getOperation()) {
  887. case MCCFIInstruction::OpRegister: {
  888. unsigned Reg1 = Instr.getRegister();
  889. unsigned Reg2 = Instr.getRegister2();
  890. if (!IsEH) {
  891. Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
  892. Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
  893. }
  894. Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
  895. Streamer.EmitULEB128IntValue(Reg1);
  896. Streamer.EmitULEB128IntValue(Reg2);
  897. return;
  898. }
  899. case MCCFIInstruction::OpWindowSave: {
  900. Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
  901. return;
  902. }
  903. case MCCFIInstruction::OpUndefined: {
  904. unsigned Reg = Instr.getRegister();
  905. Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
  906. Streamer.EmitULEB128IntValue(Reg);
  907. return;
  908. }
  909. case MCCFIInstruction::OpAdjustCfaOffset:
  910. case MCCFIInstruction::OpDefCfaOffset: {
  911. const bool IsRelative =
  912. Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
  913. Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
  914. if (IsRelative)
  915. CFAOffset += Instr.getOffset();
  916. else
  917. CFAOffset = -Instr.getOffset();
  918. Streamer.EmitULEB128IntValue(CFAOffset);
  919. return;
  920. }
  921. case MCCFIInstruction::OpDefCfa: {
  922. unsigned Reg = Instr.getRegister();
  923. if (!IsEH)
  924. Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
  925. Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
  926. Streamer.EmitULEB128IntValue(Reg);
  927. CFAOffset = -Instr.getOffset();
  928. Streamer.EmitULEB128IntValue(CFAOffset);
  929. return;
  930. }
  931. case MCCFIInstruction::OpDefCfaRegister: {
  932. unsigned Reg = Instr.getRegister();
  933. if (!IsEH)
  934. Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
  935. Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
  936. Streamer.EmitULEB128IntValue(Reg);
  937. return;
  938. }
  939. case MCCFIInstruction::OpOffset:
  940. case MCCFIInstruction::OpRelOffset: {
  941. const bool IsRelative =
  942. Instr.getOperation() == MCCFIInstruction::OpRelOffset;
  943. unsigned Reg = Instr.getRegister();
  944. if (!IsEH)
  945. Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
  946. int Offset = Instr.getOffset();
  947. if (IsRelative)
  948. Offset -= CFAOffset;
  949. Offset = Offset / dataAlignmentFactor;
  950. if (Offset < 0) {
  951. Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
  952. Streamer.EmitULEB128IntValue(Reg);
  953. Streamer.EmitSLEB128IntValue(Offset);
  954. } else if (Reg < 64) {
  955. Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
  956. Streamer.EmitULEB128IntValue(Offset);
  957. } else {
  958. Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
  959. Streamer.EmitULEB128IntValue(Reg);
  960. Streamer.EmitULEB128IntValue(Offset);
  961. }
  962. return;
  963. }
  964. case MCCFIInstruction::OpRememberState:
  965. Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
  966. return;
  967. case MCCFIInstruction::OpRestoreState:
  968. Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
  969. return;
  970. case MCCFIInstruction::OpSameValue: {
  971. unsigned Reg = Instr.getRegister();
  972. Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
  973. Streamer.EmitULEB128IntValue(Reg);
  974. return;
  975. }
  976. case MCCFIInstruction::OpRestore: {
  977. unsigned Reg = Instr.getRegister();
  978. if (!IsEH)
  979. Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
  980. Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
  981. return;
  982. }
  983. case MCCFIInstruction::OpEscape:
  984. Streamer.EmitBytes(Instr.getValues());
  985. return;
  986. }
  987. llvm_unreachable("Unhandled case in switch");
  988. }
  989. /// Emit frame instructions to describe the layout of the frame.
  990. void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
  991. ArrayRef<MCCFIInstruction> Instrs,
  992. MCSymbol *BaseLabel) {
  993. for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
  994. const MCCFIInstruction &Instr = Instrs[i];
  995. MCSymbol *Label = Instr.getLabel();
  996. // Throw out move if the label is invalid.
  997. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
  998. // Advance row if new location.
  999. if (BaseLabel && Label) {
  1000. MCSymbol *ThisSym = Label;
  1001. if (ThisSym != BaseLabel) {
  1002. streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
  1003. BaseLabel = ThisSym;
  1004. }
  1005. }
  1006. EmitCFIInstruction(streamer, Instr);
  1007. }
  1008. }
  1009. /// Emit the unwind information in a compact way.
  1010. void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
  1011. const MCDwarfFrameInfo &Frame) {
  1012. MCContext &Context = Streamer.getContext();
  1013. const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
  1014. // range-start range-length compact-unwind-enc personality-func lsda
  1015. // _foo LfooEnd-_foo 0x00000023 0 0
  1016. // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
  1017. //
  1018. // .section __LD,__compact_unwind,regular,debug
  1019. //
  1020. // # compact unwind for _foo
  1021. // .quad _foo
  1022. // .set L1,LfooEnd-_foo
  1023. // .long L1
  1024. // .long 0x01010001
  1025. // .quad 0
  1026. // .quad 0
  1027. //
  1028. // # compact unwind for _bar
  1029. // .quad _bar
  1030. // .set L2,LbarEnd-_bar
  1031. // .long L2
  1032. // .long 0x01020011
  1033. // .quad __gxx_personality
  1034. // .quad except_tab1
  1035. uint32_t Encoding = Frame.CompactUnwindEncoding;
  1036. if (!Encoding) return;
  1037. bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
  1038. // The encoding needs to know we have an LSDA.
  1039. if (!DwarfEHFrameOnly && Frame.Lsda)
  1040. Encoding |= 0x40000000;
  1041. // Range Start
  1042. unsigned FDEEncoding = MOFI->getFDEEncoding();
  1043. unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
  1044. Streamer.EmitSymbolValue(Frame.Begin, Size);
  1045. // Range Length
  1046. const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
  1047. *Frame.End, 0);
  1048. emitAbsValue(Streamer, Range, 4);
  1049. // Compact Encoding
  1050. Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
  1051. Streamer.EmitIntValue(Encoding, Size);
  1052. // Personality Function
  1053. Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
  1054. if (!DwarfEHFrameOnly && Frame.Personality)
  1055. Streamer.EmitSymbolValue(Frame.Personality, Size);
  1056. else
  1057. Streamer.EmitIntValue(0, Size); // No personality fn
  1058. // LSDA
  1059. Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
  1060. if (!DwarfEHFrameOnly && Frame.Lsda)
  1061. Streamer.EmitSymbolValue(Frame.Lsda, Size);
  1062. else
  1063. Streamer.EmitIntValue(0, Size); // No LSDA
  1064. }
  1065. static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
  1066. if (IsEH)
  1067. return 1;
  1068. switch (DwarfVersion) {
  1069. case 2:
  1070. return 1;
  1071. case 3:
  1072. return 3;
  1073. case 4:
  1074. return 4;
  1075. }
  1076. llvm_unreachable("Unknown version");
  1077. }
  1078. const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
  1079. const MCSymbol *personality,
  1080. unsigned personalityEncoding,
  1081. const MCSymbol *lsda,
  1082. bool IsSignalFrame,
  1083. unsigned lsdaEncoding,
  1084. bool IsSimple) {
  1085. MCContext &context = streamer.getContext();
  1086. const MCRegisterInfo *MRI = context.getRegisterInfo();
  1087. const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
  1088. MCSymbol *sectionStart = context.createTempSymbol();
  1089. streamer.EmitLabel(sectionStart);
  1090. MCSymbol *sectionEnd = context.createTempSymbol();
  1091. // Length
  1092. const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
  1093. *sectionEnd, 4);
  1094. emitAbsValue(streamer, Length, 4);
  1095. // CIE ID
  1096. unsigned CIE_ID = IsEH ? 0 : -1;
  1097. streamer.EmitIntValue(CIE_ID, 4);
  1098. // Version
  1099. uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
  1100. streamer.EmitIntValue(CIEVersion, 1);
  1101. // Augmentation String
  1102. SmallString<8> Augmentation;
  1103. if (IsEH) {
  1104. Augmentation += "z";
  1105. if (personality)
  1106. Augmentation += "P";
  1107. if (lsda)
  1108. Augmentation += "L";
  1109. Augmentation += "R";
  1110. if (IsSignalFrame)
  1111. Augmentation += "S";
  1112. streamer.EmitBytes(Augmentation);
  1113. }
  1114. streamer.EmitIntValue(0, 1);
  1115. if (CIEVersion >= 4) {
  1116. // Address Size
  1117. streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1);
  1118. // Segment Descriptor Size
  1119. streamer.EmitIntValue(0, 1);
  1120. }
  1121. // Code Alignment Factor
  1122. streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
  1123. // Data Alignment Factor
  1124. streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
  1125. // Return Address Register
  1126. if (CIEVersion == 1) {
  1127. assert(MRI->getRARegister() <= 255 &&
  1128. "DWARF 2 encodes return_address_register in one byte");
  1129. streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
  1130. } else {
  1131. streamer.EmitULEB128IntValue(
  1132. MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
  1133. }
  1134. // Augmentation Data Length (optional)
  1135. unsigned augmentationLength = 0;
  1136. if (IsEH) {
  1137. if (personality) {
  1138. // Personality Encoding
  1139. augmentationLength += 1;
  1140. // Personality
  1141. augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
  1142. }
  1143. if (lsda)
  1144. augmentationLength += 1;
  1145. // Encoding of the FDE pointers
  1146. augmentationLength += 1;
  1147. streamer.EmitULEB128IntValue(augmentationLength);
  1148. // Augmentation Data (optional)
  1149. if (personality) {
  1150. // Personality Encoding
  1151. emitEncodingByte(streamer, personalityEncoding);
  1152. // Personality
  1153. EmitPersonality(streamer, *personality, personalityEncoding);
  1154. }
  1155. if (lsda)
  1156. emitEncodingByte(streamer, lsdaEncoding);
  1157. // Encoding of the FDE pointers
  1158. emitEncodingByte(streamer, MOFI->getFDEEncoding());
  1159. }
  1160. // Initial Instructions
  1161. const MCAsmInfo *MAI = context.getAsmInfo();
  1162. if (!IsSimple) {
  1163. const std::vector<MCCFIInstruction> &Instructions =
  1164. MAI->getInitialFrameState();
  1165. EmitCFIInstructions(streamer, Instructions, nullptr);
  1166. }
  1167. InitialCFAOffset = CFAOffset;
  1168. // Padding
  1169. streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
  1170. streamer.EmitLabel(sectionEnd);
  1171. return *sectionStart;
  1172. }
  1173. MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
  1174. const MCSymbol &cieStart,
  1175. const MCDwarfFrameInfo &frame) {
  1176. MCContext &context = streamer.getContext();
  1177. MCSymbol *fdeStart = context.createTempSymbol();
  1178. MCSymbol *fdeEnd = context.createTempSymbol();
  1179. const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
  1180. CFAOffset = InitialCFAOffset;
  1181. // Length
  1182. const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
  1183. emitAbsValue(streamer, Length, 4);
  1184. streamer.EmitLabel(fdeStart);
  1185. // CIE Pointer
  1186. const MCAsmInfo *asmInfo = context.getAsmInfo();
  1187. if (IsEH) {
  1188. const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
  1189. 0);
  1190. emitAbsValue(streamer, offset, 4);
  1191. } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
  1192. const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
  1193. cieStart, 0);
  1194. emitAbsValue(streamer, offset, 4);
  1195. } else {
  1196. streamer.EmitSymbolValue(&cieStart, 4);
  1197. }
  1198. // PC Begin
  1199. unsigned PCEncoding =
  1200. IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
  1201. unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
  1202. emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
  1203. // PC Range
  1204. const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
  1205. *frame.End, 0);
  1206. emitAbsValue(streamer, Range, PCSize);
  1207. if (IsEH) {
  1208. // Augmentation Data Length
  1209. unsigned augmentationLength = 0;
  1210. if (frame.Lsda)
  1211. augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
  1212. streamer.EmitULEB128IntValue(augmentationLength);
  1213. // Augmentation Data
  1214. if (frame.Lsda)
  1215. emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
  1216. }
  1217. // Call Frame Instructions
  1218. EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
  1219. // Padding
  1220. streamer.EmitValueToAlignment(PCSize);
  1221. return fdeEnd;
  1222. }
  1223. namespace {
  1224. struct CIEKey {
  1225. static const CIEKey getEmptyKey() {
  1226. return CIEKey(nullptr, 0, -1, false, false);
  1227. }
  1228. static const CIEKey getTombstoneKey() {
  1229. return CIEKey(nullptr, -1, 0, false, false);
  1230. }
  1231. CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
  1232. unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
  1233. : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
  1234. LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
  1235. IsSimple(IsSimple_) {}
  1236. const MCSymbol *Personality;
  1237. unsigned PersonalityEncoding;
  1238. unsigned LsdaEncoding;
  1239. bool IsSignalFrame;
  1240. bool IsSimple;
  1241. };
  1242. }
  1243. namespace llvm {
  1244. template <>
  1245. struct DenseMapInfo<CIEKey> {
  1246. static CIEKey getEmptyKey() {
  1247. return CIEKey::getEmptyKey();
  1248. }
  1249. static CIEKey getTombstoneKey() {
  1250. return CIEKey::getTombstoneKey();
  1251. }
  1252. static unsigned getHashValue(const CIEKey &Key) {
  1253. return static_cast<unsigned>(hash_combine(Key.Personality,
  1254. Key.PersonalityEncoding,
  1255. Key.LsdaEncoding,
  1256. Key.IsSignalFrame,
  1257. Key.IsSimple));
  1258. }
  1259. static bool isEqual(const CIEKey &LHS,
  1260. const CIEKey &RHS) {
  1261. return LHS.Personality == RHS.Personality &&
  1262. LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
  1263. LHS.LsdaEncoding == RHS.LsdaEncoding &&
  1264. LHS.IsSignalFrame == RHS.IsSignalFrame &&
  1265. LHS.IsSimple == RHS.IsSimple;
  1266. }
  1267. };
  1268. }
  1269. void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
  1270. bool IsEH) {
  1271. Streamer.generateCompactUnwindEncodings(MAB);
  1272. MCContext &Context = Streamer.getContext();
  1273. const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
  1274. FrameEmitterImpl Emitter(IsEH);
  1275. ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
  1276. // Emit the compact unwind info if available.
  1277. bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
  1278. if (IsEH && MOFI->getCompactUnwindSection()) {
  1279. bool SectionEmitted = false;
  1280. for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
  1281. const MCDwarfFrameInfo &Frame = FrameArray[i];
  1282. if (Frame.CompactUnwindEncoding == 0) continue;
  1283. if (!SectionEmitted) {
  1284. Streamer.SwitchSection(MOFI->getCompactUnwindSection());
  1285. Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
  1286. SectionEmitted = true;
  1287. }
  1288. NeedsEHFrameSection |=
  1289. Frame.CompactUnwindEncoding ==
  1290. MOFI->getCompactUnwindDwarfEHFrameOnly();
  1291. Emitter.EmitCompactUnwind(Streamer, Frame);
  1292. }
  1293. }
  1294. if (!NeedsEHFrameSection) return;
  1295. MCSection &Section =
  1296. IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
  1297. : *MOFI->getDwarfFrameSection();
  1298. Streamer.SwitchSection(&Section);
  1299. MCSymbol *SectionStart = Context.createTempSymbol();
  1300. Streamer.EmitLabel(SectionStart);
  1301. Emitter.setSectionStart(SectionStart);
  1302. MCSymbol *FDEEnd = nullptr;
  1303. DenseMap<CIEKey, const MCSymbol *> CIEStarts;
  1304. const MCSymbol *DummyDebugKey = nullptr;
  1305. NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
  1306. for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
  1307. const MCDwarfFrameInfo &Frame = FrameArray[i];
  1308. // Emit the label from the previous iteration
  1309. if (FDEEnd) {
  1310. Streamer.EmitLabel(FDEEnd);
  1311. FDEEnd = nullptr;
  1312. }
  1313. if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
  1314. MOFI->getCompactUnwindDwarfEHFrameOnly())
  1315. // Don't generate an EH frame if we don't need one. I.e., it's taken care
  1316. // of by the compact unwind encoding.
  1317. continue;
  1318. CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
  1319. Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
  1320. const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
  1321. if (!CIEStart)
  1322. CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
  1323. Frame.PersonalityEncoding, Frame.Lsda,
  1324. Frame.IsSignalFrame,
  1325. Frame.LsdaEncoding,
  1326. Frame.IsSimple);
  1327. FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
  1328. }
  1329. Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
  1330. if (FDEEnd)
  1331. Streamer.EmitLabel(FDEEnd);
  1332. }
  1333. void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
  1334. uint64_t AddrDelta) {
  1335. MCContext &Context = Streamer.getContext();
  1336. SmallString<256> Tmp;
  1337. raw_svector_ostream OS(Tmp);
  1338. MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
  1339. Streamer.EmitBytes(OS.str());
  1340. }
  1341. void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
  1342. uint64_t AddrDelta,
  1343. raw_ostream &OS) {
  1344. // Scale the address delta by the minimum instruction length.
  1345. AddrDelta = ScaleAddrDelta(Context, AddrDelta);
  1346. if (AddrDelta == 0) {
  1347. } else if (isUIntN(6, AddrDelta)) {
  1348. uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
  1349. OS << Opcode;
  1350. } else if (isUInt<8>(AddrDelta)) {
  1351. OS << uint8_t(dwarf::DW_CFA_advance_loc1);
  1352. OS << uint8_t(AddrDelta);
  1353. } else if (isUInt<16>(AddrDelta)) {
  1354. OS << uint8_t(dwarf::DW_CFA_advance_loc2);
  1355. if (Context.getAsmInfo()->isLittleEndian())
  1356. support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta);
  1357. else
  1358. support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta);
  1359. } else {
  1360. assert(isUInt<32>(AddrDelta));
  1361. OS << uint8_t(dwarf::DW_CFA_advance_loc4);
  1362. if (Context.getAsmInfo()->isLittleEndian())
  1363. support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta);
  1364. else
  1365. support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta);
  1366. }
  1367. }