DwarfCompileUnit.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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 = llvm::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 (RI->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->getDiscriminator() && DD->getDwarfVersion() >= 4)
  477. addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
  478. IA->getDiscriminator());
  479. // Add name to the name table, we do this here because we're guaranteed
  480. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  481. DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
  482. return ScopeDIE;
  483. }
  484. // Construct new DW_TAG_lexical_block for this scope and attach
  485. // DW_AT_low_pc/DW_AT_high_pc labels.
  486. DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
  487. if (DD->isLexicalScopeDIENull(Scope))
  488. return nullptr;
  489. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
  490. if (Scope->isAbstractScope())
  491. return ScopeDIE;
  492. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  493. return ScopeDIE;
  494. }
  495. /// constructVariableDIE - Construct a DIE for the given DbgVariable.
  496. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
  497. auto D = constructVariableDIEImpl(DV, Abstract);
  498. DV.setDIE(*D);
  499. return D;
  500. }
  501. DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
  502. const LexicalScope &Scope) {
  503. auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
  504. insertDIE(DL.getLabel(), LabelDie);
  505. DL.setDIE(*LabelDie);
  506. if (Scope.isAbstractScope())
  507. applyLabelAttributes(DL, *LabelDie);
  508. return LabelDie;
  509. }
  510. DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
  511. bool Abstract) {
  512. // Define variable debug information entry.
  513. auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
  514. insertDIE(DV.getVariable(), VariableDie);
  515. if (Abstract) {
  516. applyVariableAttributes(DV, *VariableDie);
  517. return VariableDie;
  518. }
  519. // Add variable address.
  520. unsigned Offset = DV.getDebugLocListIndex();
  521. if (Offset != ~0U) {
  522. addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
  523. return VariableDie;
  524. }
  525. // Check if variable has a single location description.
  526. if (auto *DVal = DV.getValueLoc()) {
  527. if (DVal->isLocation())
  528. addVariableAddress(DV, *VariableDie, DVal->getLoc());
  529. else if (DVal->isInt()) {
  530. auto *Expr = DV.getSingleExpression();
  531. if (Expr && Expr->getNumElements()) {
  532. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  533. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  534. // If there is an expression, emit raw unsigned bytes.
  535. DwarfExpr.addFragmentOffset(Expr);
  536. DwarfExpr.addUnsignedConstant(DVal->getInt());
  537. DwarfExpr.addExpression(Expr);
  538. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  539. } else
  540. addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
  541. } else if (DVal->isConstantFP()) {
  542. addConstantFPValue(*VariableDie, DVal->getConstantFP());
  543. } else if (DVal->isConstantInt()) {
  544. addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
  545. }
  546. return VariableDie;
  547. }
  548. // .. else use frame index.
  549. if (!DV.hasFrameIndexExprs())
  550. return VariableDie;
  551. Optional<unsigned> NVPTXAddressSpace;
  552. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  553. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  554. for (auto &Fragment : DV.getFrameIndexExprs()) {
  555. unsigned FrameReg = 0;
  556. const DIExpression *Expr = Fragment.Expr;
  557. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  558. int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
  559. DwarfExpr.addFragmentOffset(Expr);
  560. SmallVector<uint64_t, 8> Ops;
  561. Ops.push_back(dwarf::DW_OP_plus_uconst);
  562. Ops.push_back(Offset);
  563. // According to
  564. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  565. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  566. // correctly interpret address space of the variable address.
  567. // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
  568. // sequence for the NVPTX + gdb target.
  569. unsigned LocalNVPTXAddressSpace;
  570. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  571. const DIExpression *NewExpr =
  572. DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
  573. if (NewExpr != Expr) {
  574. Expr = NewExpr;
  575. NVPTXAddressSpace = LocalNVPTXAddressSpace;
  576. }
  577. }
  578. if (Expr)
  579. Ops.append(Expr->elements_begin(), Expr->elements_end());
  580. DIExpressionCursor Cursor(Ops);
  581. DwarfExpr.setMemoryLocationKind();
  582. if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
  583. addOpAddress(*Loc, FrameSymbol);
  584. else
  585. DwarfExpr.addMachineRegExpression(
  586. *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
  587. DwarfExpr.addExpression(std::move(Cursor));
  588. }
  589. if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
  590. // According to
  591. // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
  592. // cuda-gdb requires DW_AT_address_class for all variables to be able to
  593. // correctly interpret address space of the variable address.
  594. const unsigned NVPTX_ADDR_local_space = 6;
  595. addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
  596. NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
  597. }
  598. addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
  599. if (DwarfExpr.TagOffset)
  600. addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
  601. *DwarfExpr.TagOffset);
  602. return VariableDie;
  603. }
  604. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
  605. const LexicalScope &Scope,
  606. DIE *&ObjectPointer) {
  607. auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
  608. if (DV.isObjectPointer())
  609. ObjectPointer = Var;
  610. return Var;
  611. }
  612. /// Return all DIVariables that appear in count: expressions.
  613. static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
  614. SmallVector<const DIVariable *, 2> Result;
  615. auto *Array = dyn_cast<DICompositeType>(Var->getType());
  616. if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
  617. return Result;
  618. for (auto *El : Array->getElements()) {
  619. if (auto *Subrange = dyn_cast<DISubrange>(El)) {
  620. auto Count = Subrange->getCount();
  621. if (auto *Dependency = Count.dyn_cast<DIVariable *>())
  622. Result.push_back(Dependency);
  623. }
  624. }
  625. return Result;
  626. }
  627. /// Sort local variables so that variables appearing inside of helper
  628. /// expressions come first.
  629. static SmallVector<DbgVariable *, 8>
  630. sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
  631. SmallVector<DbgVariable *, 8> Result;
  632. SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
  633. // Map back from a DIVariable to its containing DbgVariable.
  634. SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
  635. // Set of DbgVariables in Result.
  636. SmallDenseSet<DbgVariable *, 8> Visited;
  637. // For cycle detection.
  638. SmallDenseSet<DbgVariable *, 8> Visiting;
  639. // Initialize the worklist and the DIVariable lookup table.
  640. for (auto Var : reverse(Input)) {
  641. DbgVar.insert({Var->getVariable(), Var});
  642. WorkList.push_back({Var, 0});
  643. }
  644. // Perform a stable topological sort by doing a DFS.
  645. while (!WorkList.empty()) {
  646. auto Item = WorkList.back();
  647. DbgVariable *Var = Item.getPointer();
  648. bool visitedAllDependencies = Item.getInt();
  649. WorkList.pop_back();
  650. // Dependency is in a different lexical scope or a global.
  651. if (!Var)
  652. continue;
  653. // Already handled.
  654. if (Visited.count(Var))
  655. continue;
  656. // Add to Result if all dependencies are visited.
  657. if (visitedAllDependencies) {
  658. Visited.insert(Var);
  659. Result.push_back(Var);
  660. continue;
  661. }
  662. // Detect cycles.
  663. auto Res = Visiting.insert(Var);
  664. if (!Res.second) {
  665. assert(false && "dependency cycle in local variables");
  666. return Result;
  667. }
  668. // Push dependencies and this node onto the worklist, so that this node is
  669. // visited again after all of its dependencies are handled.
  670. WorkList.push_back({Var, 1});
  671. for (auto *Dependency : dependencies(Var)) {
  672. auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
  673. WorkList.push_back({DbgVar[Dep], 0});
  674. }
  675. }
  676. return Result;
  677. }
  678. DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
  679. SmallVectorImpl<DIE *> &Children,
  680. bool *HasNonScopeChildren) {
  681. assert(Children.empty());
  682. DIE *ObjectPointer = nullptr;
  683. // Emit function arguments (order is significant).
  684. auto Vars = DU->getScopeVariables().lookup(Scope);
  685. for (auto &DV : Vars.Args)
  686. Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
  687. // Emit local variables.
  688. auto Locals = sortLocalVars(Vars.Locals);
  689. for (DbgVariable *DV : Locals)
  690. Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
  691. // Skip imported directives in gmlt-like data.
  692. if (!includeMinimalInlineScopes()) {
  693. // There is no need to emit empty lexical block DIE.
  694. for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
  695. Children.push_back(
  696. constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
  697. }
  698. if (HasNonScopeChildren)
  699. *HasNonScopeChildren = !Children.empty();
  700. for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
  701. Children.push_back(constructLabelDIE(*DL, *Scope));
  702. for (LexicalScope *LS : Scope->getChildren())
  703. constructScopeDIE(LS, Children);
  704. return ObjectPointer;
  705. }
  706. DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
  707. LexicalScope *Scope) {
  708. DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
  709. if (Scope) {
  710. assert(!Scope->getInlinedAt());
  711. assert(!Scope->isAbstractScope());
  712. // Collect lexical scope children first.
  713. // ObjectPointer might be a local (non-argument) local variable if it's a
  714. // block's synthetic this pointer.
  715. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
  716. addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  717. }
  718. // If this is a variadic function, add an unspecified parameter.
  719. DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
  720. // If we have a single element of null, it is a function that returns void.
  721. // If we have more than one elements and the last one is null, it is a
  722. // variadic function.
  723. if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
  724. !includeMinimalInlineScopes())
  725. ScopeDIE.addChild(
  726. DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
  727. return ScopeDIE;
  728. }
  729. DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
  730. DIE &ScopeDIE) {
  731. // We create children when the scope DIE is not null.
  732. SmallVector<DIE *, 8> Children;
  733. DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
  734. // Add children
  735. for (auto &I : Children)
  736. ScopeDIE.addChild(std::move(I));
  737. return ObjectPointer;
  738. }
  739. void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
  740. LexicalScope *Scope) {
  741. DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
  742. if (AbsDef)
  743. return;
  744. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  745. DIE *ContextDIE;
  746. DwarfCompileUnit *ContextCU = this;
  747. if (includeMinimalInlineScopes())
  748. ContextDIE = &getUnitDie();
  749. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  750. // the important distinction that the debug node is not associated with the
  751. // DIE (since the debug node will be associated with the concrete DIE, if
  752. // any). It could be refactored to some common utility function.
  753. else if (auto *SPDecl = SP->getDeclaration()) {
  754. ContextDIE = &getUnitDie();
  755. getOrCreateSubprogramDIE(SPDecl);
  756. } else {
  757. ContextDIE = getOrCreateContextDIE(SP->getScope());
  758. // The scope may be shared with a subprogram that has already been
  759. // constructed in another CU, in which case we need to construct this
  760. // subprogram in the same CU.
  761. ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
  762. }
  763. // Passing null as the associated node because the abstract definition
  764. // shouldn't be found by lookup.
  765. AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
  766. ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
  767. if (!ContextCU->includeMinimalInlineScopes())
  768. ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
  769. if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
  770. ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
  771. }
  772. DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
  773. const DISubprogram &CalleeSP,
  774. bool IsTail,
  775. const MCExpr *PCOffset) {
  776. // Insert a call site entry DIE within ScopeDIE.
  777. DIE &CallSiteDIE =
  778. createAndAddDIE(dwarf::DW_TAG_call_site, ScopeDIE, nullptr);
  779. // For the purposes of showing tail call frames in backtraces, a key piece of
  780. // information is DW_AT_call_origin, a pointer to the callee DIE.
  781. DIE *CalleeDIE = getOrCreateSubprogramDIE(&CalleeSP);
  782. assert(CalleeDIE && "Could not create DIE for call site entry origin");
  783. addDIEEntry(CallSiteDIE, dwarf::DW_AT_call_origin, *CalleeDIE);
  784. if (IsTail) {
  785. // Attach DW_AT_call_tail_call to tail calls for standards compliance.
  786. addFlag(CallSiteDIE, dwarf::DW_AT_call_tail_call);
  787. } else {
  788. // Attach the return PC to allow the debugger to disambiguate call paths
  789. // from one function to another.
  790. assert(PCOffset && "Missing return PC information for a call");
  791. addAddressExpr(CallSiteDIE, dwarf::DW_AT_call_return_pc, PCOffset);
  792. }
  793. return CallSiteDIE;
  794. }
  795. DIE *DwarfCompileUnit::constructImportedEntityDIE(
  796. const DIImportedEntity *Module) {
  797. DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
  798. insertDIE(Module, IMDie);
  799. DIE *EntityDie;
  800. auto *Entity = Module->getEntity();
  801. if (auto *NS = dyn_cast<DINamespace>(Entity))
  802. EntityDie = getOrCreateNameSpace(NS);
  803. else if (auto *M = dyn_cast<DIModule>(Entity))
  804. EntityDie = getOrCreateModule(M);
  805. else if (auto *SP = dyn_cast<DISubprogram>(Entity))
  806. EntityDie = getOrCreateSubprogramDIE(SP);
  807. else if (auto *T = dyn_cast<DIType>(Entity))
  808. EntityDie = getOrCreateTypeDIE(T);
  809. else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
  810. EntityDie = getOrCreateGlobalVariableDIE(GV, {});
  811. else
  812. EntityDie = getDIE(Entity);
  813. assert(EntityDie);
  814. addSourceLine(*IMDie, Module->getLine(), Module->getFile());
  815. addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
  816. StringRef Name = Module->getName();
  817. if (!Name.empty())
  818. addString(*IMDie, dwarf::DW_AT_name, Name);
  819. return IMDie;
  820. }
  821. void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
  822. DIE *D = getDIE(SP);
  823. if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
  824. if (D)
  825. // If this subprogram has an abstract definition, reference that
  826. addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  827. } else {
  828. assert(D || includeMinimalInlineScopes());
  829. if (D)
  830. // And attach the attributes
  831. applySubprogramAttributesToDefinition(SP, *D);
  832. }
  833. }
  834. void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
  835. DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
  836. auto *Die = Entity->getDIE();
  837. /// Label may be used to generate DW_AT_low_pc, so put it outside
  838. /// if/else block.
  839. const DbgLabel *Label = nullptr;
  840. if (AbsEntity && AbsEntity->getDIE()) {
  841. addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
  842. Label = dyn_cast<const DbgLabel>(Entity);
  843. } else {
  844. if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
  845. applyVariableAttributes(*Var, *Die);
  846. else if ((Label = dyn_cast<const DbgLabel>(Entity)))
  847. applyLabelAttributes(*Label, *Die);
  848. else
  849. llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
  850. }
  851. if (Label)
  852. if (const auto *Sym = Label->getSymbol())
  853. addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
  854. }
  855. DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
  856. auto &AbstractEntities = getAbstractEntities();
  857. auto I = AbstractEntities.find(Node);
  858. if (I != AbstractEntities.end())
  859. return I->second.get();
  860. return nullptr;
  861. }
  862. void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
  863. LexicalScope *Scope) {
  864. assert(Scope && Scope->isAbstractScope());
  865. auto &Entity = getAbstractEntities()[Node];
  866. if (isa<const DILocalVariable>(Node)) {
  867. Entity = llvm::make_unique<DbgVariable>(
  868. cast<const DILocalVariable>(Node), nullptr /* IA */);;
  869. DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
  870. } else if (isa<const DILabel>(Node)) {
  871. Entity = llvm::make_unique<DbgLabel>(
  872. cast<const DILabel>(Node), nullptr /* IA */);
  873. DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
  874. }
  875. }
  876. void DwarfCompileUnit::emitHeader(bool UseOffsets) {
  877. // Don't bother labeling the .dwo unit, as its offset isn't used.
  878. if (!Skeleton && !DD->useSectionsAsReferences()) {
  879. LabelBegin = Asm->createTempSymbol("cu_begin");
  880. Asm->OutStreamer->EmitLabel(LabelBegin);
  881. }
  882. dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
  883. : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
  884. : dwarf::DW_UT_compile;
  885. DwarfUnit::emitCommonHeader(UseOffsets, UT);
  886. if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
  887. Asm->emitInt64(getDWOId());
  888. }
  889. bool DwarfCompileUnit::hasDwarfPubSections() const {
  890. switch (CUNode->getNameTableKind()) {
  891. case DICompileUnit::DebugNameTableKind::None:
  892. return false;
  893. // Opting in to GNU Pubnames/types overrides the default to ensure these are
  894. // generated for things like Gold's gdb_index generation.
  895. case DICompileUnit::DebugNameTableKind::GNU:
  896. return true;
  897. case DICompileUnit::DebugNameTableKind::Default:
  898. return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
  899. !CUNode->isDebugDirectivesOnly() &&
  900. DD->getAccelTableKind() != AccelTableKind::Apple &&
  901. DD->getDwarfVersion() < 5;
  902. }
  903. llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
  904. }
  905. /// addGlobalName - Add a new global name to the compile unit.
  906. void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
  907. const DIScope *Context) {
  908. if (!hasDwarfPubSections())
  909. return;
  910. std::string FullName = getParentContextString(Context) + Name.str();
  911. GlobalNames[FullName] = &Die;
  912. }
  913. void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
  914. const DIScope *Context) {
  915. if (!hasDwarfPubSections())
  916. return;
  917. std::string FullName = getParentContextString(Context) + Name.str();
  918. // Insert, allowing the entry to remain as-is if it's already present
  919. // This way the CU-level type DIE is preferred over the "can't describe this
  920. // type as a unit offset because it's not really in the CU at all, it's only
  921. // in a type unit"
  922. GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  923. }
  924. /// Add a new global type to the unit.
  925. void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  926. const DIScope *Context) {
  927. if (!hasDwarfPubSections())
  928. return;
  929. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  930. GlobalTypes[FullName] = &Die;
  931. }
  932. void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
  933. const DIScope *Context) {
  934. if (!hasDwarfPubSections())
  935. return;
  936. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  937. // Insert, allowing the entry to remain as-is if it's already present
  938. // This way the CU-level type DIE is preferred over the "can't describe this
  939. // type as a unit offset because it's not really in the CU at all, it's only
  940. // in a type unit"
  941. GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
  942. }
  943. /// addVariableAddress - Add DW_AT_location attribute for a
  944. /// DbgVariable based on provided MachineLocation.
  945. void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
  946. MachineLocation Location) {
  947. // addBlockByrefAddress is obsolete and will be removed soon.
  948. // The clang frontend always generates block byref variables with a
  949. // complex expression that encodes exactly what addBlockByrefAddress
  950. // would do.
  951. assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
  952. "block byref variable without a complex expression");
  953. if (DV.hasComplexAddress())
  954. addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
  955. else
  956. addAddress(Die, dwarf::DW_AT_location, Location);
  957. }
  958. /// Add an address attribute to a die based on the location provided.
  959. void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
  960. const MachineLocation &Location) {
  961. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  962. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  963. if (Location.isIndirect())
  964. DwarfExpr.setMemoryLocationKind();
  965. DIExpressionCursor Cursor({});
  966. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  967. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  968. return;
  969. DwarfExpr.addExpression(std::move(Cursor));
  970. // Now attach the location information to the DIE.
  971. addBlock(Die, Attribute, DwarfExpr.finalize());
  972. }
  973. /// Start with the address based on the location provided, and generate the
  974. /// DWARF information necessary to find the actual variable given the extra
  975. /// address information encoded in the DbgVariable, starting from the starting
  976. /// location. Add the DWARF information to the die.
  977. void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
  978. dwarf::Attribute Attribute,
  979. const MachineLocation &Location) {
  980. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  981. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  982. const DIExpression *DIExpr = DV.getSingleExpression();
  983. DwarfExpr.addFragmentOffset(DIExpr);
  984. if (Location.isIndirect())
  985. DwarfExpr.setMemoryLocationKind();
  986. DIExpressionCursor Cursor(DIExpr);
  987. if (DIExpr->isEntryValue()) {
  988. DwarfExpr.setEntryValueFlag();
  989. DwarfExpr.addEntryValueExpression(Cursor);
  990. }
  991. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  992. if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
  993. return;
  994. DwarfExpr.addExpression(std::move(Cursor));
  995. // Now attach the location information to the DIE.
  996. addBlock(Die, Attribute, DwarfExpr.finalize());
  997. }
  998. /// Add a Dwarf loclistptr attribute data and value.
  999. void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
  1000. unsigned Index) {
  1001. dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  1002. : dwarf::DW_FORM_data4;
  1003. Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
  1004. }
  1005. void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
  1006. DIE &VariableDie) {
  1007. StringRef Name = Var.getName();
  1008. if (!Name.empty())
  1009. addString(VariableDie, dwarf::DW_AT_name, Name);
  1010. const auto *DIVar = Var.getVariable();
  1011. if (DIVar)
  1012. if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
  1013. addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
  1014. AlignInBytes);
  1015. addSourceLine(VariableDie, DIVar);
  1016. addType(VariableDie, Var.getType());
  1017. if (Var.isArtificial())
  1018. addFlag(VariableDie, dwarf::DW_AT_artificial);
  1019. }
  1020. void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
  1021. DIE &LabelDie) {
  1022. StringRef Name = Label.getName();
  1023. if (!Name.empty())
  1024. addString(LabelDie, dwarf::DW_AT_name, Name);
  1025. const auto *DILabel = Label.getLabel();
  1026. addSourceLine(LabelDie, DILabel);
  1027. }
  1028. /// Add a Dwarf expression attribute data and value.
  1029. void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
  1030. const MCExpr *Expr) {
  1031. Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
  1032. }
  1033. void DwarfCompileUnit::addAddressExpr(DIE &Die, dwarf::Attribute Attribute,
  1034. const MCExpr *Expr) {
  1035. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  1036. DIEExpr(Expr));
  1037. }
  1038. void DwarfCompileUnit::applySubprogramAttributesToDefinition(
  1039. const DISubprogram *SP, DIE &SPDie) {
  1040. auto *SPDecl = SP->getDeclaration();
  1041. auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
  1042. applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
  1043. addGlobalName(SP->getName(), SPDie, Context);
  1044. }
  1045. bool DwarfCompileUnit::isDwoUnit() const {
  1046. return DD->useSplitDwarf() && Skeleton;
  1047. }
  1048. void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
  1049. constructTypeDIE(D, CTy);
  1050. }
  1051. bool DwarfCompileUnit::includeMinimalInlineScopes() const {
  1052. return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
  1053. (DD->useSplitDwarf() && !Skeleton);
  1054. }
  1055. void DwarfCompileUnit::addAddrTableBase() {
  1056. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  1057. MCSymbol *Label = DD->getAddressPool().getLabel();
  1058. addSectionLabel(getUnitDie(),
  1059. getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
  1060. : dwarf::DW_AT_GNU_addr_base,
  1061. Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
  1062. }
  1063. void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
  1064. Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
  1065. new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
  1066. }
  1067. void DwarfCompileUnit::createBaseTypeDIEs() {
  1068. // Insert the base_type DIEs directly after the CU so that their offsets will
  1069. // fit in the fixed size ULEB128 used inside the location expressions.
  1070. // Maintain order by iterating backwards and inserting to the front of CU
  1071. // child list.
  1072. for (auto &Btr : reverse(ExprRefedBaseTypes)) {
  1073. DIE &Die = getUnitDie().addChildFront(
  1074. DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
  1075. SmallString<32> Str;
  1076. addString(Die, dwarf::DW_AT_name,
  1077. Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
  1078. "_" + Twine(Btr.BitSize)).toStringRef(Str));
  1079. addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
  1080. addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
  1081. Btr.Die = &Die;
  1082. }
  1083. }