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