DwarfCompileUnit.cpp 31 KB

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