DwarfDebug.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  1. //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
  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. //
  10. // This file contains support for writing dwarf debug info into asm files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "DwarfDebug.h"
  14. #include "ByteStreamer.h"
  15. #include "DIEHash.h"
  16. #include "DebugLocEntry.h"
  17. #include "DwarfCompileUnit.h"
  18. #include "DwarfExpression.h"
  19. #include "DwarfUnit.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/CodeGen/DIE.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineModuleInfo.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/ValueHandle.h"
  33. #include "llvm/MC/MCAsmInfo.h"
  34. #include "llvm/MC/MCDwarf.h"
  35. #include "llvm/MC/MCSection.h"
  36. #include "llvm/MC/MCStreamer.h"
  37. #include "llvm/MC/MCSymbol.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/Dwarf.h"
  41. #include "llvm/Support/Endian.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include "llvm/Support/FormattedStream.h"
  44. #include "llvm/Support/LEB128.h"
  45. #include "llvm/Support/MD5.h"
  46. #include "llvm/Support/Path.h"
  47. #include "llvm/Support/Timer.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Target/TargetFrameLowering.h"
  50. #include "llvm/Target/TargetLoweringObjectFile.h"
  51. #include "llvm/Target/TargetMachine.h"
  52. #include "llvm/Target/TargetOptions.h"
  53. #include "llvm/Target/TargetRegisterInfo.h"
  54. #include "llvm/Target/TargetSubtargetInfo.h"
  55. using namespace llvm;
  56. #define DEBUG_TYPE "dwarfdebug"
  57. static cl::opt<bool>
  58. DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
  59. cl::desc("Disable debug info printing"));
  60. static cl::opt<bool> UnknownLocations(
  61. "use-unknown-locations", cl::Hidden,
  62. cl::desc("Make an absence of debug location information explicit."),
  63. cl::init(false));
  64. static cl::opt<bool>
  65. GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
  66. cl::desc("Generate GNU-style pubnames and pubtypes"),
  67. cl::init(false));
  68. static cl::opt<bool> GenerateARangeSection("generate-arange-section",
  69. cl::Hidden,
  70. cl::desc("Generate dwarf aranges"),
  71. cl::init(false));
  72. namespace {
  73. enum DefaultOnOff { Default, Enable, Disable };
  74. }
  75. static cl::opt<DefaultOnOff>
  76. DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
  77. cl::desc("Output prototype dwarf accelerator tables."),
  78. cl::values(clEnumVal(Default, "Default for platform"),
  79. clEnumVal(Enable, "Enabled"),
  80. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  81. cl::init(Default));
  82. static cl::opt<DefaultOnOff>
  83. SplitDwarf("split-dwarf", cl::Hidden,
  84. cl::desc("Output DWARF5 split debug info."),
  85. cl::values(clEnumVal(Default, "Default for platform"),
  86. clEnumVal(Enable, "Enabled"),
  87. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  88. cl::init(Default));
  89. static cl::opt<DefaultOnOff>
  90. DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
  91. cl::desc("Generate DWARF pubnames and pubtypes sections"),
  92. cl::values(clEnumVal(Default, "Default for platform"),
  93. clEnumVal(Enable, "Enabled"),
  94. clEnumVal(Disable, "Disabled"), clEnumValEnd),
  95. cl::init(Default));
  96. enum LinkageNameOption {
  97. DefaultLinkageNames,
  98. AllLinkageNames,
  99. AbstractLinkageNames
  100. };
  101. static cl::opt<LinkageNameOption>
  102. DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
  103. cl::desc("Which DWARF linkage-name attributes to emit."),
  104. cl::values(clEnumValN(DefaultLinkageNames, "Default",
  105. "Default for platform"),
  106. clEnumValN(AllLinkageNames, "All", "All"),
  107. clEnumValN(AbstractLinkageNames, "Abstract",
  108. "Abstract subprograms"),
  109. clEnumValEnd),
  110. cl::init(DefaultLinkageNames));
  111. static const char *const DWARFGroupName = "DWARF Emission";
  112. static const char *const DbgTimerName = "DWARF Debug Writer";
  113. void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
  114. BS.EmitInt8(
  115. Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
  116. : dwarf::OperationEncodingString(Op));
  117. }
  118. void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
  119. BS.EmitSLEB128(Value, Twine(Value));
  120. }
  121. void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
  122. BS.EmitULEB128(Value, Twine(Value));
  123. }
  124. bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
  125. unsigned MachineReg) {
  126. // This information is not available while emitting .debug_loc entries.
  127. return false;
  128. }
  129. //===----------------------------------------------------------------------===//
  130. bool DbgVariable::isBlockByrefVariable() const {
  131. assert(Var && "Invalid complex DbgVariable!");
  132. return Var->getType().resolve()->isBlockByrefStruct();
  133. }
  134. const DIType *DbgVariable::getType() const {
  135. DIType *Ty = Var->getType().resolve();
  136. // FIXME: isBlockByrefVariable should be reformulated in terms of complex
  137. // addresses instead.
  138. if (Ty->isBlockByrefStruct()) {
  139. /* Byref variables, in Blocks, are declared by the programmer as
  140. "SomeType VarName;", but the compiler creates a
  141. __Block_byref_x_VarName struct, and gives the variable VarName
  142. either the struct, or a pointer to the struct, as its type. This
  143. is necessary for various behind-the-scenes things the compiler
  144. needs to do with by-reference variables in blocks.
  145. However, as far as the original *programmer* is concerned, the
  146. variable should still have type 'SomeType', as originally declared.
  147. The following function dives into the __Block_byref_x_VarName
  148. struct to find the original type of the variable. This will be
  149. passed back to the code generating the type for the Debug
  150. Information Entry for the variable 'VarName'. 'VarName' will then
  151. have the original type 'SomeType' in its debug information.
  152. The original type 'SomeType' will be the type of the field named
  153. 'VarName' inside the __Block_byref_x_VarName struct.
  154. NOTE: In order for this to not completely fail on the debugger
  155. side, the Debug Information Entry for the variable VarName needs to
  156. have a DW_AT_location that tells the debugger how to unwind through
  157. the pointers and __Block_byref_x_VarName struct to find the actual
  158. value of the variable. The function addBlockByrefType does this. */
  159. DIType *subType = Ty;
  160. uint16_t tag = Ty->getTag();
  161. if (tag == dwarf::DW_TAG_pointer_type)
  162. subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
  163. auto Elements = cast<DICompositeType>(subType)->getElements();
  164. for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
  165. auto *DT = cast<DIDerivedType>(Elements[i]);
  166. if (getName() == DT->getName())
  167. return resolve(DT->getBaseType());
  168. }
  169. }
  170. return Ty;
  171. }
  172. static const DwarfAccelTable::Atom TypeAtoms[] = {
  173. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
  174. DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
  175. DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
  176. DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
  177. : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
  178. InfoHolder(A, "info_string", DIEValueAllocator),
  179. SkeletonHolder(A, "skel_string", DIEValueAllocator),
  180. IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
  181. AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  182. dwarf::DW_FORM_data4)),
  183. AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  184. dwarf::DW_FORM_data4)),
  185. AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
  186. dwarf::DW_FORM_data4)),
  187. AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) {
  188. CurFn = nullptr;
  189. Triple TT(Asm->getTargetTriple());
  190. // Make sure we know our "debugger tuning." The target option takes
  191. // precedence; fall back to triple-based defaults.
  192. if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
  193. DebuggerTuning = Asm->TM.Options.DebuggerTuning;
  194. else if (IsDarwin)
  195. DebuggerTuning = DebuggerKind::LLDB;
  196. else if (TT.isPS4CPU())
  197. DebuggerTuning = DebuggerKind::SCE;
  198. else
  199. DebuggerTuning = DebuggerKind::GDB;
  200. // Turn on accelerator tables for LLDB by default.
  201. if (DwarfAccelTables == Default)
  202. HasDwarfAccelTables = tuneForLLDB();
  203. else
  204. HasDwarfAccelTables = DwarfAccelTables == Enable;
  205. HasAppleExtensionAttributes = tuneForLLDB();
  206. // Handle split DWARF. Off by default for now.
  207. if (SplitDwarf == Default)
  208. HasSplitDwarf = false;
  209. else
  210. HasSplitDwarf = SplitDwarf == Enable;
  211. // Pubnames/pubtypes on by default for GDB.
  212. if (DwarfPubSections == Default)
  213. HasDwarfPubSections = tuneForGDB();
  214. else
  215. HasDwarfPubSections = DwarfPubSections == Enable;
  216. // SCE defaults to linkage names only for abstract subprograms.
  217. if (DwarfLinkageNames == DefaultLinkageNames)
  218. UseAllLinkageNames = !tuneForSCE();
  219. else
  220. UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
  221. unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
  222. DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
  223. : MMI->getModule()->getDwarfVersion();
  224. // Use dwarf 4 by default if nothing is requested.
  225. DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
  226. // Work around a GDB bug. GDB doesn't support the standard opcode;
  227. // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
  228. // is defined as of DWARF 3.
  229. // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
  230. // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
  231. UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
  232. // GDB does not fully support the DWARF 4 representation for bitfields.
  233. UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
  234. Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
  235. }
  236. // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
  237. DwarfDebug::~DwarfDebug() { }
  238. static bool isObjCClass(StringRef Name) {
  239. return Name.startswith("+") || Name.startswith("-");
  240. }
  241. static bool hasObjCCategory(StringRef Name) {
  242. if (!isObjCClass(Name))
  243. return false;
  244. return Name.find(") ") != StringRef::npos;
  245. }
  246. static void getObjCClassCategory(StringRef In, StringRef &Class,
  247. StringRef &Category) {
  248. if (!hasObjCCategory(In)) {
  249. Class = In.slice(In.find('[') + 1, In.find(' '));
  250. Category = "";
  251. return;
  252. }
  253. Class = In.slice(In.find('[') + 1, In.find('('));
  254. Category = In.slice(In.find('[') + 1, In.find(' '));
  255. }
  256. static StringRef getObjCMethodName(StringRef In) {
  257. return In.slice(In.find(' ') + 1, In.find(']'));
  258. }
  259. // Add the various names to the Dwarf accelerator table names.
  260. // TODO: Determine whether or not we should add names for programs
  261. // that do not have a DW_AT_name or DW_AT_linkage_name field - this
  262. // is only slightly different than the lookup of non-standard ObjC names.
  263. void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
  264. if (!SP->isDefinition())
  265. return;
  266. addAccelName(SP->getName(), Die);
  267. // If the linkage name is different than the name, go ahead and output
  268. // that as well into the name table.
  269. if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
  270. addAccelName(SP->getLinkageName(), Die);
  271. // If this is an Objective-C selector name add it to the ObjC accelerator
  272. // too.
  273. if (isObjCClass(SP->getName())) {
  274. StringRef Class, Category;
  275. getObjCClassCategory(SP->getName(), Class, Category);
  276. addAccelObjC(Class, Die);
  277. if (Category != "")
  278. addAccelObjC(Category, Die);
  279. // Also add the base method name to the name table.
  280. addAccelName(getObjCMethodName(SP->getName()), Die);
  281. }
  282. }
  283. /// Check whether we should create a DIE for the given Scope, return true
  284. /// if we don't create a DIE (the corresponding DIE is null).
  285. bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
  286. if (Scope->isAbstractScope())
  287. return false;
  288. // We don't create a DIE if there is no Range.
  289. const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
  290. if (Ranges.empty())
  291. return true;
  292. if (Ranges.size() > 1)
  293. return false;
  294. // We don't create a DIE if we have a single Range and the end label
  295. // is null.
  296. return !getLabelAfterInsn(Ranges.front().second);
  297. }
  298. template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
  299. F(CU);
  300. if (auto *SkelCU = CU.getSkeleton())
  301. if (CU.getCUNode()->getSplitDebugInlining())
  302. F(*SkelCU);
  303. }
  304. void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
  305. assert(Scope && Scope->getScopeNode());
  306. assert(Scope->isAbstractScope());
  307. assert(!Scope->getInlinedAt());
  308. const MDNode *SP = Scope->getScopeNode();
  309. ProcessedSPNodes.insert(SP);
  310. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  311. // was inlined from another compile unit.
  312. auto &CU = *CUMap.lookup(cast<DISubprogram>(SP)->getUnit());
  313. forBothCUs(CU, [&](DwarfCompileUnit &CU) {
  314. CU.constructAbstractSubprogramScopeDIE(Scope);
  315. });
  316. }
  317. void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
  318. if (!GenerateGnuPubSections)
  319. return;
  320. U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
  321. }
  322. // Create new DwarfCompileUnit for the given metadata node with tag
  323. // DW_TAG_compile_unit.
  324. DwarfCompileUnit &
  325. DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) {
  326. StringRef FN = DIUnit->getFilename();
  327. CompilationDir = DIUnit->getDirectory();
  328. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  329. InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
  330. DwarfCompileUnit &NewCU = *OwnedUnit;
  331. DIE &Die = NewCU.getUnitDie();
  332. InfoHolder.addUnit(std::move(OwnedUnit));
  333. if (useSplitDwarf()) {
  334. NewCU.setSkeleton(constructSkeletonCU(NewCU));
  335. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  336. DIUnit->getSplitDebugFilename());
  337. }
  338. // LTO with assembly output shares a single line table amongst multiple CUs.
  339. // To avoid the compilation directory being ambiguous, let the line table
  340. // explicitly describe the directory of all files, never relying on the
  341. // compilation directory.
  342. if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
  343. Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
  344. NewCU.getUniqueID(), CompilationDir);
  345. NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer());
  346. NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  347. DIUnit->getSourceLanguage());
  348. NewCU.addString(Die, dwarf::DW_AT_name, FN);
  349. if (!useSplitDwarf()) {
  350. NewCU.initStmtList();
  351. // If we're using split dwarf the compilation dir is going to be in the
  352. // skeleton CU and so we don't need to duplicate it here.
  353. if (!CompilationDir.empty())
  354. NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  355. addGnuPubAttributes(NewCU, Die);
  356. }
  357. if (useAppleExtensionAttributes()) {
  358. if (DIUnit->isOptimized())
  359. NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
  360. StringRef Flags = DIUnit->getFlags();
  361. if (!Flags.empty())
  362. NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  363. if (unsigned RVer = DIUnit->getRuntimeVersion())
  364. NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
  365. dwarf::DW_FORM_data1, RVer);
  366. }
  367. if (useSplitDwarf())
  368. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
  369. else
  370. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
  371. if (DIUnit->getDWOId()) {
  372. // This CU is either a clang module DWO or a skeleton CU.
  373. NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
  374. DIUnit->getDWOId());
  375. if (!DIUnit->getSplitDebugFilename().empty())
  376. // This is a prefabricated skeleton CU.
  377. NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
  378. DIUnit->getSplitDebugFilename());
  379. }
  380. CUMap.insert({DIUnit, &NewCU});
  381. CUDieMap.insert({&Die, &NewCU});
  382. return NewCU;
  383. }
  384. void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
  385. const DIImportedEntity *N) {
  386. if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
  387. D->addChild(TheCU.constructImportedEntityDIE(N));
  388. }
  389. // Emit all Dwarf sections that should come prior to the content. Create
  390. // global DIEs and emit initial debug info sections. This is invoked by
  391. // the target AsmPrinter.
  392. void DwarfDebug::beginModule() {
  393. NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
  394. if (DisableDebugInfoPrinting)
  395. return;
  396. const Module *M = MMI->getModule();
  397. unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
  398. M->debug_compile_units_end());
  399. // Tell MMI whether we have debug info.
  400. MMI->setDebugInfoAvailability(NumDebugCUs > 0);
  401. SingleCU = NumDebugCUs == 1;
  402. DenseMap<DIGlobalVariable *, const GlobalVariable *> GVMap;
  403. for (const GlobalVariable &Global : M->globals()) {
  404. SmallVector<DIGlobalVariable *, 1> GVs;
  405. Global.getDebugInfo(GVs);
  406. for (auto &GV : GVs)
  407. GVMap[GV] = &Global;
  408. }
  409. for (DICompileUnit *CUNode : M->debug_compile_units()) {
  410. DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
  411. for (auto *IE : CUNode->getImportedEntities())
  412. CU.addImportedEntity(IE);
  413. for (auto *GV : CUNode->getGlobalVariables())
  414. CU.getOrCreateGlobalVariableDIE(GV, GVMap.lookup(GV));
  415. for (auto *Ty : CUNode->getEnumTypes()) {
  416. // The enum types array by design contains pointers to
  417. // MDNodes rather than DIRefs. Unique them here.
  418. CU.getOrCreateTypeDIE(cast<DIType>(Ty));
  419. }
  420. for (auto *Ty : CUNode->getRetainedTypes()) {
  421. // The retained types array by design contains pointers to
  422. // MDNodes rather than DIRefs. Unique them here.
  423. if (DIType *RT = dyn_cast<DIType>(Ty))
  424. if (!RT->isExternalTypeRef())
  425. // There is no point in force-emitting a forward declaration.
  426. CU.getOrCreateTypeDIE(RT);
  427. }
  428. // Emit imported_modules last so that the relevant context is already
  429. // available.
  430. for (auto *IE : CUNode->getImportedEntities())
  431. constructAndAddImportedEntityDIE(CU, IE);
  432. }
  433. }
  434. void DwarfDebug::finishVariableDefinitions() {
  435. for (const auto &Var : ConcreteVariables) {
  436. DIE *VariableDie = Var->getDIE();
  437. assert(VariableDie);
  438. // FIXME: Consider the time-space tradeoff of just storing the unit pointer
  439. // in the ConcreteVariables list, rather than looking it up again here.
  440. // DIE::getUnit isn't simple - it walks parent pointers, etc.
  441. DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
  442. assert(Unit);
  443. DbgVariable *AbsVar = getExistingAbstractVariable(
  444. InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
  445. if (AbsVar && AbsVar->getDIE()) {
  446. Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
  447. *AbsVar->getDIE());
  448. } else
  449. Unit->applyVariableAttributes(*Var, *VariableDie);
  450. }
  451. }
  452. void DwarfDebug::finishSubprogramDefinitions() {
  453. for (auto &F : MMI->getModule()->functions())
  454. if (auto *SP = F.getSubprogram())
  455. if (ProcessedSPNodes.count(SP) &&
  456. SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)
  457. forBothCUs(*CUMap.lookup(SP->getUnit()), [&](DwarfCompileUnit &CU) {
  458. CU.finishSubprogramDefinition(SP);
  459. });
  460. }
  461. void DwarfDebug::finalizeModuleInfo() {
  462. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  463. finishSubprogramDefinitions();
  464. finishVariableDefinitions();
  465. // Handle anything that needs to be done on a per-unit basis after
  466. // all other generation.
  467. for (const auto &P : CUMap) {
  468. auto &TheCU = *P.second;
  469. // Emit DW_AT_containing_type attribute to connect types with their
  470. // vtable holding type.
  471. TheCU.constructContainingTypeDIEs();
  472. // Add CU specific attributes if we need to add any.
  473. // If we're splitting the dwarf out now that we've got the entire
  474. // CU then add the dwo id to it.
  475. auto *SkCU = TheCU.getSkeleton();
  476. if (useSplitDwarf()) {
  477. // Emit a unique identifier for this CU.
  478. uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
  479. TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  480. dwarf::DW_FORM_data8, ID);
  481. SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
  482. dwarf::DW_FORM_data8, ID);
  483. // We don't keep track of which addresses are used in which CU so this
  484. // is a bit pessimistic under LTO.
  485. if (!AddrPool.isEmpty()) {
  486. const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
  487. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
  488. Sym, Sym);
  489. }
  490. if (!SkCU->getRangeLists().empty()) {
  491. const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
  492. SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
  493. Sym, Sym);
  494. }
  495. }
  496. // If we have code split among multiple sections or non-contiguous
  497. // ranges of code then emit a DW_AT_ranges attribute on the unit that will
  498. // remain in the .o file, otherwise add a DW_AT_low_pc.
  499. // FIXME: We should use ranges allow reordering of code ala
  500. // .subsections_via_symbols in mach-o. This would mean turning on
  501. // ranges for all subprogram DIEs for mach-o.
  502. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  503. if (unsigned NumRanges = TheCU.getRanges().size()) {
  504. if (NumRanges > 1)
  505. // A DW_AT_low_pc attribute may also be specified in combination with
  506. // DW_AT_ranges to specify the default base address for use in
  507. // location lists (see Section 2.6.2) and range lists (see Section
  508. // 2.17.3).
  509. U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
  510. else
  511. U.setBaseAddress(TheCU.getRanges().front().getStart());
  512. U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
  513. }
  514. auto *CUNode = cast<DICompileUnit>(P.first);
  515. // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
  516. if (CUNode->getMacros())
  517. U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
  518. U.getMacroLabelBegin(),
  519. TLOF.getDwarfMacinfoSection()->getBeginSymbol());
  520. }
  521. // Compute DIE offsets and sizes.
  522. InfoHolder.computeSizeAndOffsets();
  523. if (useSplitDwarf())
  524. SkeletonHolder.computeSizeAndOffsets();
  525. }
  526. // Emit all Dwarf sections that should come after the content.
  527. void DwarfDebug::endModule() {
  528. assert(CurFn == nullptr);
  529. assert(CurMI == nullptr);
  530. // If we aren't actually generating debug info (check beginModule -
  531. // conditionalized on !DisableDebugInfoPrinting and the presence of the
  532. // llvm.dbg.cu metadata node)
  533. if (!MMI->hasDebugInfo())
  534. return;
  535. // Finalize the debug info for the module.
  536. finalizeModuleInfo();
  537. emitDebugStr();
  538. if (useSplitDwarf())
  539. emitDebugLocDWO();
  540. else
  541. // Emit info into a debug loc section.
  542. emitDebugLoc();
  543. // Corresponding abbreviations into a abbrev section.
  544. emitAbbreviations();
  545. // Emit all the DIEs into a debug info section.
  546. emitDebugInfo();
  547. // Emit info into a debug aranges section.
  548. if (GenerateARangeSection)
  549. emitDebugARanges();
  550. // Emit info into a debug ranges section.
  551. emitDebugRanges();
  552. // Emit info into a debug macinfo section.
  553. emitDebugMacinfo();
  554. if (useSplitDwarf()) {
  555. emitDebugStrDWO();
  556. emitDebugInfoDWO();
  557. emitDebugAbbrevDWO();
  558. emitDebugLineDWO();
  559. // Emit DWO addresses.
  560. AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
  561. }
  562. // Emit info into the dwarf accelerator table sections.
  563. if (useDwarfAccelTables()) {
  564. emitAccelNames();
  565. emitAccelObjC();
  566. emitAccelNamespaces();
  567. emitAccelTypes();
  568. }
  569. // Emit the pubnames and pubtypes sections if requested.
  570. if (HasDwarfPubSections) {
  571. emitDebugPubNames(GenerateGnuPubSections);
  572. emitDebugPubTypes(GenerateGnuPubSections);
  573. }
  574. // clean up.
  575. AbstractVariables.clear();
  576. }
  577. // Find abstract variable, if any, associated with Var.
  578. DbgVariable *
  579. DwarfDebug::getExistingAbstractVariable(InlinedVariable IV,
  580. const DILocalVariable *&Cleansed) {
  581. // More then one inlined variable corresponds to one abstract variable.
  582. Cleansed = IV.first;
  583. auto I = AbstractVariables.find(Cleansed);
  584. if (I != AbstractVariables.end())
  585. return I->second.get();
  586. return nullptr;
  587. }
  588. DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) {
  589. const DILocalVariable *Cleansed;
  590. return getExistingAbstractVariable(IV, Cleansed);
  591. }
  592. void DwarfDebug::createAbstractVariable(const DILocalVariable *Var,
  593. LexicalScope *Scope) {
  594. auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr);
  595. InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
  596. AbstractVariables[Var] = std::move(AbsDbgVariable);
  597. }
  598. void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV,
  599. const MDNode *ScopeNode) {
  600. const DILocalVariable *Cleansed = nullptr;
  601. if (getExistingAbstractVariable(IV, Cleansed))
  602. return;
  603. createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
  604. cast<DILocalScope>(ScopeNode)));
  605. }
  606. void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(
  607. InlinedVariable IV, const MDNode *ScopeNode) {
  608. const DILocalVariable *Cleansed = nullptr;
  609. if (getExistingAbstractVariable(IV, Cleansed))
  610. return;
  611. if (LexicalScope *Scope =
  612. LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
  613. createAbstractVariable(Cleansed, Scope);
  614. }
  615. // Collect variable information from side table maintained by MMI.
  616. void DwarfDebug::collectVariableInfoFromMMITable(
  617. DenseSet<InlinedVariable> &Processed) {
  618. for (const auto &VI : MMI->getVariableDbgInfo()) {
  619. if (!VI.Var)
  620. continue;
  621. assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
  622. "Expected inlined-at fields to agree");
  623. InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
  624. Processed.insert(Var);
  625. LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
  626. // If variable scope is not found then skip this variable.
  627. if (!Scope)
  628. continue;
  629. ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode());
  630. auto RegVar = make_unique<DbgVariable>(Var.first, Var.second);
  631. RegVar->initializeMMI(VI.Expr, VI.Slot);
  632. if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
  633. ConcreteVariables.push_back(std::move(RegVar));
  634. }
  635. }
  636. // Get .debug_loc entry for the instruction range starting at MI.
  637. static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
  638. const DIExpression *Expr = MI->getDebugExpression();
  639. assert(MI->getNumOperands() == 4);
  640. if (MI->getOperand(0).isReg()) {
  641. MachineLocation MLoc;
  642. // If the second operand is an immediate, this is a
  643. // register-indirect address.
  644. if (!MI->getOperand(1).isImm())
  645. MLoc.set(MI->getOperand(0).getReg());
  646. else
  647. MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
  648. return DebugLocEntry::Value(Expr, MLoc);
  649. }
  650. if (MI->getOperand(0).isImm())
  651. return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
  652. if (MI->getOperand(0).isFPImm())
  653. return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
  654. if (MI->getOperand(0).isCImm())
  655. return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
  656. llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
  657. }
  658. /// \brief If this and Next are describing different pieces of the same
  659. /// variable, merge them by appending Next's values to the current
  660. /// list of values.
  661. /// Return true if the merge was successful.
  662. bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
  663. if (Begin == Next.Begin) {
  664. auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
  665. auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
  666. if (!FirstExpr->isBitPiece() || !FirstNextExpr->isBitPiece())
  667. return false;
  668. // We can only merge entries if none of the pieces overlap any others.
  669. // In doing so, we can take advantage of the fact that both lists are
  670. // sorted.
  671. for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
  672. for (; j < Next.Values.size(); ++j) {
  673. int res = DebugHandlerBase::pieceCmp(
  674. cast<DIExpression>(Values[i].Expression),
  675. cast<DIExpression>(Next.Values[j].Expression));
  676. if (res == 0) // The two expressions overlap, we can't merge.
  677. return false;
  678. // Values[i] is entirely before Next.Values[j],
  679. // so go back to the next entry of Values.
  680. else if (res == -1)
  681. break;
  682. // Next.Values[j] is entirely before Values[i], so go on to the
  683. // next entry of Next.Values.
  684. }
  685. }
  686. addValues(Next.Values);
  687. End = Next.End;
  688. return true;
  689. }
  690. return false;
  691. }
  692. /// Build the location list for all DBG_VALUEs in the function that
  693. /// describe the same variable. If the ranges of several independent
  694. /// pieces of the same variable overlap partially, split them up and
  695. /// combine the ranges. The resulting DebugLocEntries are will have
  696. /// strict monotonically increasing begin addresses and will never
  697. /// overlap.
  698. //
  699. // Input:
  700. //
  701. // Ranges History [var, loc, piece ofs size]
  702. // 0 | [x, (reg0, piece 0, 32)]
  703. // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
  704. // 2 | | ...
  705. // 3 | [clobber reg0]
  706. // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
  707. // x.
  708. //
  709. // Output:
  710. //
  711. // [0-1] [x, (reg0, piece 0, 32)]
  712. // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
  713. // [3-4] [x, (reg1, piece 32, 32)]
  714. // [4- ] [x, (mem, piece 0, 64)]
  715. void
  716. DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
  717. const DbgValueHistoryMap::InstrRanges &Ranges) {
  718. SmallVector<DebugLocEntry::Value, 4> OpenRanges;
  719. for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  720. const MachineInstr *Begin = I->first;
  721. const MachineInstr *End = I->second;
  722. assert(Begin->isDebugValue() && "Invalid History entry");
  723. // Check if a variable is inaccessible in this range.
  724. if (Begin->getNumOperands() > 1 &&
  725. Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
  726. OpenRanges.clear();
  727. continue;
  728. }
  729. // If this piece overlaps with any open ranges, truncate them.
  730. const DIExpression *DIExpr = Begin->getDebugExpression();
  731. auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
  732. return piecesOverlap(DIExpr, R.getExpression());
  733. });
  734. OpenRanges.erase(Last, OpenRanges.end());
  735. const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
  736. assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
  737. const MCSymbol *EndLabel;
  738. if (End != nullptr)
  739. EndLabel = getLabelAfterInsn(End);
  740. else if (std::next(I) == Ranges.end())
  741. EndLabel = Asm->getFunctionEnd();
  742. else
  743. EndLabel = getLabelBeforeInsn(std::next(I)->first);
  744. assert(EndLabel && "Forgot label after instruction ending a range!");
  745. DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
  746. auto Value = getDebugLocValue(Begin);
  747. DebugLocEntry Loc(StartLabel, EndLabel, Value);
  748. bool couldMerge = false;
  749. // If this is a piece, it may belong to the current DebugLocEntry.
  750. if (DIExpr->isBitPiece()) {
  751. // Add this value to the list of open ranges.
  752. OpenRanges.push_back(Value);
  753. // Attempt to add the piece to the last entry.
  754. if (!DebugLoc.empty())
  755. if (DebugLoc.back().MergeValues(Loc))
  756. couldMerge = true;
  757. }
  758. if (!couldMerge) {
  759. // Need to add a new DebugLocEntry. Add all values from still
  760. // valid non-overlapping pieces.
  761. if (OpenRanges.size())
  762. Loc.addValues(OpenRanges);
  763. DebugLoc.push_back(std::move(Loc));
  764. }
  765. // Attempt to coalesce the ranges of two otherwise identical
  766. // DebugLocEntries.
  767. auto CurEntry = DebugLoc.rbegin();
  768. DEBUG({
  769. dbgs() << CurEntry->getValues().size() << " Values:\n";
  770. for (auto &Value : CurEntry->getValues())
  771. Value.dump();
  772. dbgs() << "-----\n";
  773. });
  774. auto PrevEntry = std::next(CurEntry);
  775. if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
  776. DebugLoc.pop_back();
  777. }
  778. }
  779. DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope,
  780. InlinedVariable IV) {
  781. ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode());
  782. ConcreteVariables.push_back(make_unique<DbgVariable>(IV.first, IV.second));
  783. InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
  784. return ConcreteVariables.back().get();
  785. }
  786. // Determine whether this DBG_VALUE is valid at the beginning of the function.
  787. static bool validAtEntry(const MachineInstr *MInsn) {
  788. auto MBB = MInsn->getParent();
  789. // Is it in the entry basic block?
  790. if (!MBB->pred_empty())
  791. return false;
  792. for (MachineBasicBlock::const_reverse_iterator I(MInsn); I != MBB->rend(); ++I)
  793. if (!(I->isDebugValue() || I->getFlag(MachineInstr::FrameSetup)))
  794. return false;
  795. return true;
  796. }
  797. // Find variables for each lexical scope.
  798. void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
  799. const DISubprogram *SP,
  800. DenseSet<InlinedVariable> &Processed) {
  801. // Grab the variable info that was squirreled away in the MMI side-table.
  802. collectVariableInfoFromMMITable(Processed);
  803. for (const auto &I : DbgValues) {
  804. InlinedVariable IV = I.first;
  805. if (Processed.count(IV))
  806. continue;
  807. // Instruction ranges, specifying where IV is accessible.
  808. const auto &Ranges = I.second;
  809. if (Ranges.empty())
  810. continue;
  811. LexicalScope *Scope = nullptr;
  812. if (const DILocation *IA = IV.second)
  813. Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
  814. else
  815. Scope = LScopes.findLexicalScope(IV.first->getScope());
  816. // If variable scope is not found then skip this variable.
  817. if (!Scope)
  818. continue;
  819. Processed.insert(IV);
  820. DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
  821. const MachineInstr *MInsn = Ranges.front().first;
  822. assert(MInsn->isDebugValue() && "History must begin with debug value");
  823. // Check if there is a single DBG_VALUE, valid throughout the function.
  824. // A single constant is also considered valid for the entire function.
  825. if (Ranges.size() == 1 &&
  826. (MInsn->getOperand(0).isImm() ||
  827. (validAtEntry(MInsn) && Ranges.front().second == nullptr))) {
  828. RegVar->initializeDbgValue(MInsn);
  829. continue;
  830. }
  831. // Handle multiple DBG_VALUE instructions describing one variable.
  832. DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
  833. // Build the location list for this variable.
  834. SmallVector<DebugLocEntry, 8> Entries;
  835. buildLocationList(Entries, Ranges);
  836. // If the variable has a DIBasicType, extract it. Basic types cannot have
  837. // unique identifiers, so don't bother resolving the type with the
  838. // identifier map.
  839. const DIBasicType *BT = dyn_cast<DIBasicType>(
  840. static_cast<const Metadata *>(IV.first->getType()));
  841. // Finalize the entry by lowering it into a DWARF bytestream.
  842. for (auto &Entry : Entries)
  843. Entry.finalize(*Asm, List, BT);
  844. }
  845. // Collect info for variables that were optimized out.
  846. for (const DILocalVariable *DV : SP->getVariables()) {
  847. if (Processed.insert(InlinedVariable(DV, nullptr)).second)
  848. if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
  849. createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
  850. }
  851. }
  852. // Process beginning of an instruction.
  853. void DwarfDebug::beginInstruction(const MachineInstr *MI) {
  854. DebugHandlerBase::beginInstruction(MI);
  855. assert(CurMI);
  856. // Check if source location changes, but ignore DBG_VALUE locations.
  857. if (!MI->isDebugValue()) {
  858. const DebugLoc &DL = MI->getDebugLoc();
  859. if (DL != PrevInstLoc) {
  860. if (DL) {
  861. unsigned Flags = 0;
  862. PrevInstLoc = DL;
  863. if (DL == PrologEndLoc) {
  864. Flags |= DWARF2_FLAG_PROLOGUE_END;
  865. PrologEndLoc = DebugLoc();
  866. Flags |= DWARF2_FLAG_IS_STMT;
  867. }
  868. if (DL.getLine() !=
  869. Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine())
  870. Flags |= DWARF2_FLAG_IS_STMT;
  871. const MDNode *Scope = DL.getScope();
  872. recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
  873. } else if (UnknownLocations) {
  874. PrevInstLoc = DL;
  875. recordSourceLine(0, 0, nullptr, 0);
  876. }
  877. }
  878. }
  879. }
  880. static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
  881. // First known non-DBG_VALUE and non-frame setup location marks
  882. // the beginning of the function body.
  883. for (const auto &MBB : *MF)
  884. for (const auto &MI : MBB)
  885. if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
  886. MI.getDebugLoc())
  887. return MI.getDebugLoc();
  888. return DebugLoc();
  889. }
  890. // Gather pre-function debug information. Assumes being called immediately
  891. // after the function entry point has been emitted.
  892. void DwarfDebug::beginFunction(const MachineFunction *MF) {
  893. CurFn = MF;
  894. // If there's no debug info for the function we're not going to do anything.
  895. if (!MMI->hasDebugInfo())
  896. return;
  897. auto DI = MF->getFunction()->getSubprogram();
  898. if (!DI)
  899. return;
  900. // Grab the lexical scopes for the function, if we don't have any of those
  901. // then we're not going to be able to do anything.
  902. DebugHandlerBase::beginFunction(MF);
  903. if (LScopes.empty())
  904. return;
  905. // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
  906. // belongs to so that we add to the correct per-cu line table in the
  907. // non-asm case.
  908. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  909. // FnScope->getScopeNode() and DI->second should represent the same function,
  910. // though they may not be the same MDNode due to inline functions merged in
  911. // LTO where the debug info metadata still differs (either due to distinct
  912. // written differences - two versions of a linkonce_odr function
  913. // written/copied into two separate files, or some sub-optimal metadata that
  914. // isn't structurally identical (see: file path/name info from clang, which
  915. // includes the directory of the cpp file being built, even when the file name
  916. // is absolute (such as an <> lookup header)))
  917. auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
  918. DwarfCompileUnit *TheCU = CUMap.lookup(SP->getUnit());
  919. if (!TheCU) {
  920. assert(SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug &&
  921. "DICompileUnit missing from llvm.dbg.cu?");
  922. return;
  923. }
  924. if (Asm->OutStreamer->hasRawTextSupport())
  925. // Use a single line table if we are generating assembly.
  926. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  927. else
  928. Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
  929. // Record beginning of function.
  930. PrologEndLoc = findPrologueEndLoc(MF);
  931. if (DILocation *L = PrologEndLoc) {
  932. // We'd like to list the prologue as "not statements" but GDB behaves
  933. // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
  934. auto *SP = L->getInlinedAtScope()->getSubprogram();
  935. recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
  936. }
  937. }
  938. // Gather and emit post-function debug information.
  939. void DwarfDebug::endFunction(const MachineFunction *MF) {
  940. assert(CurFn == MF &&
  941. "endFunction should be called with the same function as beginFunction");
  942. const DISubprogram *SP = MF->getFunction()->getSubprogram();
  943. if (!MMI->hasDebugInfo() || LScopes.empty() || !SP ||
  944. SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) {
  945. // If we don't have a lexical scope for this function then there will
  946. // be a hole in the range information. Keep note of this by setting the
  947. // previously used section to nullptr.
  948. PrevCU = nullptr;
  949. CurFn = nullptr;
  950. DebugHandlerBase::endFunction(MF);
  951. // Mark functions with no debug info on any instructions, but a
  952. // valid DISubprogram as processed.
  953. if (SP)
  954. ProcessedSPNodes.insert(SP);
  955. return;
  956. }
  957. // Set DwarfDwarfCompileUnitID in MCContext to default value.
  958. Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
  959. LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
  960. SP = cast<DISubprogram>(FnScope->getScopeNode());
  961. DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
  962. DenseSet<InlinedVariable> ProcessedVars;
  963. collectVariableInfo(TheCU, SP, ProcessedVars);
  964. // Add the range of this function to the list of ranges for the CU.
  965. TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
  966. // Under -gmlt, skip building the subprogram if there are no inlined
  967. // subroutines inside it.
  968. if (TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
  969. LScopes.getAbstractScopesList().empty() && !IsDarwin) {
  970. assert(InfoHolder.getScopeVariables().empty());
  971. assert(DbgValues.empty());
  972. // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
  973. // by a -gmlt CU. Add a test and remove this assertion.
  974. assert(AbstractVariables.empty());
  975. PrevLabel = nullptr;
  976. CurFn = nullptr;
  977. DebugHandlerBase::endFunction(MF);
  978. return;
  979. }
  980. #ifndef NDEBUG
  981. size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
  982. #endif
  983. // Construct abstract scopes.
  984. for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
  985. auto *SP = cast<DISubprogram>(AScope->getScopeNode());
  986. // Collect info for variables that were optimized out.
  987. for (const DILocalVariable *DV : SP->getVariables()) {
  988. if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
  989. continue;
  990. ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
  991. DV->getScope());
  992. assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
  993. && "ensureAbstractVariableIsCreated inserted abstract scopes");
  994. }
  995. constructAbstractSubprogramScopeDIE(AScope);
  996. }
  997. TheCU.constructSubprogramScopeDIE(FnScope);
  998. if (auto *SkelCU = TheCU.getSkeleton())
  999. if (!LScopes.getAbstractScopesList().empty() &&
  1000. TheCU.getCUNode()->getSplitDebugInlining())
  1001. SkelCU->constructSubprogramScopeDIE(FnScope);
  1002. // Clear debug info
  1003. // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
  1004. // DbgVariables except those that are also in AbstractVariables (since they
  1005. // can be used cross-function)
  1006. InfoHolder.getScopeVariables().clear();
  1007. PrevLabel = nullptr;
  1008. CurFn = nullptr;
  1009. DebugHandlerBase::endFunction(MF);
  1010. }
  1011. // Register a source line with debug info. Returns the unique label that was
  1012. // emitted and which provides correspondence to the source line list.
  1013. void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
  1014. unsigned Flags) {
  1015. StringRef Fn;
  1016. StringRef Dir;
  1017. unsigned Src = 1;
  1018. unsigned Discriminator = 0;
  1019. if (auto *Scope = cast_or_null<DIScope>(S)) {
  1020. Fn = Scope->getFilename();
  1021. Dir = Scope->getDirectory();
  1022. if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
  1023. Discriminator = LBF->getDiscriminator();
  1024. unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
  1025. Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
  1026. .getOrCreateSourceID(Fn, Dir);
  1027. }
  1028. Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
  1029. Discriminator, Fn);
  1030. }
  1031. //===----------------------------------------------------------------------===//
  1032. // Emit Methods
  1033. //===----------------------------------------------------------------------===//
  1034. // Emit the debug info section.
  1035. void DwarfDebug::emitDebugInfo() {
  1036. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1037. Holder.emitUnits(/* UseOffsets */ false);
  1038. }
  1039. // Emit the abbreviation section.
  1040. void DwarfDebug::emitAbbreviations() {
  1041. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1042. Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
  1043. }
  1044. void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
  1045. StringRef TableName) {
  1046. Accel.FinalizeTable(Asm, TableName);
  1047. Asm->OutStreamer->SwitchSection(Section);
  1048. // Emit the full data.
  1049. Accel.emit(Asm, Section->getBeginSymbol(), this);
  1050. }
  1051. // Emit visible names into a hashed accelerator table section.
  1052. void DwarfDebug::emitAccelNames() {
  1053. emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
  1054. "Names");
  1055. }
  1056. // Emit objective C classes and categories into a hashed accelerator table
  1057. // section.
  1058. void DwarfDebug::emitAccelObjC() {
  1059. emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
  1060. "ObjC");
  1061. }
  1062. // Emit namespace dies into a hashed accelerator table.
  1063. void DwarfDebug::emitAccelNamespaces() {
  1064. emitAccel(AccelNamespace,
  1065. Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
  1066. "namespac");
  1067. }
  1068. // Emit type dies into a hashed accelerator table.
  1069. void DwarfDebug::emitAccelTypes() {
  1070. emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
  1071. "types");
  1072. }
  1073. // Public name handling.
  1074. // The format for the various pubnames:
  1075. //
  1076. // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
  1077. // for the DIE that is named.
  1078. //
  1079. // gnu pubnames - offset/index value/name tuples where the offset is the offset
  1080. // into the CU and the index value is computed according to the type of value
  1081. // for the DIE that is named.
  1082. //
  1083. // For type units the offset is the offset of the skeleton DIE. For split dwarf
  1084. // it's the offset within the debug_info/debug_types dwo section, however, the
  1085. // reference in the pubname header doesn't change.
  1086. /// computeIndexValue - Compute the gdb index value for the DIE and CU.
  1087. static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
  1088. const DIE *Die) {
  1089. dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
  1090. // We could have a specification DIE that has our most of our knowledge,
  1091. // look for that now.
  1092. if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
  1093. DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
  1094. if (SpecDIE.findAttribute(dwarf::DW_AT_external))
  1095. Linkage = dwarf::GIEL_EXTERNAL;
  1096. } else if (Die->findAttribute(dwarf::DW_AT_external))
  1097. Linkage = dwarf::GIEL_EXTERNAL;
  1098. switch (Die->getTag()) {
  1099. case dwarf::DW_TAG_class_type:
  1100. case dwarf::DW_TAG_structure_type:
  1101. case dwarf::DW_TAG_union_type:
  1102. case dwarf::DW_TAG_enumeration_type:
  1103. return dwarf::PubIndexEntryDescriptor(
  1104. dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
  1105. ? dwarf::GIEL_STATIC
  1106. : dwarf::GIEL_EXTERNAL);
  1107. case dwarf::DW_TAG_typedef:
  1108. case dwarf::DW_TAG_base_type:
  1109. case dwarf::DW_TAG_subrange_type:
  1110. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
  1111. case dwarf::DW_TAG_namespace:
  1112. return dwarf::GIEK_TYPE;
  1113. case dwarf::DW_TAG_subprogram:
  1114. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
  1115. case dwarf::DW_TAG_variable:
  1116. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
  1117. case dwarf::DW_TAG_enumerator:
  1118. return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
  1119. dwarf::GIEL_STATIC);
  1120. default:
  1121. return dwarf::GIEK_NONE;
  1122. }
  1123. }
  1124. /// emitDebugPubNames - Emit visible names into a debug pubnames section.
  1125. ///
  1126. void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
  1127. MCSection *PSec = GnuStyle
  1128. ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
  1129. : Asm->getObjFileLowering().getDwarfPubNamesSection();
  1130. emitDebugPubSection(GnuStyle, PSec, "Names",
  1131. &DwarfCompileUnit::getGlobalNames);
  1132. }
  1133. void DwarfDebug::emitDebugPubSection(
  1134. bool GnuStyle, MCSection *PSec, StringRef Name,
  1135. const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
  1136. for (const auto &NU : CUMap) {
  1137. DwarfCompileUnit *TheU = NU.second;
  1138. const auto &Globals = (TheU->*Accessor)();
  1139. if (Globals.empty())
  1140. continue;
  1141. if (auto *Skeleton = TheU->getSkeleton())
  1142. TheU = Skeleton;
  1143. // Start the dwarf pubnames section.
  1144. Asm->OutStreamer->SwitchSection(PSec);
  1145. // Emit the header.
  1146. Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
  1147. MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
  1148. MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
  1149. Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
  1150. Asm->OutStreamer->EmitLabel(BeginLabel);
  1151. Asm->OutStreamer->AddComment("DWARF Version");
  1152. Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
  1153. Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
  1154. Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
  1155. Asm->OutStreamer->AddComment("Compilation Unit Length");
  1156. Asm->EmitInt32(TheU->getLength());
  1157. // Emit the pubnames for this compilation unit.
  1158. for (const auto &GI : Globals) {
  1159. const char *Name = GI.getKeyData();
  1160. const DIE *Entity = GI.second;
  1161. Asm->OutStreamer->AddComment("DIE offset");
  1162. Asm->EmitInt32(Entity->getOffset());
  1163. if (GnuStyle) {
  1164. dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
  1165. Asm->OutStreamer->AddComment(
  1166. Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
  1167. dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
  1168. Asm->EmitInt8(Desc.toBits());
  1169. }
  1170. Asm->OutStreamer->AddComment("External Name");
  1171. Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
  1172. }
  1173. Asm->OutStreamer->AddComment("End Mark");
  1174. Asm->EmitInt32(0);
  1175. Asm->OutStreamer->EmitLabel(EndLabel);
  1176. }
  1177. }
  1178. void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
  1179. MCSection *PSec = GnuStyle
  1180. ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
  1181. : Asm->getObjFileLowering().getDwarfPubTypesSection();
  1182. emitDebugPubSection(GnuStyle, PSec, "Types",
  1183. &DwarfCompileUnit::getGlobalTypes);
  1184. }
  1185. /// Emit null-terminated strings into a debug str section.
  1186. void DwarfDebug::emitDebugStr() {
  1187. DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
  1188. Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
  1189. }
  1190. void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
  1191. const DebugLocStream::Entry &Entry) {
  1192. auto &&Comments = DebugLocs.getComments(Entry);
  1193. auto Comment = Comments.begin();
  1194. auto End = Comments.end();
  1195. for (uint8_t Byte : DebugLocs.getBytes(Entry))
  1196. Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
  1197. }
  1198. static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
  1199. ByteStreamer &Streamer,
  1200. const DebugLocEntry::Value &Value,
  1201. unsigned PieceOffsetInBits) {
  1202. DebugLocDwarfExpression DwarfExpr(AP.getDwarfDebug()->getDwarfVersion(),
  1203. Streamer);
  1204. // Regular entry.
  1205. if (Value.isInt()) {
  1206. if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
  1207. BT->getEncoding() == dwarf::DW_ATE_signed_char))
  1208. DwarfExpr.AddSignedConstant(Value.getInt());
  1209. else
  1210. DwarfExpr.AddUnsignedConstant(Value.getInt());
  1211. } else if (Value.isLocation()) {
  1212. MachineLocation Loc = Value.getLoc();
  1213. const DIExpression *Expr = Value.getExpression();
  1214. if (!Expr || !Expr->getNumElements())
  1215. // Regular entry.
  1216. AP.EmitDwarfRegOp(Streamer, Loc);
  1217. else {
  1218. // Complex address entry.
  1219. const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
  1220. if (Loc.getOffset()) {
  1221. DwarfExpr.AddMachineRegIndirect(TRI, Loc.getReg(), Loc.getOffset());
  1222. DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
  1223. PieceOffsetInBits);
  1224. } else
  1225. DwarfExpr.AddMachineRegExpression(TRI, Expr, Loc.getReg(),
  1226. PieceOffsetInBits);
  1227. }
  1228. } else if (Value.isConstantFP()) {
  1229. APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
  1230. DwarfExpr.AddUnsignedConstant(RawBytes);
  1231. }
  1232. }
  1233. void DebugLocEntry::finalize(const AsmPrinter &AP,
  1234. DebugLocStream::ListBuilder &List,
  1235. const DIBasicType *BT) {
  1236. DebugLocStream::EntryBuilder Entry(List, Begin, End);
  1237. BufferByteStreamer Streamer = Entry.getStreamer();
  1238. const DebugLocEntry::Value &Value = Values[0];
  1239. if (Value.isBitPiece()) {
  1240. // Emit all pieces that belong to the same variable and range.
  1241. assert(all_of(Values, [](DebugLocEntry::Value P) {
  1242. return P.isBitPiece();
  1243. }) && "all values are expected to be pieces");
  1244. assert(std::is_sorted(Values.begin(), Values.end()) &&
  1245. "pieces are expected to be sorted");
  1246. unsigned Offset = 0;
  1247. for (auto Piece : Values) {
  1248. const DIExpression *Expr = Piece.getExpression();
  1249. unsigned PieceOffset = Expr->getBitPieceOffset();
  1250. unsigned PieceSize = Expr->getBitPieceSize();
  1251. assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
  1252. if (Offset < PieceOffset) {
  1253. // The DWARF spec seriously mandates pieces with no locations for gaps.
  1254. DebugLocDwarfExpression Expr(AP.getDwarfDebug()->getDwarfVersion(),
  1255. Streamer);
  1256. Expr.AddOpPiece(PieceOffset-Offset, 0);
  1257. Offset += PieceOffset-Offset;
  1258. }
  1259. Offset += PieceSize;
  1260. emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset);
  1261. }
  1262. } else {
  1263. assert(Values.size() == 1 && "only pieces may have >1 value");
  1264. emitDebugLocValue(AP, BT, Streamer, Value, 0);
  1265. }
  1266. }
  1267. void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
  1268. // Emit the size.
  1269. Asm->OutStreamer->AddComment("Loc expr size");
  1270. Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
  1271. // Emit the entry.
  1272. APByteStreamer Streamer(*Asm);
  1273. emitDebugLocEntry(Streamer, Entry);
  1274. }
  1275. // Emit locations into the debug loc section.
  1276. void DwarfDebug::emitDebugLoc() {
  1277. // Start the dwarf loc section.
  1278. Asm->OutStreamer->SwitchSection(
  1279. Asm->getObjFileLowering().getDwarfLocSection());
  1280. unsigned char Size = Asm->getDataLayout().getPointerSize();
  1281. for (const auto &List : DebugLocs.getLists()) {
  1282. Asm->OutStreamer->EmitLabel(List.Label);
  1283. const DwarfCompileUnit *CU = List.CU;
  1284. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1285. // Set up the range. This range is relative to the entry point of the
  1286. // compile unit. This is a hard coded 0 for low_pc when we're emitting
  1287. // ranges, or the DW_AT_low_pc on the compile unit otherwise.
  1288. if (auto *Base = CU->getBaseAddress()) {
  1289. Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
  1290. Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
  1291. } else {
  1292. Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
  1293. Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
  1294. }
  1295. emitDebugLocEntryLocation(Entry);
  1296. }
  1297. Asm->OutStreamer->EmitIntValue(0, Size);
  1298. Asm->OutStreamer->EmitIntValue(0, Size);
  1299. }
  1300. }
  1301. void DwarfDebug::emitDebugLocDWO() {
  1302. Asm->OutStreamer->SwitchSection(
  1303. Asm->getObjFileLowering().getDwarfLocDWOSection());
  1304. for (const auto &List : DebugLocs.getLists()) {
  1305. Asm->OutStreamer->EmitLabel(List.Label);
  1306. for (const auto &Entry : DebugLocs.getEntries(List)) {
  1307. // Just always use start_length for now - at least that's one address
  1308. // rather than two. We could get fancier and try to, say, reuse an
  1309. // address we know we've emitted elsewhere (the start of the function?
  1310. // The start of the CU or CU subrange that encloses this range?)
  1311. Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
  1312. unsigned idx = AddrPool.getIndex(Entry.BeginSym);
  1313. Asm->EmitULEB128(idx);
  1314. Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
  1315. emitDebugLocEntryLocation(Entry);
  1316. }
  1317. Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
  1318. }
  1319. }
  1320. struct ArangeSpan {
  1321. const MCSymbol *Start, *End;
  1322. };
  1323. // Emit a debug aranges section, containing a CU lookup for any
  1324. // address we can tie back to a CU.
  1325. void DwarfDebug::emitDebugARanges() {
  1326. // Provides a unique id per text section.
  1327. MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
  1328. // Filter labels by section.
  1329. for (const SymbolCU &SCU : ArangeLabels) {
  1330. if (SCU.Sym->isInSection()) {
  1331. // Make a note of this symbol and it's section.
  1332. MCSection *Section = &SCU.Sym->getSection();
  1333. if (!Section->getKind().isMetadata())
  1334. SectionMap[Section].push_back(SCU);
  1335. } else {
  1336. // Some symbols (e.g. common/bss on mach-o) can have no section but still
  1337. // appear in the output. This sucks as we rely on sections to build
  1338. // arange spans. We can do it without, but it's icky.
  1339. SectionMap[nullptr].push_back(SCU);
  1340. }
  1341. }
  1342. DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
  1343. for (auto &I : SectionMap) {
  1344. MCSection *Section = I.first;
  1345. SmallVector<SymbolCU, 8> &List = I.second;
  1346. if (List.size() < 1)
  1347. continue;
  1348. // If we have no section (e.g. common), just write out
  1349. // individual spans for each symbol.
  1350. if (!Section) {
  1351. for (const SymbolCU &Cur : List) {
  1352. ArangeSpan Span;
  1353. Span.Start = Cur.Sym;
  1354. Span.End = nullptr;
  1355. assert(Cur.CU);
  1356. Spans[Cur.CU].push_back(Span);
  1357. }
  1358. continue;
  1359. }
  1360. // Sort the symbols by offset within the section.
  1361. std::sort(
  1362. List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
  1363. unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
  1364. unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
  1365. // Symbols with no order assigned should be placed at the end.
  1366. // (e.g. section end labels)
  1367. if (IA == 0)
  1368. return false;
  1369. if (IB == 0)
  1370. return true;
  1371. return IA < IB;
  1372. });
  1373. // Insert a final terminator.
  1374. List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
  1375. // Build spans between each label.
  1376. const MCSymbol *StartSym = List[0].Sym;
  1377. for (size_t n = 1, e = List.size(); n < e; n++) {
  1378. const SymbolCU &Prev = List[n - 1];
  1379. const SymbolCU &Cur = List[n];
  1380. // Try and build the longest span we can within the same CU.
  1381. if (Cur.CU != Prev.CU) {
  1382. ArangeSpan Span;
  1383. Span.Start = StartSym;
  1384. Span.End = Cur.Sym;
  1385. assert(Prev.CU);
  1386. Spans[Prev.CU].push_back(Span);
  1387. StartSym = Cur.Sym;
  1388. }
  1389. }
  1390. }
  1391. // Start the dwarf aranges section.
  1392. Asm->OutStreamer->SwitchSection(
  1393. Asm->getObjFileLowering().getDwarfARangesSection());
  1394. unsigned PtrSize = Asm->getDataLayout().getPointerSize();
  1395. // Build a list of CUs used.
  1396. std::vector<DwarfCompileUnit *> CUs;
  1397. for (const auto &it : Spans) {
  1398. DwarfCompileUnit *CU = it.first;
  1399. CUs.push_back(CU);
  1400. }
  1401. // Sort the CU list (again, to ensure consistent output order).
  1402. std::sort(CUs.begin(), CUs.end(),
  1403. [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
  1404. return A->getUniqueID() < B->getUniqueID();
  1405. });
  1406. // Emit an arange table for each CU we used.
  1407. for (DwarfCompileUnit *CU : CUs) {
  1408. std::vector<ArangeSpan> &List = Spans[CU];
  1409. // Describe the skeleton CU's offset and length, not the dwo file's.
  1410. if (auto *Skel = CU->getSkeleton())
  1411. CU = Skel;
  1412. // Emit size of content not including length itself.
  1413. unsigned ContentSize =
  1414. sizeof(int16_t) + // DWARF ARange version number
  1415. sizeof(int32_t) + // Offset of CU in the .debug_info section
  1416. sizeof(int8_t) + // Pointer Size (in bytes)
  1417. sizeof(int8_t); // Segment Size (in bytes)
  1418. unsigned TupleSize = PtrSize * 2;
  1419. // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
  1420. unsigned Padding =
  1421. OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
  1422. ContentSize += Padding;
  1423. ContentSize += (List.size() + 1) * TupleSize;
  1424. // For each compile unit, write the list of spans it covers.
  1425. Asm->OutStreamer->AddComment("Length of ARange Set");
  1426. Asm->EmitInt32(ContentSize);
  1427. Asm->OutStreamer->AddComment("DWARF Arange version number");
  1428. Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
  1429. Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
  1430. Asm->emitDwarfSymbolReference(CU->getLabelBegin());
  1431. Asm->OutStreamer->AddComment("Address Size (in bytes)");
  1432. Asm->EmitInt8(PtrSize);
  1433. Asm->OutStreamer->AddComment("Segment Size (in bytes)");
  1434. Asm->EmitInt8(0);
  1435. Asm->OutStreamer->emitFill(Padding, 0xff);
  1436. for (const ArangeSpan &Span : List) {
  1437. Asm->EmitLabelReference(Span.Start, PtrSize);
  1438. // Calculate the size as being from the span start to it's end.
  1439. if (Span.End) {
  1440. Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
  1441. } else {
  1442. // For symbols without an end marker (e.g. common), we
  1443. // write a single arange entry containing just that one symbol.
  1444. uint64_t Size = SymSize[Span.Start];
  1445. if (Size == 0)
  1446. Size = 1;
  1447. Asm->OutStreamer->EmitIntValue(Size, PtrSize);
  1448. }
  1449. }
  1450. Asm->OutStreamer->AddComment("ARange terminator");
  1451. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1452. Asm->OutStreamer->EmitIntValue(0, PtrSize);
  1453. }
  1454. }
  1455. /// Emit address ranges into a debug ranges section.
  1456. void DwarfDebug::emitDebugRanges() {
  1457. // Start the dwarf ranges section.
  1458. Asm->OutStreamer->SwitchSection(
  1459. Asm->getObjFileLowering().getDwarfRangesSection());
  1460. // Size for our labels.
  1461. unsigned char Size = Asm->getDataLayout().getPointerSize();
  1462. // Grab the specific ranges for the compile units in the module.
  1463. for (const auto &I : CUMap) {
  1464. DwarfCompileUnit *TheCU = I.second;
  1465. if (auto *Skel = TheCU->getSkeleton())
  1466. TheCU = Skel;
  1467. // Iterate over the misc ranges for the compile units in the module.
  1468. for (const RangeSpanList &List : TheCU->getRangeLists()) {
  1469. // Emit our symbol so we can find the beginning of the range.
  1470. Asm->OutStreamer->EmitLabel(List.getSym());
  1471. for (const RangeSpan &Range : List.getRanges()) {
  1472. const MCSymbol *Begin = Range.getStart();
  1473. const MCSymbol *End = Range.getEnd();
  1474. assert(Begin && "Range without a begin symbol?");
  1475. assert(End && "Range without an end symbol?");
  1476. if (auto *Base = TheCU->getBaseAddress()) {
  1477. Asm->EmitLabelDifference(Begin, Base, Size);
  1478. Asm->EmitLabelDifference(End, Base, Size);
  1479. } else {
  1480. Asm->OutStreamer->EmitSymbolValue(Begin, Size);
  1481. Asm->OutStreamer->EmitSymbolValue(End, Size);
  1482. }
  1483. }
  1484. // And terminate the list with two 0 values.
  1485. Asm->OutStreamer->EmitIntValue(0, Size);
  1486. Asm->OutStreamer->EmitIntValue(0, Size);
  1487. }
  1488. }
  1489. }
  1490. void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
  1491. for (auto *MN : Nodes) {
  1492. if (auto *M = dyn_cast<DIMacro>(MN))
  1493. emitMacro(*M);
  1494. else if (auto *F = dyn_cast<DIMacroFile>(MN))
  1495. emitMacroFile(*F, U);
  1496. else
  1497. llvm_unreachable("Unexpected DI type!");
  1498. }
  1499. }
  1500. void DwarfDebug::emitMacro(DIMacro &M) {
  1501. Asm->EmitULEB128(M.getMacinfoType());
  1502. Asm->EmitULEB128(M.getLine());
  1503. StringRef Name = M.getName();
  1504. StringRef Value = M.getValue();
  1505. Asm->OutStreamer->EmitBytes(Name);
  1506. if (!Value.empty()) {
  1507. // There should be one space between macro name and macro value.
  1508. Asm->EmitInt8(' ');
  1509. Asm->OutStreamer->EmitBytes(Value);
  1510. }
  1511. Asm->EmitInt8('\0');
  1512. }
  1513. void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
  1514. assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
  1515. Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
  1516. Asm->EmitULEB128(F.getLine());
  1517. DIFile *File = F.getFile();
  1518. unsigned FID =
  1519. U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
  1520. Asm->EmitULEB128(FID);
  1521. handleMacroNodes(F.getElements(), U);
  1522. Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
  1523. }
  1524. /// Emit macros into a debug macinfo section.
  1525. void DwarfDebug::emitDebugMacinfo() {
  1526. // Start the dwarf macinfo section.
  1527. Asm->OutStreamer->SwitchSection(
  1528. Asm->getObjFileLowering().getDwarfMacinfoSection());
  1529. for (const auto &P : CUMap) {
  1530. auto &TheCU = *P.second;
  1531. auto *SkCU = TheCU.getSkeleton();
  1532. DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
  1533. auto *CUNode = cast<DICompileUnit>(P.first);
  1534. Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
  1535. handleMacroNodes(CUNode->getMacros(), U);
  1536. }
  1537. Asm->OutStreamer->AddComment("End Of Macro List Mark");
  1538. Asm->EmitInt8(0);
  1539. }
  1540. // DWARF5 Experimental Separate Dwarf emitters.
  1541. void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
  1542. std::unique_ptr<DwarfCompileUnit> NewU) {
  1543. NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
  1544. U.getCUNode()->getSplitDebugFilename());
  1545. if (!CompilationDir.empty())
  1546. NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
  1547. addGnuPubAttributes(*NewU, Die);
  1548. SkeletonHolder.addUnit(std::move(NewU));
  1549. }
  1550. // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
  1551. // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
  1552. // DW_AT_addr_base, DW_AT_ranges_base.
  1553. DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
  1554. auto OwnedUnit = make_unique<DwarfCompileUnit>(
  1555. CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
  1556. DwarfCompileUnit &NewCU = *OwnedUnit;
  1557. NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
  1558. NewCU.initStmtList();
  1559. initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
  1560. return NewCU;
  1561. }
  1562. // Emit the .debug_info.dwo section for separated dwarf. This contains the
  1563. // compile units that would normally be in debug_info.
  1564. void DwarfDebug::emitDebugInfoDWO() {
  1565. assert(useSplitDwarf() && "No split dwarf debug info?");
  1566. // Don't emit relocations into the dwo file.
  1567. InfoHolder.emitUnits(/* UseOffsets */ true);
  1568. }
  1569. // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
  1570. // abbreviations for the .debug_info.dwo section.
  1571. void DwarfDebug::emitDebugAbbrevDWO() {
  1572. assert(useSplitDwarf() && "No split dwarf?");
  1573. InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
  1574. }
  1575. void DwarfDebug::emitDebugLineDWO() {
  1576. assert(useSplitDwarf() && "No split dwarf?");
  1577. Asm->OutStreamer->SwitchSection(
  1578. Asm->getObjFileLowering().getDwarfLineDWOSection());
  1579. SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
  1580. }
  1581. // Emit the .debug_str.dwo section for separated dwarf. This contains the
  1582. // string section and is identical in format to traditional .debug_str
  1583. // sections.
  1584. void DwarfDebug::emitDebugStrDWO() {
  1585. assert(useSplitDwarf() && "No split dwarf?");
  1586. MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
  1587. InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
  1588. OffSec);
  1589. }
  1590. MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
  1591. if (!useSplitDwarf())
  1592. return nullptr;
  1593. if (SingleCU)
  1594. SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
  1595. return &SplitTypeUnitFileTable;
  1596. }
  1597. uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
  1598. MD5 Hash;
  1599. Hash.update(Identifier);
  1600. // ... take the least significant 8 bytes and return those. Our MD5
  1601. // implementation always returns its results in little endian, swap bytes
  1602. // appropriately.
  1603. MD5::MD5Result Result;
  1604. Hash.final(Result);
  1605. return support::endian::read64le(Result + 8);
  1606. }
  1607. void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
  1608. StringRef Identifier, DIE &RefDie,
  1609. const DICompositeType *CTy) {
  1610. // Fast path if we're building some type units and one has already used the
  1611. // address pool we know we're going to throw away all this work anyway, so
  1612. // don't bother building dependent types.
  1613. if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
  1614. return;
  1615. auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
  1616. if (!Ins.second) {
  1617. CU.addDIETypeSignature(RefDie, Ins.first->second);
  1618. return;
  1619. }
  1620. bool TopLevelType = TypeUnitsUnderConstruction.empty();
  1621. AddrPool.resetUsedFlag();
  1622. auto OwnedUnit = make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
  1623. getDwoLineTable(CU));
  1624. DwarfTypeUnit &NewTU = *OwnedUnit;
  1625. DIE &UnitDie = NewTU.getUnitDie();
  1626. TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
  1627. NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
  1628. CU.getLanguage());
  1629. uint64_t Signature = makeTypeSignature(Identifier);
  1630. NewTU.setTypeSignature(Signature);
  1631. Ins.first->second = Signature;
  1632. if (useSplitDwarf())
  1633. NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
  1634. else {
  1635. CU.applyStmtList(UnitDie);
  1636. NewTU.initSection(
  1637. Asm->getObjFileLowering().getDwarfTypesSection(Signature));
  1638. }
  1639. NewTU.setType(NewTU.createTypeDIE(CTy));
  1640. if (TopLevelType) {
  1641. auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
  1642. TypeUnitsUnderConstruction.clear();
  1643. // Types referencing entries in the address table cannot be placed in type
  1644. // units.
  1645. if (AddrPool.hasBeenUsed()) {
  1646. // Remove all the types built while building this type.
  1647. // This is pessimistic as some of these types might not be dependent on
  1648. // the type that used an address.
  1649. for (const auto &TU : TypeUnitsToAdd)
  1650. TypeSignatures.erase(TU.second);
  1651. // Construct this type in the CU directly.
  1652. // This is inefficient because all the dependent types will be rebuilt
  1653. // from scratch, including building them in type units, discovering that
  1654. // they depend on addresses, throwing them out and rebuilding them.
  1655. CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
  1656. return;
  1657. }
  1658. // If the type wasn't dependent on fission addresses, finish adding the type
  1659. // and all its dependent types.
  1660. for (auto &TU : TypeUnitsToAdd) {
  1661. InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
  1662. InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
  1663. }
  1664. }
  1665. CU.addDIETypeSignature(RefDie, Signature);
  1666. }
  1667. // Accelerator table mutators - add each name along with its companion
  1668. // DIE to the proper table while ensuring that the name that we're going
  1669. // to reference is in the string table. We do this since the names we
  1670. // add may not only be identical to the names in the DIE.
  1671. void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
  1672. if (!useDwarfAccelTables())
  1673. return;
  1674. AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1675. }
  1676. void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
  1677. if (!useDwarfAccelTables())
  1678. return;
  1679. AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1680. }
  1681. void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
  1682. if (!useDwarfAccelTables())
  1683. return;
  1684. AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1685. }
  1686. void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
  1687. if (!useDwarfAccelTables())
  1688. return;
  1689. AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
  1690. }