DwarfCompileUnit.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains support for constructing a dwarf compile unit.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "DwarfCompileUnit.h"
  13. #include "AddressPool.h"
  14. #include "DwarfDebug.h"
  15. #include "DwarfExpression.h"
  16. #include "DwarfUnit.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/BinaryFormat/Dwarf.h"
  23. #include "llvm/CodeGen/AsmPrinter.h"
  24. #include "llvm/CodeGen/DIE.h"
  25. #include "llvm/CodeGen/LexicalScopes.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/TargetFrameLowering.h"
  30. #include "llvm/CodeGen/TargetRegisterInfo.h"
  31. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/DebugInfo.h"
  34. #include "llvm/IR/DebugInfoMetadata.h"
  35. #include "llvm/IR/GlobalVariable.h"
  36. #include "llvm/MC/MCSection.h"
  37. #include "llvm/MC/MCStreamer.h"
  38. #include "llvm/MC/MCSymbol.h"
  39. #include "llvm/MC/MachineLocation.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Target/TargetLoweringObjectFile.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Target/TargetOptions.h"
  44. #include <algorithm>
  45. #include <cassert>
  46. #include <cstdint>
  47. #include <iterator>
  48. #include <memory>
  49. #include <string>
  50. #include <utility>
  51. using namespace llvm;
  52. DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
  53. AsmPrinter *A, DwarfDebug *DW,
  54. DwarfFile *DWU)
  55. : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) {
  56. insertDIE(Node, &getUnitDie());
  57. MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
  58. }
  59. /// addLabelAddress - Add a dwarf label attribute data and value using
  60. /// DW_FORM_addr or DW_FORM_GNU_addr_index.
  61. void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
  62. const MCSymbol *Label) {
  63. // Don't use the address pool in non-fission or in the skeleton unit itself.
  64. // FIXME: Once GDB supports this, it's probably worthwhile using the address
  65. // pool from the skeleton - maybe even in non-fission (possibly fewer
  66. // relocations by sharing them in the pool, but we have other ideas about how
  67. // to reduce the number of relocations as well/instead).
  68. if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
  69. return addLocalLabelAddress(Die, Attribute, Label);
  70. if (Label)
  71. DD->addArangeLabel(SymbolCU(this, Label));
  72. unsigned idx = DD->getAddressPool().getIndex(Label);
  73. Die.addValue(DIEValueAllocator, Attribute,
  74. DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
  75. : dwarf::DW_FORM_GNU_addr_index,
  76. DIEInteger(idx));
  77. }
  78. void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
  79. dwarf::Attribute Attribute,
  80. const MCSymbol *Label) {
  81. if (Label)
  82. DD->addArangeLabel(SymbolCU(this, Label));
  83. if (Label)
  84. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  85. DIELabel(Label));
  86. else
  87. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  88. DIEInteger(0));
  89. }
  90. unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
  91. // If we print assembly, we can't separate .file entries according to
  92. // compile units. Thus all files will belong to the default compile unit.
  93. // FIXME: add a better feature test than hasRawTextSupport. Even better,
  94. // extend .file to support this.
  95. unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
  96. if (!File)
  97. return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", None, None, CUID);
  98. return Asm->OutStreamer->EmitDwarfFileDirective(
  99. 0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
  100. File->getSource(), CUID);
  101. }
  102. DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
  103. const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
  104. // Check for pre-existence.
  105. if (DIE *Die = getDIE(GV))
  106. return Die;
  107. assert(GV);
  108. auto *GVContext = GV->getScope();
  109. const DIType *GTy = GV->getType();
  110. // Construct the context before querying for the existence of the DIE in
  111. // case such construction creates the DIE.
  112. auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
  113. DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
  114. : getOrCreateContextDIE(GVContext);
  115. // Add to map.
  116. DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
  117. DIScope *DeclContext;
  118. if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
  119. DeclContext = SDMDecl->getScope();
  120. assert(SDMDecl->isStaticMember() && "Expected static member decl");
  121. assert(GV->isDefinition());
  122. // We need the declaration DIE that is in the static member's class.
  123. DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
  124. addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
  125. // If the global variable's type is different from the one in the class
  126. // member type, assume that it's more specific and also emit it.
  127. if (GTy != SDMDecl->getBaseType())
  128. addType(*VariableDIE, GTy);
  129. } else {
  130. DeclContext = GV->getScope();
  131. // Add name and type.
  132. addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
  133. addType(*VariableDIE, GTy);
  134. // Add scoping info.
  135. if (!GV->isLocalToUnit())
  136. addFlag(*VariableDIE, dwarf::DW_AT_external);
  137. // Add line number info.
  138. addSourceLine(*VariableDIE, GV);
  139. }
  140. if (!GV->isDefinition())
  141. addFlag(*VariableDIE, dwarf::DW_AT_declaration);
  142. else
  143. addGlobalName(GV->getName(), *VariableDIE, DeclContext);
  144. if (uint32_t AlignInBytes = GV->getAlignInBytes())
  145. addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  146. AlignInBytes);
  147. if (MDTuple *TP = GV->getTemplateParams())
  148. addTemplateParams(*VariableDIE, DINodeArray(TP));
  149. // Add location.
  150. addLocationAttribute(VariableDIE, GV, GlobalExprs);
  151. return VariableDIE;
  152. }
  153. void DwarfCompileUnit::addLocationAttribute(
  154. DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
  155. bool addToAccelTable = false;
  156. DIELoc *Loc = nullptr;
  157. Optional<unsigned> NVPTXAddressSpace;
  158. std::unique_ptr<DIEDwarfExpression> DwarfExpr;
  159. for (const auto &GE : GlobalExprs) {
  160. const GlobalVariable *Global = GE.Var;
  161. const DIExpression *Expr = GE.Expr;
  162. // For compatibility with DWARF 3 and earlier,
  163. // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
  164. // DW_AT_const_value(X).
  165. if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
  166. addToAccelTable = true;
  167. addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
  168. break;
  169. }
  170. // We cannot describe the location of dllimport'd variables: the
  171. // computation of their address requires loads from the IAT.
  172. if (Global && Global->hasDLLImportStorageClass())
  173. continue;
  174. // Nothing to describe without address or constant.
  175. if (!Global && (!Expr || !Expr->isConstant()))
  176. continue;
  177. if (Global && Global->isThreadLocal() &&
  178. !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
  179. continue;
  180. if (!Loc) {
  181. addToAccelTable = true;
  182. Loc = new (DIEValueAllocator) DIELoc;
  183. DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
  184. }
  185. if (Expr) {
  186. // According to
  187. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  188. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  189. // correctly interpret address space of the variable address.
  190. // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  191. // sequence for the NVPTX + gdb target.
  192. unsigned LocalNVPTXAddressSpace;
  193. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  194. const DIExpression *NewExpr =
  195. DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
  196. if (NewExpr != Expr) {
  197. Expr = NewExpr;
  198. NVPTXAddressSpace = LocalNVPTXAddressSpace;
  199. }
  200. }
  201. DwarfExpr->addFragmentOffset(Expr);
  202. }
  203. if (Global) {
  204. const MCSymbol *Sym = Asm->getSymbol(Global);
  205. if (Global->isThreadLocal()) {
  206. if (Asm->TM.useEmulatedTLS()) {
  207. // TODO: add debug info for emulated thread local mode.
  208. } else {
  209. // FIXME: Make this work with -gsplit-dwarf.
  210. unsigned PointerSize = Asm->getDataLayout().getPointerSize();
  211. assert((PointerSize == 4 || PointerSize == 8) &&
  212. "Add support for other sizes if necessary");
  213. // Based on GCC's support for TLS:
  214. if (!DD->useSplitDwarf()) {
  215. // 1) Start with a constNu of the appropriate pointer size
  216. addUInt(*Loc, dwarf::DW_FORM_data1,
  217. PointerSize == 4 ? dwarf::DW_OP_const4u
  218. : dwarf::DW_OP_const8u);
  219. // 2) containing the (relocated) offset of the TLS variable
  220. // within the module's TLS block.
  221. addExpr(*Loc, dwarf::DW_FORM_udata,
  222. Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
  223. } else {
  224. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
  225. addUInt(*Loc, dwarf::DW_FORM_udata,
  226. DD->getAddressPool().getIndex(Sym, /* TLS */ true));
  227. }
  228. // 3) followed by an OP to make the debugger do a TLS lookup.
  229. addUInt(*Loc, dwarf::DW_FORM_data1,
  230. DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
  231. : dwarf::DW_OP_form_tls_address);
  232. }
  233. } else {
  234. DD->addArangeLabel(SymbolCU(this, Sym));
  235. addOpAddress(*Loc, Sym);
  236. }
  237. }
  238. // Global variables attached to symbols are memory locations.
  239. // It would be better if this were unconditional, but malformed input that
  240. // mixes non-fragments and fragments for the same variable is too expensive
  241. // to detect in the verifier.
  242. if (DwarfExpr->isUnknownLocation())
  243. DwarfExpr->setMemoryLocationKind();
  244. DwarfExpr->addExpression(Expr);
  245. }
  246. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  247. // According to
  248. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  249. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  250. // correctly interpret address space of the variable address.
  251. const unsigned NVPTX_ADDR_global_space = 5;
  252. addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
  253. NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
  254. }
  255. if (Loc)
  256. addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
  257. if (DD->useAllLinkageNames())
  258. addLinkageName(*VariableDIE, GV->getLinkageName());
  259. if (addToAccelTable) {
  260. DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
  261. // If the linkage name is different than the name, go ahead and output
  262. // that as well into the name table.
  263. if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
  264. DD->useAllLinkageNames())
  265. DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
  266. }
  267. }
  268. DIE *DwarfCompileUnit::getOrCreateCommonBlock(
  269. const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
  270. // Construct the context before querying for the existence of the DIE in case
  271. // such construction creates the DIE.
  272. DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
  273. if (DIE *NDie = getDIE(CB))
  274. return NDie;
  275. DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
  276. StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
  277. addString(NDie, dwarf::DW_AT_name, Name);
  278. addGlobalName(Name, NDie, CB->getScope());
  279. if (CB->getFile())
  280. addSourceLine(NDie, CB->getLineNo(), CB->getFile());
  281. if (DIGlobalVariable *V = CB->getDecl())
  282. getCU().addLocationAttribute(&NDie, V, GlobalExprs);
  283. return &NDie;
  284. }
  285. void DwarfCompileUnit::addRange(RangeSpan Range) {
  286. bool SameAsPrevCU = this == DD->getPrevCU();
  287. DD->setPrevCU(this);
  288. // If we have no current ranges just add the range and return, otherwise,
  289. // check the current section and CU against the previous section and CU we
  290. // emitted into and the subprogram was contained within. If these are the
  291. // same then extend our current range, otherwise add this as a new range.
  292. if (CURanges.empty() || !SameAsPrevCU ||
  293. (&CURanges.back().getEnd()->getSection() !=
  294. &Range.getEnd()->getSection())) {
  295. CURanges.push_back(Range);
  296. DD->addSectionLabel(Range.getStart());
  297. return;
  298. }
  299. CURanges.back().setEnd(Range.getEnd());
  300. }
  301. void DwarfCompileUnit::initStmtList() {
  302. if (CUNode->isDebugDirectivesOnly())
  303. return;
  304. // Define start line table label for each Compile Unit.
  305. MCSymbol *LineTableStartSym;
  306. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  307. if (DD->useSectionsAsReferences()) {
  308. LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
  309. } else {
  310. LineTableStartSym =
  311. Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
  312. }
  313. // DW_AT_stmt_list is a offset of line number information for this
  314. // compile unit in debug_line section. For split dwarf this is
  315. // left in the skeleton CU and so not included.
  316. // The line table entries are not always emitted in assembly, so it
  317. // is not okay to use line_table_start here.
  318. StmtListValue =
  319. addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
  320. TLOF.getDwarfLineSection()->getBeginSymbol());
  321. }
  322. void DwarfCompileUnit::applyStmtList(DIE &D) {
  323. D.addValue(DIEValueAllocator, *StmtListValue);
  324. }
  325. void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
  326. const MCSymbol *End) {
  327. assert(Begin && "Begin label should not be null!");
  328. assert(End && "End label should not be null!");
  329. assert(Begin->isDefined() && "Invalid starting label");
  330. assert(End->isDefined() && "Invalid end label");
  331. addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
  332. if (DD->getDwarfVersion() < 4)
  333. addLabelAddress(D, dwarf::DW_AT_high_pc, End);
  334. else
  335. addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
  336. }
  337. // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
  338. // and DW_AT_high_pc attributes. If there are global variables in this
  339. // scope then create and insert DIEs for these variables.
  340. DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
  341. DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
  342. attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
  343. if (DD->useAppleExtensionAttributes() &&
  344. !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
  345. *DD->getCurrentFunction()))
  346. addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
  347. // Only include DW_AT_frame_base in full debug info
  348. if (!includeMinimalInlineScopes()) {
  349. if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
  350. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  351. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
  352. addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
  353. } else {
  354. const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
  355. MachineLocation Location(RI->getFrameRegister(*Asm->MF));
  356. if (Register::isPhysicalRegister(Location.getReg()))
  357. addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
  358. }
  359. }
  360. // Add name to the name table, we do this here because we're guaranteed
  361. // to have concrete versions of our DW_TAG_subprogram nodes.
  362. DD->addSubprogramNames(*CUNode, SP, *SPDie);
  363. return *SPDie;
  364. }
  365. // Construct a DIE for this scope.
  366. void DwarfCompileUnit::constructScopeDIE(
  367. LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
  368. if (!Scope || !Scope->getScopeNode())
  369. return;
  370. auto *DS = Scope->getScopeNode();
  371. assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
  372. "Only handle inlined subprograms here, use "
  373. "constructSubprogramScopeDIE for non-inlined "
  374. "subprograms");
  375. SmallVector<DIE *, 8> Children;
  376. // We try to create the scope DIE first, then the children DIEs. This will
  377. // avoid creating un-used children then removing them later when we find out
  378. // the scope DIE is null.
  379. DIE *ScopeDIE;
  380. if (Scope->getParent() && isa<DISubprogram>(DS)) {
  381. ScopeDIE = constructInlinedScopeDIE(Scope);
  382. if (!ScopeDIE)
  383. return;
  384. // We create children when the scope DIE is not null.
  385. createScopeChildrenDIE(Scope, Children);
  386. } else {
  387. // Early exit when we know the scope DIE is going to be null.
  388. if (DD->isLexicalScopeDIENull(Scope))
  389. return;
  390. bool HasNonScopeChildren = false;
  391. // We create children here when we know the scope DIE is not going to be
  392. // null and the children will be added to the scope DIE.
  393. createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
  394. // If there are only other scopes as children, put them directly in the
  395. // parent instead, as this scope would serve no purpose.
  396. if (!HasNonScopeChildren) {
  397. FinalChildren.insert(FinalChildren.end(),
  398. std::make_move_iterator(Children.begin()),
  399. std::make_move_iterator(Children.end()));
  400. return;
  401. }
  402. ScopeDIE = constructLexicalScopeDIE(Scope);
  403. assert(ScopeDIE && "Scope DIE should not be null.");
  404. }
  405. // Add children
  406. for (auto &I : Children)
  407. ScopeDIE->addChild(std::move(I));
  408. FinalChildren.push_back(std::move(ScopeDIE));
  409. }
  410. void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
  411. SmallVector<RangeSpan, 2> Range) {
  412. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  413. // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
  414. // label. emitDIE() will handle emitting it appropriately.
  415. const MCSymbol *RangeSectionSym =
  416. DD->getDwarfVersion() >= 5
  417. ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
  418. : TLOF.getDwarfRangesSection()->getBeginSymbol();
  419. HasRangeLists = true;
  420. // Add the range list to the set of ranges to be emitted.
  421. auto IndexAndList =
  422. (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
  423. ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
  424. uint32_t Index = IndexAndList.first;
  425. auto &List = *IndexAndList.second;
  426. // Under fission, ranges are specified by constant offsets relative to the
  427. // CU's DW_AT_GNU_ranges_base.
  428. // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
  429. // fission until we support the forms using the .debug_addr section
  430. // (DW_RLE_startx_endx etc.).
  431. if (DD->getDwarfVersion() >= 5)
  432. addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
  433. else if (isDwoUnit())
  434. addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  435. RangeSectionSym);
  436. else
  437. addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  438. RangeSectionSym);
  439. }
  440. void DwarfCompileUnit::attachRangesOrLowHighPC(
  441. DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
  442. if (Ranges.size() == 1 || !DD->useRangesSection()) {
  443. const RangeSpan &Front = Ranges.front();
  444. const RangeSpan &Back = Ranges.back();
  445. attachLowHighPC(Die, Front.getStart(), Back.getEnd());
  446. } else
  447. addScopeRangeList(Die, std::move(Ranges));
  448. }
  449. void DwarfCompileUnit::attachRangesOrLowHighPC(
  450. DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
  451. SmallVector<RangeSpan, 2> List;
  452. List.reserve(Ranges.size());
  453. for (const InsnRange &R : Ranges)
  454. List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
  455. DD->getLabelAfterInsn(R.second)));
  456. attachRangesOrLowHighPC(Die, std::move(List));
  457. }
  458. // This scope represents inlined body of a function. Construct DIE to
  459. // represent this concrete inlined copy of the function.
  460. DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
  461. assert(Scope->getScopeNode());
  462. auto *DS = Scope->getScopeNode();
  463. auto *InlinedSP = getDISubprogram(DS);
  464. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  465. // was inlined from another compile unit.
  466. DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
  467. assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
  468. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
  469. addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
  470. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  471. // Add the call site information to the DIE.
  472. const DILocation *IA = Scope->getInlinedAt();
  473. addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
  474. getOrCreateSourceID(IA->getFile()));
  475. addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
  476. if (IA->getColumn())
  477. addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
  478. if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
  479. addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
  480. IA->getDiscriminator());
  481. // Add name to the name table, we do this here because we're guaranteed
  482. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  483. DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
  484. return ScopeDIE;
  485. }
  486. // Construct new DW_TAG_lexical_block for this scope and attach
  487. // DW_AT_low_pc/DW_AT_high_pc labels.
  488. DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
  489. if (DD->isLexicalScopeDIENull(Scope))
  490. return nullptr;
  491. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
  492. if (Scope->isAbstractScope())
  493. return ScopeDIE;
  494. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  495. return ScopeDIE;
  496. }
  497. /// constructVariableDIE - Construct a DIE for the given DbgVariable.
  498. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
  499. auto D = constructVariableDIEImpl(DV, Abstract);
  500. DV.setDIE(*D);
  501. return D;
  502. }
  503. DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
  504. const LexicalScope &Scope) {
  505. auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
  506. insertDIE(DL.getLabel(), LabelDie);
  507. DL.setDIE(*LabelDie);
  508. if (Scope.isAbstractScope())
  509. applyLabelAttributes(DL, *LabelDie);
  510. return LabelDie;
  511. }
  512. DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
  513. bool Abstract) {
  514. // Define variable debug information entry.
  515. auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
  516. insertDIE(DV.getVariable(), VariableDie);
  517. if (Abstract) {
  518. applyVariableAttributes(DV, *VariableDie);
  519. return VariableDie;
  520. }
  521. // Add variable address.
  522. unsigned Offset = DV.getDebugLocListIndex();
  523. if (Offset != ~0U) {
  524. addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
  525. return VariableDie;
  526. }
  527. // Check if variable has a single location description.
  528. if (auto *DVal = DV.getValueLoc()) {
  529. if (DVal->isLocation())
  530. addVariableAddress(DV, *VariableDie, DVal->getLoc());
  531. else if (DVal->isInt()) {
  532. auto *Expr = DV.getSingleExpression();
  533. if (Expr && Expr->getNumElements()) {
  534. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  535. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  536. // If there is an expression, emit raw unsigned bytes.
  537. DwarfExpr.addFragmentOffset(Expr);
  538. DwarfExpr.addUnsignedConstant(DVal->getInt());
  539. DwarfExpr.addExpression(Expr);
  540. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  541. } else
  542. addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
  543. } else if (DVal->isConstantFP()) {
  544. addConstantFPValue(*VariableDie, DVal->getConstantFP());
  545. } else if (DVal->isConstantInt()) {
  546. addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
  547. }
  548. return VariableDie;
  549. }
  550. // .. else use frame index.
  551. if (!DV.hasFrameIndexExprs())
  552. return VariableDie;
  553. Optional<unsigned> NVPTXAddressSpace;
  554. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  555. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  556. for (auto &Fragment : DV.getFrameIndexExprs()) {
  557. unsigned FrameReg = 0;
  558. const DIExpression *Expr = Fragment.Expr;
  559. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  560. int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
  561. DwarfExpr.addFragmentOffset(Expr);
  562. SmallVector<uint64_t, 8> Ops;
  563. DIExpression::appendOffset(Ops, Offset);
  564. // According to
  565. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  566. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  567. // correctly interpret address space of the variable address.
  568. // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  569. // sequence for the NVPTX + gdb target.
  570. unsigned LocalNVPTXAddressSpace;
  571. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  572. const DIExpression *NewExpr =
  573. DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
  574. if (NewExpr != Expr) {
  575. Expr = NewExpr;
  576. NVPTXAddressSpace = LocalNVPTXAddressSpace;
  577. }
  578. }
  579. if (Expr)
  580. Ops.append(Expr->elements_begin(), Expr->elements_end());
  581. DIExpressionCursor Cursor(Ops);
  582. DwarfExpr.setMemoryLocationKind();
  583. if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
  584. addOpAddress(*Loc, FrameSymbol);
  585. else
  586. DwarfExpr.addMachineRegExpression(
  587. *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
  588. DwarfExpr.addExpression(std::move(Cursor));
  589. }
  590. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  591. // According to
  592. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  593. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  594. // correctly interpret address space of the variable address.
  595. const unsigned NVPTX_ADDR_local_space = 6;
  596. addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
  597. NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
  598. }
  599. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  600. if (DwarfExpr.TagOffset)
  601. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  602. *DwarfExpr.TagOffset);
  603. return VariableDie;
  604. }
  605. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
  606. const LexicalScope &Scope,
  607. DIE *&ObjectPointer) {
  608. auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
  609. if (DV.isObjectPointer())
  610. ObjectPointer = Var;
  611. return Var;
  612. }
  613. /// Return all DIVariables that appear in count: expressions.
  614. static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
  615. SmallVector<const DIVariable *, 2> Result;
  616. auto *Array = dyn_cast<DICompositeType>(Var->getType());
  617. if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
  618. return Result;
  619. for (auto *El : Array->getElements()) {
  620. if (auto *Subrange = dyn_cast<DISubrange>(El)) {
  621. auto Count = Subrange->getCount();
  622. if (auto *Dependency = Count.dyn_cast<DIVariable *>())
  623. Result.push_back(Dependency);
  624. }
  625. }
  626. return Result;
  627. }
  628. /// Sort local variables so that variables appearing inside of helper
  629. /// expressions come first.
  630. static SmallVector<DbgVariable *, 8>
  631. sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
  632. SmallVector<DbgVariable *, 8> Result;
  633. SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
  634. // Map back from a DIVariable to its containing DbgVariable.
  635. SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
  636. // Set of DbgVariables in Result.
  637. SmallDenseSet<DbgVariable *, 8> Visited;
  638. // For cycle detection.
  639. SmallDenseSet<DbgVariable *, 8> Visiting;
  640. // Initialize the worklist and the DIVariable lookup table.
  641. for (auto Var : reverse(Input)) {
  642. DbgVar.insert({Var->getVariable(), Var});
  643. WorkList.push_back({Var, 0});
  644. }
  645. // Perform a stable topological sort by doing a DFS.
  646. while (!WorkList.empty()) {
  647. auto Item = WorkList.back();
  648. DbgVariable *Var = Item.getPointer();
  649. bool visitedAllDependencies = Item.getInt();
  650. WorkList.pop_back();
  651. // Dependency is in a different lexical scope or a global.
  652. if (!Var)
  653. continue;
  654. // Already handled.
  655. if (Visited.count(Var))
  656. continue;
  657. // Add to Result if all dependencies are visited.
  658. if (visitedAllDependencies) {
  659. Visited.insert(Var);
  660. Result.push_back(Var);
  661. continue;
  662. }
  663. // Detect cycles.
  664. auto Res = Visiting.insert(Var);
  665. if (!Res.second) {
  666. assert(false && "dependency cycle in local variables");
  667. return Result;
  668. }
  669. // Push dependencies and this node onto the worklist, so that this node is
  670. // visited again after all of its dependencies are handled.
  671. WorkList.push_back({Var, 1});
  672. for (auto *Dependency : dependencies(Var)) {
  673. auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
  674. WorkList.push_back({DbgVar[Dep], 0});
  675. }
  676. }
  677. return Result;
  678. }
  679. DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
  680. SmallVectorImpl<DIE *> &Children,
  681. bool *HasNonScopeChildren) {
  682. assert(Children.empty());
  683. DIE *ObjectPointer = nullptr;
  684. // Emit function arguments (order is significant).
  685. auto Vars = DU->getScopeVariables().lookup(Scope);
  686. for (auto &DV : Vars.Args)
  687. Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
  688. // Emit local variables.
  689. auto Locals = sortLocalVars(Vars.Locals);
  690. for (DbgVariable *DV : Locals)
  691. Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
  692. // Skip imported directives in gmlt-like data.
  693. if (!includeMinimalInlineScopes()) {
  694. // There is no need to emit empty lexical block DIE.
  695. for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
  696. Children.push_back(
  697. constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
  698. }
  699. if (HasNonScopeChildren)
  700. *HasNonScopeChildren = !Children.empty();
  701. for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
  702. Children.push_back(constructLabelDIE(*DL, *Scope));
  703. for (LexicalScope *LS : Scope->getChildren())
  704. constructScopeDIE(LS, Children);
  705. return ObjectPointer;
  706. }
  707. DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
  708. LexicalScope *Scope) {
  709. DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
  710. if (Scope) {
  711. assert(!Scope->getInlinedAt());
  712. assert(!Scope->isAbstractScope());
  713. // Collect lexical scope children first.
  714. // ObjectPointer might be a local (non-argument) local variable if it's a
  715. // block's synthetic this pointer.
  716. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
  717. addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  718. }
  719. // If this is a variadic function, add an unspecified parameter.
  720. DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
  721. // If we have a single element of null, it is a function that returns void.
  722. // If we have more than one elements and the last one is null, it is a
  723. // variadic function.
  724. if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
  725. !includeMinimalInlineScopes())
  726. ScopeDIE.addChild(
  727. DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
  728. return ScopeDIE;
  729. }
  730. DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
  731. DIE &ScopeDIE) {
  732. // We create children when the scope DIE is not null.
  733. SmallVector<DIE *, 8> Children;
  734. DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
  735. // Add children
  736. for (auto &I : Children)
  737. ScopeDIE.addChild(std::move(I));
  738. return ObjectPointer;
  739. }
  740. void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
  741. LexicalScope *Scope) {
  742. DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
  743. if (AbsDef)
  744. return;
  745. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  746. DIE *ContextDIE;
  747. DwarfCompileUnit *ContextCU = this;
  748. if (includeMinimalInlineScopes())
  749. ContextDIE = &getUnitDie();
  750. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  751. // the important distinction that the debug node is not associated with the
  752. // DIE (since the debug node will be associated with the concrete DIE, if
  753. // any). It could be refactored to some common utility function.
  754. else if (auto *SPDecl = SP->getDeclaration()) {
  755. ContextDIE = &getUnitDie();
  756. getOrCreateSubprogramDIE(SPDecl);
  757. } else {
  758. ContextDIE = getOrCreateContextDIE(SP->getScope());
  759. // The scope may be shared with a subprogram that has already been
  760. // constructed in another CU, in which case we need to construct this
  761. // subprogram in the same CU.
  762. ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
  763. }
  764. // Passing null as the associated node because the abstract definition
  765. // shouldn't be found by lookup.
  766. AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
  767. ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
  768. if (!ContextCU->includeMinimalInlineScopes())
  769. ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
  770. if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
  771. ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
  772. }
  773. /// Whether to use the GNU analog for a DWARF5 tag, attribute, or location atom.
  774. static bool useGNUAnalogForDwarf5Feature(DwarfDebug *DD) {
  775. return DD->getDwarfVersion() == 4 && DD->tuneForGDB();
  776. }
  777. dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
  778. if (!useGNUAnalogForDwarf5Feature(DD))
  779. return Tag;
  780. switch (Tag) {
  781. case dwarf::DW_TAG_call_site:
  782. return dwarf::DW_TAG_GNU_call_site;
  783. case dwarf::DW_TAG_call_site_parameter:
  784. return dwarf::DW_TAG_GNU_call_site_parameter;
  785. default:
  786. llvm_unreachable("DWARF5 tag with no GNU analog");
  787. }
  788. }
  789. dwarf::Attribute
  790. DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
  791. if (!useGNUAnalogForDwarf5Feature(DD))
  792. return Attr;
  793. switch (Attr) {
  794. case dwarf::DW_AT_call_all_calls:
  795. return dwarf::DW_AT_GNU_all_call_sites;
  796. case dwarf::DW_AT_call_target:
  797. return dwarf::DW_AT_GNU_call_site_target;
  798. case dwarf::DW_AT_call_origin:
  799. return dwarf::DW_AT_abstract_origin;
  800. case dwarf::DW_AT_call_pc:
  801. return dwarf::DW_AT_low_pc;
  802. case dwarf::DW_AT_call_value:
  803. return dwarf::DW_AT_GNU_call_site_value;
  804. case dwarf::DW_AT_call_tail_call:
  805. return dwarf::DW_AT_GNU_tail_call;
  806. default:
  807. llvm_unreachable("DWARF5 attribute with no GNU analog");
  808. }
  809. }
  810. dwarf::LocationAtom
  811. DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
  812. if (!useGNUAnalogForDwarf5Feature(DD))
  813. return Loc;
  814. switch (Loc) {
  815. case dwarf::DW_OP_entry_value:
  816. return dwarf::DW_OP_GNU_entry_value;
  817. default:
  818. llvm_unreachable("DWARF5 location atom with no GNU analog");
  819. }
  820. }
  821. DIE &DwarfCompileUnit::constructCallSiteEntryDIE(
  822. DIE &ScopeDIE, const DISubprogram *CalleeSP, bool IsTail,
  823. const MCSymbol *PCAddr, const MCExpr *PCOffset, unsigned CallReg) {
  824. // Insert a call site entry DIE within ScopeDIE.
  825. DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
  826. ScopeDIE, nullptr);
  827. if (CallReg) {
  828. // Indirect call.
  829. addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
  830. MachineLocation(CallReg));
  831. } else {
  832. DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
  833. assert(CalleeDIE && "Could not create DIE for call site entry origin");
  834. addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
  835. *CalleeDIE);
  836. }
  837. if (IsTail)
  838. // Attach DW_AT_call_tail_call to tail calls for standards compliance.
  839. addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
  840. // Attach the return PC to allow the debugger to disambiguate call paths
  841. // from one function to another.
  842. if (DD->getDwarfVersion() == 4 && DD->tuneForGDB()) {
  843. assert(PCAddr && "Missing PC information for a call");
  844. addLabelAddress(CallSiteDIE, dwarf::DW_AT_low_pc, PCAddr);
  845. } else if (!IsTail || DD->tuneForGDB()) {
  846. assert(PCOffset && "Missing return PC information for a call");
  847. addAddressExpr(CallSiteDIE, dwarf::DW_AT_call_return_pc, PCOffset);
  848. }
  849. return CallSiteDIE;
  850. }
  851. void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
  852. DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
  853. for (const auto &Param : Params) {
  854. unsigned Register = Param.getRegister();
  855. auto CallSiteDieParam =
  856. DIE::get(DIEValueAllocator,
  857. getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
  858. insertDIE(CallSiteDieParam);
  859. addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
  860. MachineLocation(Register));
  861. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  862. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  863. DwarfExpr.setCallSiteParamValueFlag();
  864. DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
  865. addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
  866. DwarfExpr.finalize());
  867. CallSiteDIE.addChild(CallSiteDieParam);
  868. }
  869. }
  870. DIE *DwarfCompileUnit::constructImportedEntityDIE(
  871. const DIImportedEntity *Module) {
  872. DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
  873. insertDIE(Module, IMDie);
  874. DIE *EntityDie;
  875. auto *Entity = Module->getEntity();
  876. if (auto *NS = dyn_cast<DINamespace>(Entity))
  877. EntityDie = getOrCreateNameSpace(NS);
  878. else if (auto *M = dyn_cast<DIModule>(Entity))
  879. EntityDie = getOrCreateModule(M);
  880. else if (auto *SP = dyn_cast<DISubprogram>(Entity))
  881. EntityDie = getOrCreateSubprogramDIE(SP);
  882. else if (auto *T = dyn_cast<DIType>(Entity))
  883. EntityDie = getOrCreateTypeDIE(T);
  884. else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
  885. EntityDie = getOrCreateGlobalVariableDIE(GV, {});
  886. else
  887. EntityDie = getDIE(Entity);
  888. assert(EntityDie);
  889. addSourceLine(*IMDie, Module->getLine(), Module->getFile());
  890. addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
  891. StringRef Name = Module->getName();
  892. if (!Name.empty())
  893. addString(*IMDie, dwarf::DW_AT_name, Name);
  894. return IMDie;
  895. }
  896. void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
  897. DIE *D = getDIE(SP);
  898. if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
  899. if (D)
  900. // If this subprogram has an abstract definition, reference that
  901. addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  902. } else {
  903. assert(D || includeMinimalInlineScopes());
  904. if (D)
  905. // And attach the attributes
  906. applySubprogramAttributesToDefinition(SP, *D);
  907. }
  908. }
  909. void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
  910. DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
  911. auto *Die = Entity->getDIE();
  912. /// Label may be used to generate DW_AT_low_pc, so put it outside
  913. /// if/else block.
  914. const DbgLabel *Label = nullptr;
  915. if (AbsEntity && AbsEntity->getDIE()) {
  916. addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
  917. Label = dyn_cast<const DbgLabel>(Entity);
  918. } else {
  919. if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
  920. applyVariableAttributes(*Var, *Die);
  921. else if ((Label = dyn_cast<const DbgLabel>(Entity)))
  922. applyLabelAttributes(*Label, *Die);
  923. else
  924. llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
  925. }
  926. if (Label)
  927. if (const auto *Sym = Label->getSymbol())
  928. addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
  929. }
  930. DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
  931. auto &AbstractEntities = getAbstractEntities();
  932. auto I = AbstractEntities.find(Node);
  933. if (I != AbstractEntities.end())
  934. return I->second.get();
  935. return nullptr;
  936. }
  937. void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
  938. LexicalScope *Scope) {
  939. assert(Scope && Scope->isAbstractScope());
  940. auto &Entity = getAbstractEntities()[Node];
  941. if (isa<const DILocalVariable>(Node)) {
  942. Entity = std::make_unique<DbgVariable>(
  943. cast<const DILocalVariable>(Node), nullptr /* IA */);;
  944. DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
  945. } else if (isa<const DILabel>(Node)) {
  946. Entity = std::make_unique<DbgLabel>(
  947. cast<const DILabel>(Node), nullptr /* IA */);
  948. DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
  949. }
  950. }
  951. void DwarfCompileUnit::emitHeader(bool UseOffsets) {
  952. // Don't bother labeling the .dwo unit, as its offset isn't used.
  953. if (!Skeleton && !DD->useSectionsAsReferences()) {
  954. LabelBegin = Asm->createTempSymbol("cu_begin");
  955. Asm->OutStreamer->EmitLabel(LabelBegin);
  956. }
  957. dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
  958. : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
  959. : dwarf::DW_UT_compile;
  960. DwarfUnit::emitCommonHeader(UseOffsets, UT);
  961. if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
  962. Asm->emitInt64(getDWOId());
  963. }
  964. bool DwarfCompileUnit::hasDwarfPubSections() const {
  965. switch (CUNode->getNameTableKind()) {
  966. case DICompileUnit::DebugNameTableKind::None:
  967. return false;
  968. // Opting in to GNU Pubnames/types overrides the default to ensure these are
  969. // generated for things like Gold's gdb_index generation.
  970. case DICompileUnit::DebugNameTableKind::GNU:
  971. return true;
  972. case DICompileUnit::DebugNameTableKind::Default:
  973. return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
  974. !CUNode->isDebugDirectivesOnly() &&
  975. DD->getAccelTableKind() != AccelTableKind::Apple &&
  976. DD->getDwarfVersion() < 5;
  977. }
  978. llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
  979. }
  980. /// addGlobalName - Add a new global name to the compile unit.
  981. void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
  982. const DIScope *Context) {
  983. if (!hasDwarfPubSections())
  984. return;
  985. std::string FullName = getParentContextString(Context) + Name.str();
  986. GlobalNames[FullName] = &Die;
  987. }
  988. void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
  989. const DIScope *Context) {
  990. if (!hasDwarfPubSections())
  991. return;
  992. std::string FullName = getParentContextString(Context) + Name.str();
  993. // Insert, allowing the entry to remain as-is if it's already present
  994. // This way the CU-level type DIE is preferred over the "can't describe this
  995. // type as a unit offset because it's not really in the CU at all, it's only
  996. // in a type unit"
  997. GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  998. }
  999. /// Add a new global type to the unit.
  1000. void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  1001. const DIScope *Context) {
  1002. if (!hasDwarfPubSections())
  1003. return;
  1004. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  1005. GlobalTypes[FullName] = &Die;
  1006. }
  1007. void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
  1008. const DIScope *Context) {
  1009. if (!hasDwarfPubSections())
  1010. return;
  1011. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  1012. // Insert, allowing the entry to remain as-is if it's already present
  1013. // This way the CU-level type DIE is preferred over the "can't describe this
  1014. // type as a unit offset because it's not really in the CU at all, it's only
  1015. // in a type unit"
  1016. GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  1017. }
  1018. void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
  1019. MachineLocation Location) {
  1020. if (DV.hasComplexAddress())
  1021. addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
  1022. else
  1023. addAddress(Die, dwarf::DW_AT_location, Location);
  1024. }
  1025. /// Add an address attribute to a die based on the location provided.
  1026. void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
  1027. const MachineLocation &Location) {
  1028. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1029. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  1030. if (Location.isIndirect())
  1031. DwarfExpr.setMemoryLocationKind();
  1032. DIExpressionCursor Cursor({});
  1033. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  1034. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1035. return;
  1036. DwarfExpr.addExpression(std::move(Cursor));
  1037. // Now attach the location information to the DIE.
  1038. addBlock(Die, Attribute, DwarfExpr.finalize());
  1039. }
  1040. /// Start with the address based on the location provided, and generate the
  1041. /// DWARF information necessary to find the actual variable given the extra
  1042. /// address information encoded in the DbgVariable, starting from the starting
  1043. /// location. Add the DWARF information to the die.
  1044. void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
  1045. dwarf::Attribute Attribute,
  1046. const MachineLocation &Location) {
  1047. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  1048. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  1049. const DIExpression *DIExpr = DV.getSingleExpression();
  1050. DwarfExpr.addFragmentOffset(DIExpr);
  1051. if (Location.isIndirect())
  1052. DwarfExpr.setMemoryLocationKind();
  1053. DIExpressionCursor Cursor(DIExpr);
  1054. if (DIExpr->isEntryValue()) {
  1055. DwarfExpr.setEntryValueFlag();
  1056. DwarfExpr.addEntryValueExpression(Cursor);
  1057. }
  1058. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  1059. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  1060. return;
  1061. DwarfExpr.addExpression(std::move(Cursor));
  1062. // Now attach the location information to the DIE.
  1063. addBlock(Die, Attribute, DwarfExpr.finalize());
  1064. }
  1065. /// Add a Dwarf loclistptr attribute data and value.
  1066. void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
  1067. unsigned Index) {
  1068. dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  1069. : dwarf::DW_FORM_data4;
  1070. Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
  1071. }
  1072. void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
  1073. DIE &VariableDie) {
  1074. StringRef Name = Var.getName();
  1075. if (!Name.empty())
  1076. addString(VariableDie, dwarf::DW_AT_name, Name);
  1077. const auto *DIVar = Var.getVariable();
  1078. if (DIVar)
  1079. if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
  1080. addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1081. AlignInBytes);
  1082. addSourceLine(VariableDie, DIVar);
  1083. addType(VariableDie, Var.getType());
  1084. if (Var.isArtificial())
  1085. addFlag(VariableDie, dwarf::DW_AT_artificial);
  1086. }
  1087. void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
  1088. DIE &LabelDie) {
  1089. StringRef Name = Label.getName();
  1090. if (!Name.empty())
  1091. addString(LabelDie, dwarf::DW_AT_name, Name);
  1092. const auto *DILabel = Label.getLabel();
  1093. addSourceLine(LabelDie, DILabel);
  1094. }
  1095. /// Add a Dwarf expression attribute data and value.
  1096. void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
  1097. const MCExpr *Expr) {
  1098. Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
  1099. }
  1100. void DwarfCompileUnit::addAddressExpr(DIE &Die, dwarf::Attribute Attribute,
  1101. const MCExpr *Expr) {
  1102. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  1103. DIEExpr(Expr));
  1104. }
  1105. void DwarfCompileUnit::applySubprogramAttributesToDefinition(
  1106. const DISubprogram *SP, DIE &SPDie) {
  1107. auto *SPDecl = SP->getDeclaration();
  1108. auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
  1109. applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
  1110. addGlobalName(SP->getName(), SPDie, Context);
  1111. }
  1112. bool DwarfCompileUnit::isDwoUnit() const {
  1113. return DD->useSplitDwarf() && Skeleton;
  1114. }
  1115. void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
  1116. constructTypeDIE(D, CTy);
  1117. }
  1118. bool DwarfCompileUnit::includeMinimalInlineScopes() const {
  1119. return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
  1120. (DD->useSplitDwarf() && !Skeleton);
  1121. }
  1122. void DwarfCompileUnit::addAddrTableBase() {
  1123. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1124. MCSymbol *Label = DD->getAddressPool().getLabel();
  1125. addSectionLabel(getUnitDie(),
  1126. getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
  1127. : dwarf::DW_AT_GNU_addr_base,
  1128. Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
  1129. }
  1130. void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
  1131. Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
  1132. new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
  1133. }
  1134. void DwarfCompileUnit::createBaseTypeDIEs() {
  1135. // Insert the base_type DIEs directly after the CU so that their offsets will
  1136. // fit in the fixed size ULEB128 used inside the location expressions.
  1137. // Maintain order by iterating backwards and inserting to the front of CU
  1138. // child list.
  1139. for (auto &Btr : reverse(ExprRefedBaseTypes)) {
  1140. DIE &Die = getUnitDie().addChildFront(
  1141. DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
  1142. SmallString<32> Str;
  1143. addString(Die, dwarf::DW_AT_name,
  1144. Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
  1145. "_" + Twine(Btr.BitSize)).toStringRef(Str));
  1146. addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
  1147. addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
  1148. Btr.Die = &Die;
  1149. }
  1150. }