LLVM 24.0.0git
LexicalScopes.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/DenseMap.h"
22#include "llvm/Config/llvm-config.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/Metadata.h"
28#include "llvm/Support/Debug.h"
30#include <cassert>
31#include <string>
32#include <tuple>
33#include <utility>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "lexicalscopes"
38
39static bool skipUnit(const DICompileUnit *CU) {
40 return CU->getEmissionKind() == DICompileUnit::NoDebug;
41}
42
44 MF = nullptr;
45 CurrentFnLexicalScope = nullptr;
46 LexicalScopeMap.clear();
47 AbstractScopeMap.clear();
48 InlinedLexicalScopeMap.clear();
49 AbstractScopesList.clear();
50 DominatedBlocks.clear();
51}
52
55 // Don't attempt any lexical scope creation for a NoDebug compile unit.
56 if (skipUnit(Fn.getFunction().getSubprogram()->getUnit()))
57 return;
58 MF = &Fn;
60 extractLexicalScopes(MIRanges);
61 if (CurrentFnLexicalScope) {
62 constructScopeNest(CurrentFnLexicalScope);
63 assignInstructionRanges(MIRanges);
64 }
65}
66
67/// extractLexicalScopes - Extract instruction ranges for each lexical scopes
68/// for the given machine function.
69void LexicalScopes::extractLexicalScopes(
70 SmallVectorImpl<std::pair<InsnRange, LexicalScope *>> &MIRanges) {
71 // Scan each instruction and create scopes. First build working set of scopes.
72 for (const auto &MBB : *MF) {
73 const MachineInstr *RangeBeginMI = nullptr;
74 const MachineInstr *PrevMI = nullptr;
75 const DILocation *PrevDL = nullptr;
76 for (const auto &MInsn : MBB) {
77 // Ignore DBG_VALUE and similar instruction that do not contribute to any
78 // instruction in the output.
79 if (MInsn.isMetaInstruction())
80 continue;
81
82 // Check if instruction has valid location information.
83 const DILocation *MIDL = MInsn.getDebugLoc();
84 if (!MIDL) {
85 PrevMI = &MInsn;
86 continue;
87 }
88
89 // If scope has not changed then skip this instruction.
90 if (MIDL == PrevDL) {
91 PrevMI = &MInsn;
92 continue;
93 }
94
95 if (RangeBeginMI) {
96 // If we have already seen a beginning of an instruction range and
97 // current instruction scope does not match scope of first instruction
98 // in this range then create a new instruction range.
99 MIRanges.push_back(
100 {InsnRange(RangeBeginMI, PrevMI), getOrCreateLexicalScope(PrevDL)});
101 }
102
103 // This is a beginning of a new instruction range.
104 RangeBeginMI = &MInsn;
105
106 // Reset previous markers.
107 PrevMI = &MInsn;
108 PrevDL = MIDL;
109 }
110
111 // Create last instruction range.
112 if (RangeBeginMI && PrevMI && PrevDL)
113 MIRanges.push_back(
114 {InsnRange(RangeBeginMI, PrevMI), getOrCreateLexicalScope(PrevDL)});
115 }
116}
117
118/// findLexicalScope - Find lexical scope, either regular or inlined, for the
119/// given DebugLoc. Return NULL if not found.
121 DILocalScope *Scope = DL->getScope();
122 if (!Scope)
123 return nullptr;
124
125 // The scope that we were created with could have an extra file - which
126 // isn't what we care about in this case.
127 Scope = Scope->getNonLexicalBlockFileScope();
128
129 if (auto *IA = DL->getInlinedAt()) {
130 auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
131 return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
132 }
133 return findLexicalScope(Scope);
134}
135
136/// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
137/// not available then create new lexical scope.
138LexicalScope *LexicalScopes::getOrCreateLexicalScope(const DILocalScope *Scope,
139 const DILocation *IA) {
140 if (IA) {
141 // Skip scopes inlined from a NoDebug compile unit.
142 if (skipUnit(Scope->getSubprogram()->getUnit()))
143 return getOrCreateLexicalScope(IA);
144 // Create an abstract scope for inlined function.
146 // Create an inlined scope for inlined function.
147 return getOrCreateInlinedScope(Scope, IA);
148 }
149
150 return getOrCreateRegularScope(Scope);
151}
152
153/// getOrCreateRegularScope - Find or create a regular lexical scope.
155LexicalScopes::getOrCreateRegularScope(const DILocalScope *Scope) {
156 assert(Scope && "Invalid Scope encoding!");
157 Scope = Scope->getNonLexicalBlockFileScope();
158
159 auto I = LexicalScopeMap.find(Scope);
160 if (I != LexicalScopeMap.end())
161 return &I->second;
162
163 // FIXME: Should the following dyn_cast be DILexicalBlock?
164 LexicalScope *Parent = nullptr;
165 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
166 Parent = getOrCreateLexicalScope(Block->getScope());
167 I = LexicalScopeMap.emplace(std::piecewise_construct,
168 std::forward_as_tuple(Scope),
169 std::forward_as_tuple(Parent, Scope, nullptr,
170 false)).first;
171
172 if (!Parent) {
173 assert(cast<DISubprogram>(Scope)->describes(&MF->getFunction()));
174 assert(!CurrentFnLexicalScope);
175 CurrentFnLexicalScope = &I->second;
176 }
177
178 return &I->second;
179}
180
181/// getOrCreateInlinedScope - Find or create an inlined lexical scope.
183LexicalScopes::getOrCreateInlinedScope(const DILocalScope *Scope,
184 const DILocation *InlinedAt) {
185 assert(Scope && "Invalid Scope encoding!");
186 Scope = Scope->getNonLexicalBlockFileScope();
187 std::pair<const DILocalScope *, const DILocation *> P(Scope, InlinedAt);
188 auto I = InlinedLexicalScopeMap.find(P);
189 if (I != InlinedLexicalScopeMap.end())
190 return &I->second;
191
192 LexicalScope *Parent;
193 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
194 Parent = getOrCreateInlinedScope(Block->getScope(), InlinedAt);
195 else
196 Parent = getOrCreateLexicalScope(InlinedAt);
197
198 I = InlinedLexicalScopeMap
199 .emplace(std::piecewise_construct, std::forward_as_tuple(P),
200 std::forward_as_tuple(Parent, Scope, InlinedAt, false))
201 .first;
202 return &I->second;
203}
204
205/// getOrCreateAbstractScope - Find or create an abstract lexical scope.
208 assert(Scope && "Invalid Scope encoding!");
209 Scope = Scope->getNonLexicalBlockFileScope();
210 auto I = AbstractScopeMap.find(Scope);
211 if (I != AbstractScopeMap.end())
212 return &I->second;
213
214 // FIXME: Should the following isa be DILexicalBlock?
215 LexicalScope *Parent = nullptr;
216 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
217 Parent = getOrCreateAbstractScope(Block->getScope());
218
219 I = AbstractScopeMap.emplace(std::piecewise_construct,
220 std::forward_as_tuple(Scope),
221 std::forward_as_tuple(Parent, Scope,
222 nullptr, true)).first;
223 if (isa<DISubprogram>(Scope))
224 AbstractScopesList.push_back(&I->second);
225 return &I->second;
226}
227
228/// constructScopeNest - Traverse the Scope tree depth-first, storing
229/// traversal state in WorkStack and recording the depth-first
230/// numbering (setDFSIn, setDFSOut) for edge classification.
231void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
232 assert(Scope && "Unable to calculate scope dominance graph!");
234 WorkStack.push_back(std::make_pair(Scope, 0));
235 unsigned Counter = 0;
236 while (!WorkStack.empty()) {
237 auto &ScopePosition = WorkStack.back();
238 LexicalScope *WS = ScopePosition.first;
239 size_t ChildNum = ScopePosition.second++;
240 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
241 if (ChildNum < Children.size()) {
242 auto &ChildScope = Children[ChildNum];
243 WorkStack.push_back(std::make_pair(ChildScope, 0));
244 ChildScope->setDFSIn(++Counter);
245 } else {
246 WorkStack.pop_back();
247 WS->setDFSOut(++Counter);
248 }
249 }
250}
251
252/// assignInstructionRanges - Find ranges of instructions covered by each
253/// lexical scope.
254void LexicalScopes::assignInstructionRanges(
255 ArrayRef<std::pair<InsnRange, LexicalScope *>> MIRanges) {
256 LexicalScope *PrevLexicalScope = nullptr;
257 for (auto [R, S] : MIRanges) {
258 assert(S && "Lost LexicalScope for a machine instruction!");
259 if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
260 PrevLexicalScope->closeInsnRange(S);
261 S->openInsnRange(R.first);
262 S->extendInsnRange(R.second);
263 PrevLexicalScope = S;
264 }
265
266 if (PrevLexicalScope)
267 PrevLexicalScope->closeInsnRange();
268}
269
270/// getMachineBasicBlocks - Populate given set using machine basic blocks which
271/// have machine instructions that belong to lexical scope identified by
272/// DebugLoc.
275 assert(MF && "Method called on a uninitialized LexicalScopes object!");
276 MBBs.clear();
277
278 LexicalScope *Scope = getOrCreateLexicalScope(DL);
279 if (!Scope)
280 return;
281
282 if (Scope == CurrentFnLexicalScope) {
284 return;
285 }
286
287 // The scope ranges can cover multiple basic blocks in each span. Iterate over
288 // all blocks (in the order they are in the function) until we reach the one
289 // containing the end of the span.
290 SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
291 for (auto &R : InsnRanges)
292 for (auto CurMBBIt = R.first->getParent()->getIterator(),
293 EndBBIt = std::next(R.second->getParent()->getIterator());
294 CurMBBIt != EndBBIt; CurMBBIt++)
295 MBBs.insert(&*CurMBBIt);
296}
297
299 assert(MF && "Unexpected uninitialized LexicalScopes object!");
300 LexicalScope *Scope = getOrCreateLexicalScope(DL);
301 if (!Scope)
302 return false;
303
304 // Current function scope covers all basic blocks in the function.
305 if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
306 return true;
307
308 // Fetch all the blocks in DLs scope. Because the range / block list also
309 // contain any subscopes, any instruction that DL dominates can be found in
310 // the block set.
311 //
312 // Cache the set of fetched blocks to avoid repeatedly recomputing the set in
313 // the LiveDebugValues pass.
314 std::unique_ptr<BlockSetT> &Set = DominatedBlocks[DL];
315 if (!Set) {
316 Set = std::make_unique<BlockSetT>();
318 }
319 return Set->contains(MBB);
320}
321
322#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
323LLVM_DUMP_METHOD void LexicalScope::dump(unsigned Indent) const {
324 raw_ostream &err = dbgs();
325 err.indent(Indent);
326 err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
327 const MDNode *N = Desc;
328 err.indent(Indent);
329 N->dump();
330 if (AbstractScope)
331 err << std::string(Indent, ' ') << "Abstract Scope\n";
332
333 if (!Children.empty())
334 err << std::string(Indent + 2, ' ') << "Children ...\n";
335 for (const LexicalScope *Child : Children)
336 if (Child != this)
337 Child->dump(Indent + 2);
338}
339#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file defines the DenseMap class.
static bool skipUnit(const DICompileUnit *CU)
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define P(N)
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A scope for locals.
DISubprogram * getSubprogram() const
Get the attached subprogram.
This class is used to track scope information.
SmallVectorImpl< LexicalScope * > & getChildren()
LexicalScope(LexicalScope *P, const DILocalScope *D, const DILocation *I, bool A)
void setDFSOut(unsigned O)
LLVM_ABI void dump(unsigned Indent=0) const
Print lexical scope.
bool dominates(const LexicalScope *S) const
Return true if current scope dominates given lexical scope.
void closeInsnRange(LexicalScope *NewScope=nullptr)
Create a range based on FirstInsn and LastInsn collected until now.
LLVM_ABI void scanFunction(const MachineFunction &)
Scan machine function and constuct lexical scope nest, resets the instance if necessary.
LLVM_ABI LexicalScope * getOrCreateAbstractScope(const DILocalScope *Scope)
Find or create an abstract lexical scope.
LLVM_ABI LexicalScope * findLexicalScope(const DILocation *DL)
Find lexical scope, either regular or inlined, for the given DebugLoc.
LLVM_ABI void getMachineBasicBlocks(const DILocation *DL, SmallPtrSetImpl< const MachineBasicBlock * > &MBBs)
Populate given set using machine basic blocks which have machine instructions that belong to lexical ...
LLVM_ABI void resetFunction()
Reset the instance so that it's prepared for another function.
LLVM_ABI bool dominates(const DILocation *DL, MachineBasicBlock *MBB)
Return true if DebugLoc's lexical scope dominates at least one machine instruction's lexical scope in...
Metadata node.
Definition Metadata.h:1087
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
This is used to track range of instructions with identical lexical scope.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
#define N