LexicalScopes.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //===- LexicalScopes.cpp - Collecting lexical scope info ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements LexicalScopes analysis.
  10. //
  11. // This pass collects lexical scope information and maps machine instructions
  12. // to respective lexical scopes.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/LexicalScopes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/CodeGen/MachineBasicBlock.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstr.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/DebugInfoMetadata.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/Metadata.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/Compiler.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <cassert>
  30. #include <string>
  31. #include <tuple>
  32. #include <utility>
  33. using namespace llvm;
  34. #define DEBUG_TYPE "lexicalscopes"
  35. /// reset - Reset the instance so that it's prepared for another function.
  36. void LexicalScopes::reset() {
  37. MF = nullptr;
  38. CurrentFnLexicalScope = nullptr;
  39. LexicalScopeMap.clear();
  40. AbstractScopeMap.clear();
  41. InlinedLexicalScopeMap.clear();
  42. AbstractScopesList.clear();
  43. DominatedBlocks.clear();
  44. }
  45. /// initialize - Scan machine function and constuct lexical scope nest.
  46. void LexicalScopes::initialize(const MachineFunction &Fn) {
  47. reset();
  48. // Don't attempt any lexical scope creation for a NoDebug compile unit.
  49. if (Fn.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  50. DICompileUnit::NoDebug)
  51. return;
  52. MF = &Fn;
  53. SmallVector<InsnRange, 4> MIRanges;
  54. DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;
  55. extractLexicalScopes(MIRanges, MI2ScopeMap);
  56. if (CurrentFnLexicalScope) {
  57. constructScopeNest(CurrentFnLexicalScope);
  58. assignInstructionRanges(MIRanges, MI2ScopeMap);
  59. }
  60. }
  61. /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
  62. /// for the given machine function.
  63. void LexicalScopes::extractLexicalScopes(
  64. SmallVectorImpl<InsnRange> &MIRanges,
  65. DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
  66. // Scan each instruction and create scopes. First build working set of scopes.
  67. for (const auto &MBB : *MF) {
  68. const MachineInstr *RangeBeginMI = nullptr;
  69. const MachineInstr *PrevMI = nullptr;
  70. const DILocation *PrevDL = nullptr;
  71. for (const auto &MInsn : MBB) {
  72. // Ignore DBG_VALUE and similar instruction that do not contribute to any
  73. // instruction in the output.
  74. if (MInsn.isMetaInstruction())
  75. continue;
  76. // Check if instruction has valid location information.
  77. const DILocation *MIDL = MInsn.getDebugLoc();
  78. if (!MIDL) {
  79. PrevMI = &MInsn;
  80. continue;
  81. }
  82. // If scope has not changed then skip this instruction.
  83. if (MIDL == PrevDL) {
  84. PrevMI = &MInsn;
  85. continue;
  86. }
  87. if (RangeBeginMI) {
  88. // If we have already seen a beginning of an instruction range and
  89. // current instruction scope does not match scope of first instruction
  90. // in this range then create a new instruction range.
  91. InsnRange R(RangeBeginMI, PrevMI);
  92. MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
  93. MIRanges.push_back(R);
  94. }
  95. // This is a beginning of a new instruction range.
  96. RangeBeginMI = &MInsn;
  97. // Reset previous markers.
  98. PrevMI = &MInsn;
  99. PrevDL = MIDL;
  100. }
  101. // Create last instruction range.
  102. if (RangeBeginMI && PrevMI && PrevDL) {
  103. InsnRange R(RangeBeginMI, PrevMI);
  104. MIRanges.push_back(R);
  105. MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
  106. }
  107. }
  108. }
  109. /// findLexicalScope - Find lexical scope, either regular or inlined, for the
  110. /// given DebugLoc. Return NULL if not found.
  111. LexicalScope *LexicalScopes::findLexicalScope(const DILocation *DL) {
  112. DILocalScope *Scope = DL->getScope();
  113. if (!Scope)
  114. return nullptr;
  115. // The scope that we were created with could have an extra file - which
  116. // isn't what we care about in this case.
  117. Scope = Scope->getNonLexicalBlockFileScope();
  118. if (auto *IA = DL->getInlinedAt()) {
  119. auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
  120. return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
  121. }
  122. return findLexicalScope(Scope);
  123. }
  124. /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
  125. /// not available then create new lexical scope.
  126. LexicalScope *LexicalScopes::getOrCreateLexicalScope(const DILocalScope *Scope,
  127. const DILocation *IA) {
  128. if (IA) {
  129. // Skip scopes inlined from a NoDebug compile unit.
  130. if (Scope->getSubprogram()->getUnit()->getEmissionKind() ==
  131. DICompileUnit::NoDebug)
  132. return getOrCreateLexicalScope(IA);
  133. // Create an abstract scope for inlined function.
  134. getOrCreateAbstractScope(Scope);
  135. // Create an inlined scope for inlined function.
  136. return getOrCreateInlinedScope(Scope, IA);
  137. }
  138. return getOrCreateRegularScope(Scope);
  139. }
  140. /// getOrCreateRegularScope - Find or create a regular lexical scope.
  141. LexicalScope *
  142. LexicalScopes::getOrCreateRegularScope(const DILocalScope *Scope) {
  143. assert(Scope && "Invalid Scope encoding!");
  144. Scope = Scope->getNonLexicalBlockFileScope();
  145. auto I = LexicalScopeMap.find(Scope);
  146. if (I != LexicalScopeMap.end())
  147. return &I->second;
  148. // FIXME: Should the following dyn_cast be DILexicalBlock?
  149. LexicalScope *Parent = nullptr;
  150. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  151. Parent = getOrCreateLexicalScope(Block->getScope());
  152. I = LexicalScopeMap.emplace(std::piecewise_construct,
  153. std::forward_as_tuple(Scope),
  154. std::forward_as_tuple(Parent, Scope, nullptr,
  155. false)).first;
  156. if (!Parent) {
  157. assert(cast<DISubprogram>(Scope)->describes(&MF->getFunction()));
  158. assert(!CurrentFnLexicalScope);
  159. CurrentFnLexicalScope = &I->second;
  160. }
  161. return &I->second;
  162. }
  163. /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
  164. LexicalScope *
  165. LexicalScopes::getOrCreateInlinedScope(const DILocalScope *Scope,
  166. const DILocation *InlinedAt) {
  167. assert(Scope && "Invalid Scope encoding!");
  168. Scope = Scope->getNonLexicalBlockFileScope();
  169. std::pair<const DILocalScope *, const DILocation *> P(Scope, InlinedAt);
  170. auto I = InlinedLexicalScopeMap.find(P);
  171. if (I != InlinedLexicalScopeMap.end())
  172. return &I->second;
  173. LexicalScope *Parent;
  174. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  175. Parent = getOrCreateInlinedScope(Block->getScope(), InlinedAt);
  176. else
  177. Parent = getOrCreateLexicalScope(InlinedAt);
  178. I = InlinedLexicalScopeMap
  179. .emplace(std::piecewise_construct, std::forward_as_tuple(P),
  180. std::forward_as_tuple(Parent, Scope, InlinedAt, false))
  181. .first;
  182. return &I->second;
  183. }
  184. /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
  185. LexicalScope *
  186. LexicalScopes::getOrCreateAbstractScope(const DILocalScope *Scope) {
  187. assert(Scope && "Invalid Scope encoding!");
  188. Scope = Scope->getNonLexicalBlockFileScope();
  189. auto I = AbstractScopeMap.find(Scope);
  190. if (I != AbstractScopeMap.end())
  191. return &I->second;
  192. // FIXME: Should the following isa be DILexicalBlock?
  193. LexicalScope *Parent = nullptr;
  194. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  195. Parent = getOrCreateAbstractScope(Block->getScope());
  196. I = AbstractScopeMap.emplace(std::piecewise_construct,
  197. std::forward_as_tuple(Scope),
  198. std::forward_as_tuple(Parent, Scope,
  199. nullptr, true)).first;
  200. if (isa<DISubprogram>(Scope))
  201. AbstractScopesList.push_back(&I->second);
  202. return &I->second;
  203. }
  204. /// constructScopeNest - Traverse the Scope tree depth-first, storing
  205. /// traversal state in WorkStack and recording the depth-first
  206. /// numbering (setDFSIn, setDFSOut) for edge classification.
  207. void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
  208. assert(Scope && "Unable to calculate scope dominance graph!");
  209. SmallVector<std::pair<LexicalScope *, size_t>, 4> WorkStack;
  210. WorkStack.push_back(std::make_pair(Scope, 0));
  211. unsigned Counter = 0;
  212. while (!WorkStack.empty()) {
  213. auto &ScopePosition = WorkStack.back();
  214. LexicalScope *WS = ScopePosition.first;
  215. size_t ChildNum = ScopePosition.second++;
  216. const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
  217. if (ChildNum < Children.size()) {
  218. auto &ChildScope = Children[ChildNum];
  219. WorkStack.push_back(std::make_pair(ChildScope, 0));
  220. ChildScope->setDFSIn(++Counter);
  221. } else {
  222. WorkStack.pop_back();
  223. WS->setDFSOut(++Counter);
  224. }
  225. }
  226. }
  227. /// assignInstructionRanges - Find ranges of instructions covered by each
  228. /// lexical scope.
  229. void LexicalScopes::assignInstructionRanges(
  230. SmallVectorImpl<InsnRange> &MIRanges,
  231. DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
  232. LexicalScope *PrevLexicalScope = nullptr;
  233. for (const auto &R : MIRanges) {
  234. LexicalScope *S = MI2ScopeMap.lookup(R.first);
  235. assert(S && "Lost LexicalScope for a machine instruction!");
  236. if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
  237. PrevLexicalScope->closeInsnRange(S);
  238. S->openInsnRange(R.first);
  239. S->extendInsnRange(R.second);
  240. PrevLexicalScope = S;
  241. }
  242. if (PrevLexicalScope)
  243. PrevLexicalScope->closeInsnRange();
  244. }
  245. /// getMachineBasicBlocks - Populate given set using machine basic blocks which
  246. /// have machine instructions that belong to lexical scope identified by
  247. /// DebugLoc.
  248. void LexicalScopes::getMachineBasicBlocks(
  249. const DILocation *DL, SmallPtrSetImpl<const MachineBasicBlock *> &MBBs) {
  250. assert(MF && "Method called on a uninitialized LexicalScopes object!");
  251. MBBs.clear();
  252. LexicalScope *Scope = getOrCreateLexicalScope(DL);
  253. if (!Scope)
  254. return;
  255. if (Scope == CurrentFnLexicalScope) {
  256. for (const auto &MBB : *MF)
  257. MBBs.insert(&MBB);
  258. return;
  259. }
  260. // The scope ranges can cover multiple basic blocks in each span. Iterate over
  261. // all blocks (in the order they are in the function) until we reach the one
  262. // containing the end of the span.
  263. SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
  264. for (auto &R : InsnRanges)
  265. for (auto CurMBBIt = R.first->getParent()->getIterator(),
  266. EndBBIt = std::next(R.second->getParent()->getIterator());
  267. CurMBBIt != EndBBIt; CurMBBIt++)
  268. MBBs.insert(&*CurMBBIt);
  269. }
  270. bool LexicalScopes::dominates(const DILocation *DL, MachineBasicBlock *MBB) {
  271. assert(MF && "Unexpected uninitialized LexicalScopes object!");
  272. LexicalScope *Scope = getOrCreateLexicalScope(DL);
  273. if (!Scope)
  274. return false;
  275. // Current function scope covers all basic blocks in the function.
  276. if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
  277. return true;
  278. // Fetch all the blocks in DLs scope. Because the range / block list also
  279. // contain any subscopes, any instruction that DL dominates can be found in
  280. // the block set.
  281. //
  282. // Cache the set of fetched blocks to avoid repeatedly recomputing the set in
  283. // the LiveDebugValues pass.
  284. std::unique_ptr<BlockSetT> &Set = DominatedBlocks[DL];
  285. if (!Set) {
  286. Set = std::make_unique<BlockSetT>();
  287. getMachineBasicBlocks(DL, *Set);
  288. }
  289. return Set->contains(MBB);
  290. }
  291. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  292. LLVM_DUMP_METHOD void LexicalScope::dump(unsigned Indent) const {
  293. raw_ostream &err = dbgs();
  294. err.indent(Indent);
  295. err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
  296. const MDNode *N = Desc;
  297. err.indent(Indent);
  298. N->dump();
  299. if (AbstractScope)
  300. err << std::string(Indent, ' ') << "Abstract Scope\n";
  301. if (!Children.empty())
  302. err << std::string(Indent + 2, ' ') << "Children ...\n";
  303. for (unsigned i = 0, e = Children.size(); i != e; ++i)
  304. if (Children[i] != this)
  305. Children[i]->dump(Indent + 2);
  306. }
  307. #endif