DwarfDebug.cpp 71 KB

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