DwarfCompileUnit.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. #include "DwarfCompileUnit.h"
  2. #include "DwarfExpression.h"
  3. #include "llvm/CodeGen/MachineFunction.h"
  4. #include "llvm/IR/Constants.h"
  5. #include "llvm/IR/DataLayout.h"
  6. #include "llvm/IR/GlobalValue.h"
  7. #include "llvm/IR/GlobalVariable.h"
  8. #include "llvm/IR/Instruction.h"
  9. #include "llvm/MC/MCAsmInfo.h"
  10. #include "llvm/MC/MCStreamer.h"
  11. #include "llvm/Target/TargetFrameLowering.h"
  12. #include "llvm/Target/TargetLoweringObjectFile.h"
  13. #include "llvm/Target/TargetMachine.h"
  14. #include "llvm/Target/TargetRegisterInfo.h"
  15. #include "llvm/Target/TargetSubtargetInfo.h"
  16. namespace llvm {
  17. DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
  18. AsmPrinter *A, DwarfDebug *DW,
  19. DwarfFile *DWU)
  20. : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
  21. Skeleton(nullptr), BaseAddress(nullptr) {
  22. insertDIE(Node, &getUnitDie());
  23. MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
  24. }
  25. /// addLabelAddress - Add a dwarf label attribute data and value using
  26. /// DW_FORM_addr or DW_FORM_GNU_addr_index.
  27. ///
  28. void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
  29. const MCSymbol *Label) {
  30. // Don't use the address pool in non-fission or in the skeleton unit itself.
  31. // FIXME: Once GDB supports this, it's probably worthwhile using the address
  32. // pool from the skeleton - maybe even in non-fission (possibly fewer
  33. // relocations by sharing them in the pool, but we have other ideas about how
  34. // to reduce the number of relocations as well/instead).
  35. if (!DD->useSplitDwarf() || !Skeleton)
  36. return addLocalLabelAddress(Die, Attribute, Label);
  37. if (Label)
  38. DD->addArangeLabel(SymbolCU(this, Label));
  39. unsigned idx = DD->getAddressPool().getIndex(Label);
  40. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
  41. DIEInteger(idx));
  42. }
  43. void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
  44. dwarf::Attribute Attribute,
  45. const MCSymbol *Label) {
  46. if (Label)
  47. DD->addArangeLabel(SymbolCU(this, Label));
  48. if (Label)
  49. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  50. DIELabel(Label));
  51. else
  52. Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
  53. DIEInteger(0));
  54. }
  55. unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
  56. StringRef DirName) {
  57. // If we print assembly, we can't separate .file entries according to
  58. // compile units. Thus all files will belong to the default compile unit.
  59. // FIXME: add a better feature test than hasRawTextSupport. Even better,
  60. // extend .file to support this.
  61. return Asm->OutStreamer->EmitDwarfFileDirective(
  62. 0, DirName, FileName,
  63. Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
  64. }
  65. /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
  66. DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
  67. const DIGlobalVariable *GV, const GlobalVariable *Global) {
  68. // Check for pre-existence.
  69. if (DIE *Die = getDIE(GV))
  70. return Die;
  71. assert(GV);
  72. auto *GVContext = GV->getScope();
  73. auto *GTy = DD->resolve(GV->getType());
  74. // Construct the context before querying for the existence of the DIE in
  75. // case such construction creates the DIE.
  76. DIE *ContextDIE = getOrCreateContextDIE(GVContext);
  77. // Add to map.
  78. DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
  79. DIScope *DeclContext;
  80. if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
  81. DeclContext = resolve(SDMDecl->getScope());
  82. assert(SDMDecl->isStaticMember() && "Expected static member decl");
  83. assert(GV->isDefinition());
  84. // We need the declaration DIE that is in the static member's class.
  85. DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
  86. addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
  87. } else {
  88. DeclContext = GV->getScope();
  89. // Add name and type.
  90. addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
  91. addType(*VariableDIE, GTy);
  92. // Add scoping info.
  93. if (!GV->isLocalToUnit())
  94. addFlag(*VariableDIE, dwarf::DW_AT_external);
  95. // Add line number info.
  96. addSourceLine(*VariableDIE, GV);
  97. }
  98. if (!GV->isDefinition())
  99. addFlag(*VariableDIE, dwarf::DW_AT_declaration);
  100. else
  101. addGlobalName(GV->getName(), *VariableDIE, DeclContext);
  102. // Add location.
  103. bool addToAccelTable = false;
  104. DIExpression *Expr = GV->getExpr();
  105. // For compatibility with DWARF 3 and earlier,
  106. // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
  107. // DW_AT_const_value(X).
  108. if (Expr && Expr->getNumElements() == 3 &&
  109. Expr->getElement(0) == dwarf::DW_OP_constu &&
  110. Expr->getElement(2) == dwarf::DW_OP_stack_value) {
  111. addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
  112. // We cannot describe the location of dllimport'd variables: the computation
  113. // of their address requires loads from the IAT.
  114. } else if (!Global || !Global->hasDLLImportStorageClass()) {
  115. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  116. if (Global) {
  117. addToAccelTable = true;
  118. const MCSymbol *Sym = Asm->getSymbol(Global);
  119. if (Global->isThreadLocal()) {
  120. if (Asm->TM.Options.EmulatedTLS) {
  121. // TODO: add debug info for emulated thread local mode.
  122. } else {
  123. // FIXME: Make this work with -gsplit-dwarf.
  124. unsigned PointerSize = Asm->getDataLayout().getPointerSize();
  125. assert((PointerSize == 4 || PointerSize == 8) &&
  126. "Add support for other sizes if necessary");
  127. // Based on GCC's support for TLS:
  128. if (!DD->useSplitDwarf()) {
  129. // 1) Start with a constNu of the appropriate pointer size
  130. addUInt(*Loc, dwarf::DW_FORM_data1, PointerSize == 4
  131. ? dwarf::DW_OP_const4u
  132. : dwarf::DW_OP_const8u);
  133. // 2) containing the (relocated) offset of the TLS variable
  134. // within the module's TLS block.
  135. addExpr(*Loc, dwarf::DW_FORM_udata,
  136. Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
  137. } else {
  138. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
  139. addUInt(*Loc, dwarf::DW_FORM_udata,
  140. DD->getAddressPool().getIndex(Sym, /* TLS */ true));
  141. }
  142. // 3) followed by an OP to make the debugger do a TLS lookup.
  143. addUInt(*Loc, dwarf::DW_FORM_data1,
  144. DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
  145. : dwarf::DW_OP_form_tls_address);
  146. }
  147. } else {
  148. DD->addArangeLabel(SymbolCU(this, Sym));
  149. addOpAddress(*Loc, Sym);
  150. }
  151. if (Expr) {
  152. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  153. DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
  154. }
  155. }
  156. addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
  157. if (DD->useAllLinkageNames())
  158. addLinkageName(*VariableDIE, GV->getLinkageName());
  159. }
  160. if (addToAccelTable) {
  161. DD->addAccelName(GV->getName(), *VariableDIE);
  162. // If the linkage name is different than the name, go ahead and output
  163. // that as well into the name table.
  164. if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
  165. DD->addAccelName(GV->getLinkageName(), *VariableDIE);
  166. }
  167. return VariableDIE;
  168. }
  169. void DwarfCompileUnit::addRange(RangeSpan Range) {
  170. bool SameAsPrevCU = this == DD->getPrevCU();
  171. DD->setPrevCU(this);
  172. // If we have no current ranges just add the range and return, otherwise,
  173. // check the current section and CU against the previous section and CU we
  174. // emitted into and the subprogram was contained within. If these are the
  175. // same then extend our current range, otherwise add this as a new range.
  176. if (CURanges.empty() || !SameAsPrevCU ||
  177. (&CURanges.back().getEnd()->getSection() !=
  178. &Range.getEnd()->getSection())) {
  179. CURanges.push_back(Range);
  180. return;
  181. }
  182. CURanges.back().setEnd(Range.getEnd());
  183. }
  184. DIE::value_iterator
  185. DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
  186. const MCSymbol *Label, const MCSymbol *Sec) {
  187. if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
  188. return addLabel(Die, Attribute,
  189. DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  190. : dwarf::DW_FORM_data4,
  191. Label);
  192. return addSectionDelta(Die, Attribute, Label, Sec);
  193. }
  194. void DwarfCompileUnit::initStmtList() {
  195. // Define start line table label for each Compile Unit.
  196. MCSymbol *LineTableStartSym =
  197. Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
  198. // DW_AT_stmt_list is a offset of line number information for this
  199. // compile unit in debug_line section. For split dwarf this is
  200. // left in the skeleton CU and so not included.
  201. // The line table entries are not always emitted in assembly, so it
  202. // is not okay to use line_table_start here.
  203. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  204. StmtListValue =
  205. addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
  206. TLOF.getDwarfLineSection()->getBeginSymbol());
  207. }
  208. void DwarfCompileUnit::applyStmtList(DIE &D) {
  209. D.addValue(DIEValueAllocator, *StmtListValue);
  210. }
  211. void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
  212. const MCSymbol *End) {
  213. assert(Begin && "Begin label should not be null!");
  214. assert(End && "End label should not be null!");
  215. assert(Begin->isDefined() && "Invalid starting label");
  216. assert(End->isDefined() && "Invalid end label");
  217. addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
  218. if (DD->getDwarfVersion() < 4)
  219. addLabelAddress(D, dwarf::DW_AT_high_pc, End);
  220. else
  221. addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
  222. }
  223. // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
  224. // and DW_AT_high_pc attributes. If there are global variables in this
  225. // scope then create and insert DIEs for these variables.
  226. DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
  227. DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
  228. attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
  229. if (DD->useAppleExtensionAttributes() &&
  230. !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
  231. *DD->getCurrentFunction()))
  232. addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
  233. // Only include DW_AT_frame_base in full debug info
  234. if (!includeMinimalInlineScopes()) {
  235. const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
  236. MachineLocation Location(RI->getFrameRegister(*Asm->MF));
  237. if (RI->isPhysicalRegister(Location.getReg()))
  238. addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
  239. }
  240. // Add name to the name table, we do this here because we're guaranteed
  241. // to have concrete versions of our DW_TAG_subprogram nodes.
  242. DD->addSubprogramNames(SP, *SPDie);
  243. return *SPDie;
  244. }
  245. // Construct a DIE for this scope.
  246. void DwarfCompileUnit::constructScopeDIE(
  247. LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
  248. if (!Scope || !Scope->getScopeNode())
  249. return;
  250. auto *DS = Scope->getScopeNode();
  251. assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
  252. "Only handle inlined subprograms here, use "
  253. "constructSubprogramScopeDIE for non-inlined "
  254. "subprograms");
  255. SmallVector<DIE *, 8> Children;
  256. // We try to create the scope DIE first, then the children DIEs. This will
  257. // avoid creating un-used children then removing them later when we find out
  258. // the scope DIE is null.
  259. DIE *ScopeDIE;
  260. if (Scope->getParent() && isa<DISubprogram>(DS)) {
  261. ScopeDIE = constructInlinedScopeDIE(Scope);
  262. if (!ScopeDIE)
  263. return;
  264. // We create children when the scope DIE is not null.
  265. createScopeChildrenDIE(Scope, Children);
  266. } else {
  267. // Early exit when we know the scope DIE is going to be null.
  268. if (DD->isLexicalScopeDIENull(Scope))
  269. return;
  270. unsigned ChildScopeCount;
  271. // We create children here when we know the scope DIE is not going to be
  272. // null and the children will be added to the scope DIE.
  273. createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
  274. // Skip imported directives in gmlt-like data.
  275. if (!includeMinimalInlineScopes()) {
  276. // There is no need to emit empty lexical block DIE.
  277. for (const auto *IE : ImportedEntities[DS])
  278. Children.push_back(
  279. constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
  280. }
  281. // If there are only other scopes as children, put them directly in the
  282. // parent instead, as this scope would serve no purpose.
  283. if (Children.size() == ChildScopeCount) {
  284. FinalChildren.insert(FinalChildren.end(),
  285. std::make_move_iterator(Children.begin()),
  286. std::make_move_iterator(Children.end()));
  287. return;
  288. }
  289. ScopeDIE = constructLexicalScopeDIE(Scope);
  290. assert(ScopeDIE && "Scope DIE should not be null.");
  291. }
  292. // Add children
  293. for (auto &I : Children)
  294. ScopeDIE->addChild(std::move(I));
  295. FinalChildren.push_back(std::move(ScopeDIE));
  296. }
  297. DIE::value_iterator
  298. DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
  299. const MCSymbol *Hi, const MCSymbol *Lo) {
  300. return Die.addValue(DIEValueAllocator, Attribute,
  301. DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  302. : dwarf::DW_FORM_data4,
  303. new (DIEValueAllocator) DIEDelta(Hi, Lo));
  304. }
  305. void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
  306. SmallVector<RangeSpan, 2> Range) {
  307. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  308. // Emit offset in .debug_range as a relocatable label. emitDIE will handle
  309. // emitting it appropriately.
  310. const MCSymbol *RangeSectionSym =
  311. TLOF.getDwarfRangesSection()->getBeginSymbol();
  312. RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
  313. // Under fission, ranges are specified by constant offsets relative to the
  314. // CU's DW_AT_GNU_ranges_base.
  315. if (isDwoUnit())
  316. addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  317. RangeSectionSym);
  318. else
  319. addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  320. RangeSectionSym);
  321. // Add the range list to the set of ranges to be emitted.
  322. (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
  323. }
  324. void DwarfCompileUnit::attachRangesOrLowHighPC(
  325. DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
  326. if (Ranges.size() == 1) {
  327. const auto &single = Ranges.front();
  328. attachLowHighPC(Die, single.getStart(), single.getEnd());
  329. } else
  330. addScopeRangeList(Die, std::move(Ranges));
  331. }
  332. void DwarfCompileUnit::attachRangesOrLowHighPC(
  333. DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
  334. SmallVector<RangeSpan, 2> List;
  335. List.reserve(Ranges.size());
  336. for (const InsnRange &R : Ranges)
  337. List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
  338. DD->getLabelAfterInsn(R.second)));
  339. attachRangesOrLowHighPC(Die, std::move(List));
  340. }
  341. // This scope represents inlined body of a function. Construct DIE to
  342. // represent this concrete inlined copy of the function.
  343. DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
  344. assert(Scope->getScopeNode());
  345. auto *DS = Scope->getScopeNode();
  346. auto *InlinedSP = getDISubprogram(DS);
  347. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  348. // was inlined from another compile unit.
  349. DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
  350. assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
  351. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
  352. addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
  353. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  354. // Add the call site information to the DIE.
  355. const DILocation *IA = Scope->getInlinedAt();
  356. addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
  357. getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
  358. addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
  359. if (IA->getDiscriminator())
  360. addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
  361. IA->getDiscriminator());
  362. // Add name to the name table, we do this here because we're guaranteed
  363. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  364. DD->addSubprogramNames(InlinedSP, *ScopeDIE);
  365. return ScopeDIE;
  366. }
  367. // Construct new DW_TAG_lexical_block for this scope and attach
  368. // DW_AT_low_pc/DW_AT_high_pc labels.
  369. DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
  370. if (DD->isLexicalScopeDIENull(Scope))
  371. return nullptr;
  372. auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
  373. if (Scope->isAbstractScope())
  374. return ScopeDIE;
  375. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  376. return ScopeDIE;
  377. }
  378. /// constructVariableDIE - Construct a DIE for the given DbgVariable.
  379. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
  380. auto D = constructVariableDIEImpl(DV, Abstract);
  381. DV.setDIE(*D);
  382. return D;
  383. }
  384. DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
  385. bool Abstract) {
  386. // Define variable debug information entry.
  387. auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
  388. if (Abstract) {
  389. applyVariableAttributes(DV, *VariableDie);
  390. return VariableDie;
  391. }
  392. // Add variable address.
  393. unsigned Offset = DV.getDebugLocListIndex();
  394. if (Offset != ~0U) {
  395. addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
  396. return VariableDie;
  397. }
  398. // Check if variable is described by a DBG_VALUE instruction.
  399. if (const MachineInstr *DVInsn = DV.getMInsn()) {
  400. assert(DVInsn->getNumOperands() == 4);
  401. if (DVInsn->getOperand(0).isReg()) {
  402. const MachineOperand RegOp = DVInsn->getOperand(0);
  403. // If the second operand is an immediate, this is an indirect value.
  404. if (DVInsn->getOperand(1).isImm()) {
  405. MachineLocation Location(RegOp.getReg(),
  406. DVInsn->getOperand(1).getImm());
  407. addVariableAddress(DV, *VariableDie, Location);
  408. } else if (RegOp.getReg())
  409. addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
  410. } else if (DVInsn->getOperand(0).isImm()) {
  411. // This variable is described by a single constant.
  412. // Check whether it has a DIExpression.
  413. auto *Expr = DV.getSingleExpression();
  414. if (Expr && Expr->getNumElements()) {
  415. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  416. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  417. // If there is an expression, emit raw unsigned bytes.
  418. DwarfExpr.AddUnsignedConstant(DVInsn->getOperand(0).getImm());
  419. DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
  420. addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
  421. } else
  422. addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
  423. } else if (DVInsn->getOperand(0).isFPImm())
  424. addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
  425. else if (DVInsn->getOperand(0).isCImm())
  426. addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
  427. DV.getType());
  428. return VariableDie;
  429. }
  430. // .. else use frame index.
  431. if (DV.getFrameIndex().empty())
  432. return VariableDie;
  433. auto Expr = DV.getExpression().begin();
  434. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  435. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  436. for (auto FI : DV.getFrameIndex()) {
  437. unsigned FrameReg = 0;
  438. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  439. int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
  440. assert(Expr != DV.getExpression().end() && "Wrong number of expressions");
  441. DwarfExpr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
  442. FrameReg, Offset);
  443. DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end());
  444. ++Expr;
  445. }
  446. addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
  447. return VariableDie;
  448. }
  449. DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
  450. const LexicalScope &Scope,
  451. DIE *&ObjectPointer) {
  452. auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
  453. if (DV.isObjectPointer())
  454. ObjectPointer = Var;
  455. return Var;
  456. }
  457. DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
  458. SmallVectorImpl<DIE *> &Children,
  459. unsigned *ChildScopeCount) {
  460. DIE *ObjectPointer = nullptr;
  461. for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
  462. Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
  463. unsigned ChildCountWithoutScopes = Children.size();
  464. for (LexicalScope *LS : Scope->getChildren())
  465. constructScopeDIE(LS, Children);
  466. if (ChildScopeCount)
  467. *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
  468. return ObjectPointer;
  469. }
  470. void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
  471. assert(Scope && Scope->getScopeNode());
  472. assert(!Scope->getInlinedAt());
  473. assert(!Scope->isAbstractScope());
  474. auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
  475. DD->getProcessedSPNodes().insert(Sub);
  476. DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
  477. // If this is a variadic function, add an unspecified parameter.
  478. DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
  479. // Collect lexical scope children first.
  480. // ObjectPointer might be a local (non-argument) local variable if it's a
  481. // block's synthetic this pointer.
  482. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
  483. addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  484. // If we have a single element of null, it is a function that returns void.
  485. // If we have more than one elements and the last one is null, it is a
  486. // variadic function.
  487. if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
  488. !includeMinimalInlineScopes())
  489. ScopeDIE.addChild(
  490. DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
  491. }
  492. DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
  493. DIE &ScopeDIE) {
  494. // We create children when the scope DIE is not null.
  495. SmallVector<DIE *, 8> Children;
  496. DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
  497. // Add children
  498. for (auto &I : Children)
  499. ScopeDIE.addChild(std::move(I));
  500. return ObjectPointer;
  501. }
  502. void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
  503. LexicalScope *Scope) {
  504. DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
  505. if (AbsDef)
  506. return;
  507. auto *SP = cast<DISubprogram>(Scope->getScopeNode());
  508. DIE *ContextDIE;
  509. if (includeMinimalInlineScopes())
  510. ContextDIE = &getUnitDie();
  511. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  512. // the important distinction that the debug node is not associated with the
  513. // DIE (since the debug node will be associated with the concrete DIE, if
  514. // any). It could be refactored to some common utility function.
  515. else if (auto *SPDecl = SP->getDeclaration()) {
  516. ContextDIE = &getUnitDie();
  517. getOrCreateSubprogramDIE(SPDecl);
  518. } else
  519. ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
  520. // Passing null as the associated node because the abstract definition
  521. // shouldn't be found by lookup.
  522. AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
  523. applySubprogramAttributesToDefinition(SP, *AbsDef);
  524. if (!includeMinimalInlineScopes())
  525. addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
  526. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
  527. addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
  528. }
  529. DIE *DwarfCompileUnit::constructImportedEntityDIE(
  530. const DIImportedEntity *Module) {
  531. DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
  532. insertDIE(Module, IMDie);
  533. DIE *EntityDie;
  534. auto *Entity = resolve(Module->getEntity());
  535. if (auto *NS = dyn_cast<DINamespace>(Entity))
  536. EntityDie = getOrCreateNameSpace(NS);
  537. else if (auto *M = dyn_cast<DIModule>(Entity))
  538. EntityDie = getOrCreateModule(M);
  539. else if (auto *SP = dyn_cast<DISubprogram>(Entity))
  540. EntityDie = getOrCreateSubprogramDIE(SP);
  541. else if (auto *T = dyn_cast<DIType>(Entity))
  542. EntityDie = getOrCreateTypeDIE(T);
  543. else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
  544. EntityDie = getOrCreateGlobalVariableDIE(GV, nullptr);
  545. else
  546. EntityDie = getDIE(Entity);
  547. assert(EntityDie);
  548. addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
  549. Module->getScope()->getDirectory());
  550. addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
  551. StringRef Name = Module->getName();
  552. if (!Name.empty())
  553. addString(*IMDie, dwarf::DW_AT_name, Name);
  554. return IMDie;
  555. }
  556. void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
  557. DIE *D = getDIE(SP);
  558. if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
  559. if (D)
  560. // If this subprogram has an abstract definition, reference that
  561. addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  562. } else {
  563. if (!D && !includeMinimalInlineScopes())
  564. // Lazily construct the subprogram if we didn't see either concrete or
  565. // inlined versions during codegen. (except in -gmlt ^ where we want
  566. // to omit these entirely)
  567. D = getOrCreateSubprogramDIE(SP);
  568. if (D)
  569. // And attach the attributes
  570. applySubprogramAttributesToDefinition(SP, *D);
  571. }
  572. }
  573. void DwarfCompileUnit::emitHeader(bool UseOffsets) {
  574. // Don't bother labeling the .dwo unit, as its offset isn't used.
  575. if (!Skeleton) {
  576. LabelBegin = Asm->createTempSymbol("cu_begin");
  577. Asm->OutStreamer->EmitLabel(LabelBegin);
  578. }
  579. DwarfUnit::emitHeader(UseOffsets);
  580. }
  581. /// addGlobalName - Add a new global name to the compile unit.
  582. void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
  583. const DIScope *Context) {
  584. if (includeMinimalInlineScopes())
  585. return;
  586. std::string FullName = getParentContextString(Context) + Name.str();
  587. GlobalNames[FullName] = &Die;
  588. }
  589. /// Add a new global type to the unit.
  590. void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
  591. const DIScope *Context) {
  592. if (includeMinimalInlineScopes())
  593. return;
  594. std::string FullName = getParentContextString(Context) + Ty->getName().str();
  595. GlobalTypes[FullName] = &Die;
  596. }
  597. /// addVariableAddress - Add DW_AT_location attribute for a
  598. /// DbgVariable based on provided MachineLocation.
  599. void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
  600. MachineLocation Location) {
  601. if (DV.hasComplexAddress())
  602. addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
  603. else if (DV.isBlockByrefVariable())
  604. addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
  605. else
  606. addAddress(Die, dwarf::DW_AT_location, Location);
  607. }
  608. /// Add an address attribute to a die based on the location provided.
  609. void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
  610. const MachineLocation &Location) {
  611. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  612. bool validReg;
  613. if (Location.isReg())
  614. validReg = addRegisterOpPiece(*Loc, Location.getReg());
  615. else
  616. validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
  617. if (!validReg)
  618. return;
  619. // Now attach the location information to the DIE.
  620. addBlock(Die, Attribute, Loc);
  621. }
  622. /// Start with the address based on the location provided, and generate the
  623. /// DWARF information necessary to find the actual variable given the extra
  624. /// address information encoded in the DbgVariable, starting from the starting
  625. /// location. Add the DWARF information to the die.
  626. void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
  627. dwarf::Attribute Attribute,
  628. const MachineLocation &Location) {
  629. DIELoc *Loc = new (DIEValueAllocator) DIELoc;
  630. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  631. const DIExpression *Expr = DV.getSingleExpression();
  632. bool ValidReg;
  633. const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
  634. if (Location.getOffset()) {
  635. ValidReg = DwarfExpr.AddMachineRegIndirect(TRI, Location.getReg(),
  636. Location.getOffset());
  637. if (ValidReg)
  638. DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
  639. } else
  640. ValidReg = DwarfExpr.AddMachineRegExpression(TRI, Expr, Location.getReg());
  641. // Now attach the location information to the DIE.
  642. if (ValidReg)
  643. addBlock(Die, Attribute, Loc);
  644. }
  645. /// Add a Dwarf loclistptr attribute data and value.
  646. void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
  647. unsigned Index) {
  648. dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  649. : dwarf::DW_FORM_data4;
  650. Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
  651. }
  652. void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
  653. DIE &VariableDie) {
  654. StringRef Name = Var.getName();
  655. if (!Name.empty())
  656. addString(VariableDie, dwarf::DW_AT_name, Name);
  657. addSourceLine(VariableDie, Var.getVariable());
  658. addType(VariableDie, Var.getType());
  659. if (Var.isArtificial())
  660. addFlag(VariableDie, dwarf::DW_AT_artificial);
  661. }
  662. /// Add a Dwarf expression attribute data and value.
  663. void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
  664. const MCExpr *Expr) {
  665. Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
  666. }
  667. void DwarfCompileUnit::applySubprogramAttributesToDefinition(
  668. const DISubprogram *SP, DIE &SPDie) {
  669. auto *SPDecl = SP->getDeclaration();
  670. auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
  671. applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
  672. addGlobalName(SP->getName(), SPDie, Context);
  673. }
  674. bool DwarfCompileUnit::isDwoUnit() const {
  675. return DD->useSplitDwarf() && Skeleton;
  676. }
  677. bool DwarfCompileUnit::includeMinimalInlineScopes() const {
  678. return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
  679. (DD->useSplitDwarf() && !Skeleton);
  680. }
  681. } // end llvm namespace