DebugHandlerBase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. #include "llvm/Support/CommandLine.h"
  24. using namespace llvm;
  25. #define DEBUG_TYPE "dwarfdebug"
  26. /// If true, we drop variable location ranges which exist entirely outside the
  27. /// variable's lexical scope instruction ranges.
  28. static cl::opt<bool> TrimVarLocs("trim-var-locs", cl::Hidden, cl::init(true));
  29. Optional<DbgVariableLocation>
  30. DbgVariableLocation::extractFromMachineInstruction(
  31. const MachineInstr &Instruction) {
  32. DbgVariableLocation Location;
  33. // Variables calculated from multiple locations can't be represented here.
  34. if (Instruction.getNumDebugOperands() != 1)
  35. return None;
  36. if (!Instruction.getDebugOperand(0).isReg())
  37. return None;
  38. Location.Register = Instruction.getDebugOperand(0).getReg();
  39. Location.FragmentInfo.reset();
  40. // We only handle expressions generated by DIExpression::appendOffset,
  41. // which doesn't require a full stack machine.
  42. int64_t Offset = 0;
  43. const DIExpression *DIExpr = Instruction.getDebugExpression();
  44. auto Op = DIExpr->expr_op_begin();
  45. // We can handle a DBG_VALUE_LIST iff it has exactly one location operand that
  46. // appears exactly once at the start of the expression.
  47. if (Instruction.isDebugValueList()) {
  48. if (Instruction.getNumDebugOperands() == 1 &&
  49. Op->getOp() == dwarf::DW_OP_LLVM_arg)
  50. ++Op;
  51. else
  52. return None;
  53. }
  54. while (Op != DIExpr->expr_op_end()) {
  55. switch (Op->getOp()) {
  56. case dwarf::DW_OP_constu: {
  57. int Value = Op->getArg(0);
  58. ++Op;
  59. if (Op != DIExpr->expr_op_end()) {
  60. switch (Op->getOp()) {
  61. case dwarf::DW_OP_minus:
  62. Offset -= Value;
  63. break;
  64. case dwarf::DW_OP_plus:
  65. Offset += Value;
  66. break;
  67. default:
  68. continue;
  69. }
  70. }
  71. } break;
  72. case dwarf::DW_OP_plus_uconst:
  73. Offset += Op->getArg(0);
  74. break;
  75. case dwarf::DW_OP_LLVM_fragment:
  76. Location.FragmentInfo = {Op->getArg(1), Op->getArg(0)};
  77. break;
  78. case dwarf::DW_OP_deref:
  79. Location.LoadChain.push_back(Offset);
  80. Offset = 0;
  81. break;
  82. default:
  83. return None;
  84. }
  85. ++Op;
  86. }
  87. // Do one final implicit DW_OP_deref if this was an indirect DBG_VALUE
  88. // instruction.
  89. // FIXME: Replace these with DIExpression.
  90. if (Instruction.isIndirectDebugValue())
  91. Location.LoadChain.push_back(Offset);
  92. return Location;
  93. }
  94. DebugHandlerBase::DebugHandlerBase(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
  95. void DebugHandlerBase::beginModule(Module *M) {
  96. if (M->debug_compile_units().empty())
  97. Asm = nullptr;
  98. }
  99. // Each LexicalScope has first instruction and last instruction to mark
  100. // beginning and end of a scope respectively. Create an inverse map that list
  101. // scopes starts (and ends) with an instruction. One instruction may start (or
  102. // end) multiple scopes. Ignore scopes that are not reachable.
  103. void DebugHandlerBase::identifyScopeMarkers() {
  104. SmallVector<LexicalScope *, 4> WorkList;
  105. WorkList.push_back(LScopes.getCurrentFunctionScope());
  106. while (!WorkList.empty()) {
  107. LexicalScope *S = WorkList.pop_back_val();
  108. const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
  109. if (!Children.empty())
  110. WorkList.append(Children.begin(), Children.end());
  111. if (S->isAbstractScope())
  112. continue;
  113. for (const InsnRange &R : S->getRanges()) {
  114. assert(R.first && "InsnRange does not have first instruction!");
  115. assert(R.second && "InsnRange does not have second instruction!");
  116. requestLabelBeforeInsn(R.first);
  117. requestLabelAfterInsn(R.second);
  118. }
  119. }
  120. }
  121. // Return Label preceding the instruction.
  122. MCSymbol *DebugHandlerBase::getLabelBeforeInsn(const MachineInstr *MI) {
  123. MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
  124. assert(Label && "Didn't insert label before instruction");
  125. return Label;
  126. }
  127. // Return Label immediately following the instruction.
  128. MCSymbol *DebugHandlerBase::getLabelAfterInsn(const MachineInstr *MI) {
  129. return LabelsAfterInsn.lookup(MI);
  130. }
  131. /// If this type is derived from a base type then return base type size.
  132. uint64_t DebugHandlerBase::getBaseTypeSize(const DIType *Ty) {
  133. assert(Ty);
  134. const DIDerivedType *DDTy = dyn_cast<DIDerivedType>(Ty);
  135. if (!DDTy)
  136. return Ty->getSizeInBits();
  137. unsigned Tag = DDTy->getTag();
  138. if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
  139. Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
  140. Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_atomic_type &&
  141. Tag != dwarf::DW_TAG_immutable_type)
  142. return DDTy->getSizeInBits();
  143. DIType *BaseType = DDTy->getBaseType();
  144. if (!BaseType)
  145. return 0;
  146. // If this is a derived type, go ahead and get the base type, unless it's a
  147. // reference then it's just the size of the field. Pointer types have no need
  148. // of this since they're a different type of qualification on the type.
  149. if (BaseType->getTag() == dwarf::DW_TAG_reference_type ||
  150. BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type)
  151. return Ty->getSizeInBits();
  152. return getBaseTypeSize(BaseType);
  153. }
  154. bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) {
  155. if (isa<DIStringType>(Ty)) {
  156. // Some transformations (e.g. instcombine) may decide to turn a Fortran
  157. // character object into an integer, and later ones (e.g. SROA) may
  158. // further inject a constant integer in a llvm.dbg.value call to track
  159. // the object's value. Here we trust the transformations are doing the
  160. // right thing, and treat the constant as unsigned to preserve that value
  161. // (i.e. avoid sign extension).
  162. return true;
  163. }
  164. if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
  165. if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) {
  166. if (!(Ty = CTy->getBaseType()))
  167. // FIXME: Enums without a fixed underlying type have unknown signedness
  168. // here, leading to incorrectly emitted constants.
  169. return false;
  170. } else
  171. // (Pieces of) aggregate types that get hacked apart by SROA may be
  172. // represented by a constant. Encode them as unsigned bytes.
  173. return true;
  174. }
  175. if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
  176. dwarf::Tag T = (dwarf::Tag)Ty->getTag();
  177. // Encode pointer constants as unsigned bytes. This is used at least for
  178. // null pointer constant emission.
  179. // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed
  180. // here, but accept them for now due to a bug in SROA producing bogus
  181. // dbg.values.
  182. if (T == dwarf::DW_TAG_pointer_type ||
  183. T == dwarf::DW_TAG_ptr_to_member_type ||
  184. T == dwarf::DW_TAG_reference_type ||
  185. T == dwarf::DW_TAG_rvalue_reference_type)
  186. return true;
  187. assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type ||
  188. T == dwarf::DW_TAG_volatile_type ||
  189. T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type ||
  190. T == dwarf::DW_TAG_immutable_type);
  191. assert(DTy->getBaseType() && "Expected valid base type");
  192. return isUnsignedDIType(DTy->getBaseType());
  193. }
  194. auto *BTy = cast<DIBasicType>(Ty);
  195. unsigned Encoding = BTy->getEncoding();
  196. assert((Encoding == dwarf::DW_ATE_unsigned ||
  197. Encoding == dwarf::DW_ATE_unsigned_char ||
  198. Encoding == dwarf::DW_ATE_signed ||
  199. Encoding == dwarf::DW_ATE_signed_char ||
  200. Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
  201. Encoding == dwarf::DW_ATE_boolean ||
  202. (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
  203. Ty->getName() == "decltype(nullptr)")) &&
  204. "Unsupported encoding");
  205. return Encoding == dwarf::DW_ATE_unsigned ||
  206. Encoding == dwarf::DW_ATE_unsigned_char ||
  207. Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
  208. Ty->getTag() == dwarf::DW_TAG_unspecified_type;
  209. }
  210. static bool hasDebugInfo(const MachineModuleInfo *MMI,
  211. const MachineFunction *MF) {
  212. if (!MMI->hasDebugInfo())
  213. return false;
  214. auto *SP = MF->getFunction().getSubprogram();
  215. if (!SP)
  216. return false;
  217. assert(SP->getUnit());
  218. auto EK = SP->getUnit()->getEmissionKind();
  219. if (EK == DICompileUnit::NoDebug)
  220. return false;
  221. return true;
  222. }
  223. void DebugHandlerBase::beginFunction(const MachineFunction *MF) {
  224. PrevInstBB = nullptr;
  225. if (!Asm || !hasDebugInfo(MMI, MF)) {
  226. skippedNonDebugFunction();
  227. return;
  228. }
  229. // Grab the lexical scopes for the function, if we don't have any of those
  230. // then we're not going to be able to do anything.
  231. LScopes.initialize(*MF);
  232. if (LScopes.empty()) {
  233. beginFunctionImpl(MF);
  234. return;
  235. }
  236. // Make sure that each lexical scope will have a begin/end label.
  237. identifyScopeMarkers();
  238. // Calculate history for local variables.
  239. assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
  240. assert(DbgLabels.empty() && "DbgLabels map wasn't cleaned!");
  241. calculateDbgEntityHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
  242. DbgValues, DbgLabels);
  243. InstOrdering.initialize(*MF);
  244. if (TrimVarLocs)
  245. DbgValues.trimLocationRanges(*MF, LScopes, InstOrdering);
  246. LLVM_DEBUG(DbgValues.dump());
  247. // Request labels for the full history.
  248. for (const auto &I : DbgValues) {
  249. const auto &Entries = I.second;
  250. if (Entries.empty())
  251. continue;
  252. auto IsDescribedByReg = [](const MachineInstr *MI) {
  253. return any_of(MI->debug_operands(),
  254. [](auto &MO) { return MO.isReg() && MO.getReg(); });
  255. };
  256. // The first mention of a function argument gets the CurrentFnBegin label,
  257. // so arguments are visible when breaking at function entry.
  258. //
  259. // We do not change the label for values that are described by registers,
  260. // as that could place them above their defining instructions. We should
  261. // ideally not change the labels for constant debug values either, since
  262. // doing that violates the ranges that are calculated in the history map.
  263. // However, we currently do not emit debug values for constant arguments
  264. // directly at the start of the function, so this code is still useful.
  265. const DILocalVariable *DIVar =
  266. Entries.front().getInstr()->getDebugVariable();
  267. if (DIVar->isParameter() &&
  268. getDISubprogram(DIVar->getScope())->describes(&MF->getFunction())) {
  269. if (!IsDescribedByReg(Entries.front().getInstr()))
  270. LabelsBeforeInsn[Entries.front().getInstr()] = Asm->getFunctionBegin();
  271. if (Entries.front().getInstr()->getDebugExpression()->isFragment()) {
  272. // Mark all non-overlapping initial fragments.
  273. for (auto I = Entries.begin(); I != Entries.end(); ++I) {
  274. if (!I->isDbgValue())
  275. continue;
  276. const DIExpression *Fragment = I->getInstr()->getDebugExpression();
  277. if (std::any_of(Entries.begin(), I,
  278. [&](DbgValueHistoryMap::Entry Pred) {
  279. return Pred.isDbgValue() &&
  280. Fragment->fragmentsOverlap(
  281. Pred.getInstr()->getDebugExpression());
  282. }))
  283. break;
  284. // The code that generates location lists for DWARF assumes that the
  285. // entries' start labels are monotonically increasing, and since we
  286. // don't change the label for fragments that are described by
  287. // registers, we must bail out when encountering such a fragment.
  288. if (IsDescribedByReg(I->getInstr()))
  289. break;
  290. LabelsBeforeInsn[I->getInstr()] = Asm->getFunctionBegin();
  291. }
  292. }
  293. }
  294. for (const auto &Entry : Entries) {
  295. if (Entry.isDbgValue())
  296. requestLabelBeforeInsn(Entry.getInstr());
  297. else
  298. requestLabelAfterInsn(Entry.getInstr());
  299. }
  300. }
  301. // Ensure there is a symbol before DBG_LABEL.
  302. for (const auto &I : DbgLabels) {
  303. const MachineInstr *MI = I.second;
  304. requestLabelBeforeInsn(MI);
  305. }
  306. PrevInstLoc = DebugLoc();
  307. PrevLabel = Asm->getFunctionBegin();
  308. beginFunctionImpl(MF);
  309. }
  310. void DebugHandlerBase::beginInstruction(const MachineInstr *MI) {
  311. if (!Asm || !MMI->hasDebugInfo())
  312. return;
  313. assert(CurMI == nullptr);
  314. CurMI = MI;
  315. // Insert labels where requested.
  316. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  317. LabelsBeforeInsn.find(MI);
  318. // No label needed.
  319. if (I == LabelsBeforeInsn.end())
  320. return;
  321. // Label already assigned.
  322. if (I->second)
  323. return;
  324. if (!PrevLabel) {
  325. PrevLabel = MMI->getContext().createTempSymbol();
  326. Asm->OutStreamer->emitLabel(PrevLabel);
  327. }
  328. I->second = PrevLabel;
  329. }
  330. void DebugHandlerBase::endInstruction() {
  331. if (!Asm || !MMI->hasDebugInfo())
  332. return;
  333. assert(CurMI != nullptr);
  334. // Don't create a new label after DBG_VALUE and other instructions that don't
  335. // generate code.
  336. if (!CurMI->isMetaInstruction()) {
  337. PrevLabel = nullptr;
  338. PrevInstBB = CurMI->getParent();
  339. }
  340. DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
  341. LabelsAfterInsn.find(CurMI);
  342. // No label needed or label already assigned.
  343. if (I == LabelsAfterInsn.end() || I->second) {
  344. CurMI = nullptr;
  345. return;
  346. }
  347. // We need a label after this instruction. With basic block sections, just
  348. // use the end symbol of the section if this is the last instruction of the
  349. // section. This reduces the need for an additional label and also helps
  350. // merging ranges.
  351. if (CurMI->getParent()->isEndSection() && CurMI->getNextNode() == nullptr) {
  352. PrevLabel = CurMI->getParent()->getEndSymbol();
  353. } else if (!PrevLabel) {
  354. PrevLabel = MMI->getContext().createTempSymbol();
  355. Asm->OutStreamer->emitLabel(PrevLabel);
  356. }
  357. I->second = PrevLabel;
  358. CurMI = nullptr;
  359. }
  360. void DebugHandlerBase::endFunction(const MachineFunction *MF) {
  361. if (Asm && hasDebugInfo(MMI, MF))
  362. endFunctionImpl(MF);
  363. DbgValues.clear();
  364. DbgLabels.clear();
  365. LabelsBeforeInsn.clear();
  366. LabelsAfterInsn.clear();
  367. InstOrdering.clear();
  368. }
  369. void DebugHandlerBase::beginBasicBlock(const MachineBasicBlock &MBB) {
  370. if (!MBB.isBeginSection())
  371. return;
  372. PrevLabel = MBB.getSymbol();
  373. }
  374. void DebugHandlerBase::endBasicBlock(const MachineBasicBlock &MBB) {
  375. if (!MBB.isEndSection())
  376. return;
  377. PrevLabel = nullptr;
  378. }