DebugHandlerBase.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. //===-- llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp -------*- C++ -*--===//
  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. // Common functionality for different debug information format backends.
  10. // LLVM currently supports DWARF and CodeView.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/DebugHandlerBase.h"
  14. #include "llvm/ADT/Optional.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/CodeGen/AsmPrinter.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/CodeGen/MachineInstr.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  21. #include "llvm/IR/DebugInfo.h"
  22. #include "llvm/MC/MCStreamer.h"
  23. using namespace llvm;
  24. #define DEBUG_TYPE "dwarfdebug"
  25. Optional<DbgVariableLocation>
  26. DbgVariableLocation::extractFromMachineInstruction(
  27. const MachineInstr &Instruction) {
  28. DbgVariableLocation Location;
  29. if (!Instruction.isDebugValue())
  30. return None;
  31. if (!Instruction.getOperand(0).isReg())
  32. return None;
  33. Location.Register = Instruction.getOperand(0).getReg();
  34. Location.FragmentInfo.reset();
  35. // We only handle expressions generated by DIExpression::appendOffset,
  36. // which doesn't require a full stack machine.
  37. int64_t Offset = 0;
  38. const DIExpression *DIExpr = Instruction.getDebugExpression();
  39. auto Op = DIExpr->expr_op_begin();
  40. while (Op != DIExpr->expr_op_end()) {
  41. switch (Op->getOp()) {
  42. case dwarf::DW_OP_constu: {
  43. int Value = Op->getArg(0);
  44. ++Op;
  45. if (Op != DIExpr->expr_op_end()) {
  46. switch (Op->getOp()) {
  47. case dwarf::DW_OP_minus:
  48. Offset -= Value;
  49. break;
  50. case dwarf::DW_OP_plus:
  51. Offset += Value;
  52. break;
  53. default:
  54. continue;
  55. }
  56. }
  57. } break;
  58. case dwarf::DW_OP_plus_uconst:
  59. Offset += Op->getArg(0);
  60. break;
  61. case dwarf::DW_OP_LLVM_fragment:
  62. Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
  63. break;
  64. case dwarf::DW_OP_deref:
  65. Location.LoadChain.push_back(Offset);
  66. Offset = 0;
  67. break;
  68. default:
  69. return None;
  70. }
  71. ++Op;
  72. }
  73. // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
  74. // instruction.
  75. // FIXME: Replace these with DIExpression.
  76. if (Instruction.isIndirectDebugValue())
  77. Location.LoadChain.push_back(Offset);
  78. return Location;
  79. }
  80. DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
  81. // Each LexicalScope has first instruction and last instruction to mark
  82. // beginning and end of a scope respectively. Create an inverse map that list
  83. // scopes starts (and ends) with an instruction. One instruction may start (or
  84. // end) multiple scopes. Ignore scopes that are not reachable.
  85. void DebugHandlerBase::identifyScopeMarkers() {
  86. SmallVector<LexicalScope *, 4> WorkList;
  87. WorkList.push_back(LScopes.getCurrentFunctionScope());
  88. while (!WorkList.empty()) {
  89. LexicalScope *S = WorkList.pop_back_val();
  90. const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
  91. if (!Children.empty())
  92. WorkList.append(Children.begin(), Children.end());
  93. if (S->isAbstractScope())
  94. continue;
  95. for (const InsnRange &R : S->getRanges()) {
  96. assert(R.first && "InsnRange does not have first instruction!");
  97. assert(R.second && "InsnRange does not have second instruction!");
  98. requestLabelBeforeInsn(R.first);
  99. requestLabelAfterInsn(R.second);
  100. }
  101. }
  102. }
  103. // Return Label preceding the instruction.
  104. MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
  105. MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
  106. assert(Label && "Didn't insert label before instruction");
  107. return Label;
  108. }
  109. // Return Label immediately following the instruction.
  110. MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
  111. return LabelsAfterInsn.lookup(MI);
  112. }
  113. // Return the function-local offset of an instruction.
  114. const MCExpr *
  115. DebugHandlerBase::getFunctionLocalOffsetAfterInsn(const MachineInstr *MI) {
  116. MCContext &MC = Asm->OutContext;
  117. MCSymbol *Start = Asm->getFunctionBegin();
  118. const auto *StartRef = MCSymbolRefExpr::create(Start, MC);
  119. MCSymbol *AfterInsn = getLabelAfterInsn(MI);
  120. assert(AfterInsn && "Expected label after instruction");
  121. const auto *AfterRef = MCSymbolRefExpr::create(AfterInsn, MC);
  122. return MCBinaryExpr::createSub(AfterRef, StartRef, MC);
  123. }
  124. /// If this type is derived from a base type then return base type size.
  125. uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
  126. assert(Ty);
  127. const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
  128. if (!DDTy)
  129. return Ty->getSizeInBits();
  130. unsigned Tag = DDTy->getTag();
  131. if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
  132. Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
  133. Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type)
  134. return DDTy->getSizeInBits();
  135. DIType *BaseType = DDTy->getBaseType();
  136. if (!BaseType)
  137. return 0;
  138. // If this is a derived type, go ahead and get the base type, unless it's a
  139. // reference then it's just the size of the field. Pointer types have no need
  140. // of this since they're a different type of qualification on the type.
  141. if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
  142. BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
  143. return Ty->getSizeInBits();
  144. return getBaseTypeSize(BaseType);
  145. }
  146. static bool hasDebugInfo(const MachineModuleInfo *MMI,
  147. const MachineFunction *MF) {
  148. if (!MMI->hasDebugInfo())
  149. return false;
  150. auto *SP = MF->getFunction().getSubprogram();
  151. if (!SP)
  152. return false;
  153. assert(SP->getUnit());
  154. auto EK = SP->getUnit()->getEmissionKind();
  155. if (EK == DICompileUnit::NoDebug)
  156. return false;
  157. return true;
  158. }
  159. void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
  160. PrevInstBB = nullptr;
  161. if (!Asm || !hasDebugInfo(MMI, MF)) {
  162. skippedNonDebugFunction();
  163. return;
  164. }
  165. // Grab the lexical scopes for the function, if we don't have any of those
  166. // then we're not going to be able to do anything.
  167. LScopes.initialize(*MF);
  168. if (LScopes.empty()) {
  169. beginFunctionImpl(MF);
  170. return;
  171. }
  172. // Make sure that each lexical scope will have a begin/end label.
  173. identifyScopeMarkers();
  174. // Calculate history for local variables.
  175. assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
  176. assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
  177. calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
  178. DbgValues, DbgLabels);
  179. LLVM_DEBUG(DbgValues.dump());
  180. // Request labels for the full history.
  181. for (const auto &I : DbgValues) {
  182. const auto &Entries = I.second;
  183. if (Entries.empty())
  184. continue;
  185. auto IsDescribedByReg = [](const MachineInstr *MI) {
  186. return MI->getOperand(0).isReg() && MI->getOperand(0).getReg();
  187. };
  188. // The first mention of a function argument gets the CurrentFnBegin label,
  189. // so arguments are visible when breaking at function entry.
  190. //
  191. // We do not change the label for values that are described by registers,
  192. // as that could place them above their defining instructions. We should
  193. // ideally not change the labels for constant debug values either, since
  194. // doing that violates the ranges that are calculated in the history map.
  195. // However, we currently do not emit debug values for constant arguments
  196. // directly at the start of the function, so this code is still useful.
  197. const DILocalVariable *DIVar =
  198. Entries.front().getInstr()->getDebugVariable();
  199. if (DIVar->isParameter() &&
  200. getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
  201. if (!IsDescribedByReg(Entries.front().getInstr()))
  202. LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
  203. if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
  204. // Mark all non-overlapping initial fragments.
  205. for (auto I = Entries.begin(); I != Entries.end(); ++I) {
  206. if (!I->isDbgValue())
  207. continue;
  208. const DIExpression *Fragment = I->getInstr()->getDebugExpression();
  209. if (std::any_of(Entries.begin(), I,
  210. [&](DbgValueHistoryMap::Entry Pred) {
  211. return Pred.isDbgValue() &&
  212. Fragment->fragmentsOverlap(
  213. Pred.getInstr()->getDebugExpression());
  214. }))
  215. break;
  216. if (!IsDescribedByReg(I->getInstr()))
  217. LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
  218. }
  219. }
  220. }
  221. for (const auto &Entry : Entries) {
  222. if (Entry.isDbgValue())
  223. requestLabelBeforeInsn(Entry.getInstr());
  224. else
  225. requestLabelAfterInsn(Entry.getInstr());
  226. }
  227. }
  228. // Ensure there is a symbol before DBG_LABEL.
  229. for (const auto &I : DbgLabels) {
  230. const MachineInstr *MI = I.second;
  231. requestLabelBeforeInsn(MI);
  232. }
  233. PrevInstLoc = DebugLoc();
  234. PrevLabel = Asm->getFunctionBegin();
  235. beginFunctionImpl(MF);
  236. }
  237. void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
  238. if (!MMI->hasDebugInfo())
  239. return;
  240. assert(CurMI == nullptr);
  241. CurMI = MI;
  242. // Insert labels where requested.
  243. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  244. LabelsBeforeInsn.find(MI);
  245. // No label needed.
  246. if (I == LabelsBeforeInsn.end())
  247. return;
  248. // Label already assigned.
  249. if (I->second)
  250. return;
  251. if (!PrevLabel) {
  252. PrevLabel = MMI->getContext().createTempSymbol();
  253. Asm->OutStreamer->EmitLabel(PrevLabel);
  254. }
  255. I->second = PrevLabel;
  256. }
  257. void DebugHandlerBase::endInstruction() {
  258. if (!MMI->hasDebugInfo())
  259. return;
  260. assert(CurMI != nullptr);
  261. // Don't create a new label after DBG_VALUE and other instructions that don't
  262. // generate code.
  263. if (!CurMI->isMetaInstruction()) {
  264. PrevLabel = nullptr;
  265. PrevInstBB = CurMI->getParent();
  266. }
  267. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  268. LabelsAfterInsn.find(CurMI);
  269. CurMI = nullptr;
  270. // No label needed.
  271. if (I == LabelsAfterInsn.end())
  272. return;
  273. // Label already assigned.
  274. if (I->second)
  275. return;
  276. // We need a label after this instruction.
  277. if (!PrevLabel) {
  278. PrevLabel = MMI->getContext().createTempSymbol();
  279. Asm->OutStreamer->EmitLabel(PrevLabel);
  280. }
  281. I->second = PrevLabel;
  282. }
  283. void DebugHandlerBase::endFunction(const MachineFunction *MF) {
  284. if (hasDebugInfo(MMI, MF))
  285. endFunctionImpl(MF);
  286. DbgValues.clear();
  287. DbgLabels.clear();
  288. LabelsBeforeInsn.clear();
  289. LabelsAfterInsn.clear();
  290. }