Convert several loops over MachineFunction basic blocks to range-based loops
[oota-llvm.git] / lib / CodeGen / LexicalScopes.cpp
1 //===- LexicalScopes.cpp - Collecting lexical scope info ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements LexicalScopes analysis.
11 //
12 // This pass collects lexical scope information and maps machine instructions
13 // to respective lexical scopes.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/LexicalScopes.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FormattedStream.h"
25 using namespace llvm;
26
27 #define DEBUG_TYPE "lexicalscopes"
28
29 /// ~LexicalScopes - final cleanup after ourselves.
30 LexicalScopes::~LexicalScopes() { reset(); }
31
32 /// reset - Reset the instance so that it's prepared for another function.
33 void LexicalScopes::reset() {
34   MF = nullptr;
35   CurrentFnLexicalScope = nullptr;
36   DeleteContainerSeconds(LexicalScopeMap);
37   DeleteContainerSeconds(AbstractScopeMap);
38   InlinedLexicalScopeMap.clear();
39   AbstractScopesList.clear();
40 }
41
42 /// initialize - Scan machine function and constuct lexical scope nest.
43 void LexicalScopes::initialize(const MachineFunction &Fn) {
44   reset();
45   MF = &Fn;
46   SmallVector<InsnRange, 4> MIRanges;
47   DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;
48   extractLexicalScopes(MIRanges, MI2ScopeMap);
49   if (CurrentFnLexicalScope) {
50     constructScopeNest(CurrentFnLexicalScope);
51     assignInstructionRanges(MIRanges, MI2ScopeMap);
52   }
53 }
54
55 /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
56 /// for the given machine function.
57 void LexicalScopes::extractLexicalScopes(
58     SmallVectorImpl<InsnRange> &MIRanges,
59     DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
60
61   // Scan each instruction and create scopes. First build working set of scopes.
62   for (const auto &MBB : *MF) {
63     const MachineInstr *RangeBeginMI = nullptr;
64     const MachineInstr *PrevMI = nullptr;
65     DebugLoc PrevDL;
66     for (MachineBasicBlock::const_iterator II = MBB.begin(), IE = MBB.end();
67          II != IE; ++II) {
68       const MachineInstr *MInsn = II;
69
70       // Check if instruction has valid location information.
71       const DebugLoc MIDL = MInsn->getDebugLoc();
72       if (MIDL.isUnknown()) {
73         PrevMI = MInsn;
74         continue;
75       }
76
77       // If scope has not changed then skip this instruction.
78       if (MIDL == PrevDL) {
79         PrevMI = MInsn;
80         continue;
81       }
82
83       // Ignore DBG_VALUE. It does not contribute to any instruction in output.
84       if (MInsn->isDebugValue())
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
96       // This is a beginning of a new instruction range.
97       RangeBeginMI = MInsn;
98
99       // Reset previous markers.
100       PrevMI = MInsn;
101       PrevDL = MIDL;
102     }
103
104     // Create last instruction range.
105     if (RangeBeginMI && PrevMI && !PrevDL.isUnknown()) {
106       InsnRange R(RangeBeginMI, PrevMI);
107       MIRanges.push_back(R);
108       MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
109     }
110   }
111 }
112
113 /// findLexicalScope - Find lexical scope, either regular or inlined, for the
114 /// given DebugLoc. Return NULL if not found.
115 LexicalScope *LexicalScopes::findLexicalScope(DebugLoc DL) {
116   MDNode *Scope = nullptr;
117   MDNode *IA = nullptr;
118   DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());
119   if (!Scope)
120     return nullptr;
121
122   // The scope that we were created with could have an extra file - which
123   // isn't what we care about in this case.
124   DIDescriptor D = DIDescriptor(Scope);
125   if (D.isLexicalBlockFile())
126     Scope = DILexicalBlockFile(Scope).getScope();
127
128   if (IA)
129     return InlinedLexicalScopeMap.lookup(DebugLoc::getFromDILocation(IA));
130   return LexicalScopeMap.lookup(Scope);
131 }
132
133 /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
134 /// not available then create new lexical scope.
135 LexicalScope *LexicalScopes::getOrCreateLexicalScope(DebugLoc DL) {
136   MDNode *Scope = nullptr;
137   MDNode *InlinedAt = nullptr;
138   DL.getScopeAndInlinedAt(Scope, InlinedAt, MF->getFunction()->getContext());
139
140   if (InlinedAt) {
141     // Create an abstract scope for inlined function.
142     getOrCreateAbstractScope(Scope);
143     // Create an inlined scope for inlined function.
144     return getOrCreateInlinedScope(Scope, InlinedAt);
145   }
146
147   return getOrCreateRegularScope(Scope);
148 }
149
150 /// getOrCreateRegularScope - Find or create a regular lexical scope.
151 LexicalScope *LexicalScopes::getOrCreateRegularScope(MDNode *Scope) {
152   DIDescriptor D = DIDescriptor(Scope);
153   if (D.isLexicalBlockFile()) {
154     Scope = DILexicalBlockFile(Scope).getScope();
155     D = DIDescriptor(Scope);
156   }
157
158   LexicalScope *WScope = LexicalScopeMap.lookup(Scope);
159   if (WScope)
160     return WScope;
161
162   LexicalScope *Parent = nullptr;
163   if (D.isLexicalBlock())
164     Parent = getOrCreateLexicalScope(DebugLoc::getFromDILexicalBlock(Scope));
165   WScope = new LexicalScope(Parent, DIDescriptor(Scope), nullptr, false);
166   LexicalScopeMap.insert(std::make_pair(Scope, WScope));
167   if (!Parent && DIDescriptor(Scope).isSubprogram() &&
168       DISubprogram(Scope).describes(MF->getFunction()))
169     CurrentFnLexicalScope = WScope;
170
171   return WScope;
172 }
173
174 /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
175 LexicalScope *LexicalScopes::getOrCreateInlinedScope(MDNode *Scope,
176                                                      MDNode *InlinedAt) {
177   LexicalScope *InlinedScope = LexicalScopeMap.lookup(InlinedAt);
178   if (InlinedScope)
179     return InlinedScope;
180
181   DebugLoc InlinedLoc = DebugLoc::getFromDILocation(InlinedAt);
182   InlinedScope = new LexicalScope(getOrCreateLexicalScope(InlinedLoc),
183                                   DIDescriptor(Scope), InlinedAt, false);
184   InlinedLexicalScopeMap[InlinedLoc] = InlinedScope;
185   LexicalScopeMap[InlinedAt] = InlinedScope;
186   return InlinedScope;
187 }
188
189 /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
190 LexicalScope *LexicalScopes::getOrCreateAbstractScope(const MDNode *N) {
191   assert(N && "Invalid Scope encoding!");
192
193   DIDescriptor Scope(N);
194   if (Scope.isLexicalBlockFile())
195     Scope = DILexicalBlockFile(Scope).getScope();
196   LexicalScope *AScope = AbstractScopeMap.lookup(N);
197   if (AScope)
198     return AScope;
199
200   LexicalScope *Parent = nullptr;
201   if (Scope.isLexicalBlock()) {
202     DILexicalBlock DB(N);
203     DIDescriptor ParentDesc = DB.getContext();
204     Parent = getOrCreateAbstractScope(ParentDesc);
205   }
206   AScope = new LexicalScope(Parent, DIDescriptor(N), nullptr, true);
207   AbstractScopeMap[N] = AScope;
208   if (DIDescriptor(N).isSubprogram())
209     AbstractScopesList.push_back(AScope);
210   return AScope;
211 }
212
213 /// constructScopeNest
214 void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
215   assert(Scope && "Unable to calculate scope dominance graph!");
216   SmallVector<LexicalScope *, 4> WorkStack;
217   WorkStack.push_back(Scope);
218   unsigned Counter = 0;
219   while (!WorkStack.empty()) {
220     LexicalScope *WS = WorkStack.back();
221     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
222     bool visitedChildren = false;
223     for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
224                                                          SE = Children.end();
225          SI != SE; ++SI) {
226       LexicalScope *ChildScope = *SI;
227       if (!ChildScope->getDFSOut()) {
228         WorkStack.push_back(ChildScope);
229         visitedChildren = true;
230         ChildScope->setDFSIn(++Counter);
231         break;
232       }
233     }
234     if (!visitedChildren) {
235       WorkStack.pop_back();
236       WS->setDFSOut(++Counter);
237     }
238   }
239 }
240
241 /// assignInstructionRanges - Find ranges of instructions covered by each
242 /// lexical scope.
243 void LexicalScopes::assignInstructionRanges(
244     SmallVectorImpl<InsnRange> &MIRanges,
245     DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
246
247   LexicalScope *PrevLexicalScope = nullptr;
248   for (SmallVectorImpl<InsnRange>::const_iterator RI = MIRanges.begin(),
249                                                   RE = MIRanges.end();
250        RI != RE; ++RI) {
251     const InsnRange &R = *RI;
252     LexicalScope *S = MI2ScopeMap.lookup(R.first);
253     assert(S && "Lost LexicalScope for a machine instruction!");
254     if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
255       PrevLexicalScope->closeInsnRange(S);
256     S->openInsnRange(R.first);
257     S->extendInsnRange(R.second);
258     PrevLexicalScope = S;
259   }
260
261   if (PrevLexicalScope)
262     PrevLexicalScope->closeInsnRange();
263 }
264
265 /// getMachineBasicBlocks - Populate given set using machine basic blocks which
266 /// have machine instructions that belong to lexical scope identified by
267 /// DebugLoc.
268 void LexicalScopes::getMachineBasicBlocks(
269     DebugLoc DL, SmallPtrSet<const MachineBasicBlock *, 4> &MBBs) {
270   MBBs.clear();
271   LexicalScope *Scope = getOrCreateLexicalScope(DL);
272   if (!Scope)
273     return;
274
275   if (Scope == CurrentFnLexicalScope) {
276     for (const auto &MBB : *MF)
277       MBBs.insert(&MBB);
278     return;
279   }
280
281   SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
282   for (SmallVectorImpl<InsnRange>::iterator I = InsnRanges.begin(),
283                                             E = InsnRanges.end();
284        I != E; ++I) {
285     InsnRange &R = *I;
286     MBBs.insert(R.first->getParent());
287   }
288 }
289
290 /// dominates - Return true if DebugLoc's lexical scope dominates at least one
291 /// machine instruction's lexical scope in a given machine basic block.
292 bool LexicalScopes::dominates(DebugLoc DL, MachineBasicBlock *MBB) {
293   LexicalScope *Scope = getOrCreateLexicalScope(DL);
294   if (!Scope)
295     return false;
296
297   // Current function scope covers all basic blocks in the function.
298   if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
299     return true;
300
301   bool Result = false;
302   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
303        ++I) {
304     DebugLoc IDL = I->getDebugLoc();
305     if (IDL.isUnknown())
306       continue;
307     if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))
308       if (Scope->dominates(IScope))
309         return true;
310   }
311   return Result;
312 }
313
314 /// dump - Print data structures.
315 void LexicalScope::dump(unsigned Indent) const {
316 #ifndef NDEBUG
317   raw_ostream &err = dbgs();
318   err.indent(Indent);
319   err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
320   const MDNode *N = Desc;
321   err.indent(Indent);
322   N->dump();
323   if (AbstractScope)
324     err << std::string(Indent, ' ') << "Abstract Scope\n";
325
326   if (!Children.empty())
327     err << std::string(Indent + 2, ' ') << "Children ...\n";
328   for (unsigned i = 0, e = Children.size(); i != e; ++i)
329     if (Children[i] != this)
330       Children[i]->dump(Indent + 2);
331 #endif
332 }