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