LLVM API Documentation

LexicalScopes.cpp
Go to the documentation of this file.
00001 //===- LexicalScopes.cpp - Collecting lexical scope info ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements LexicalScopes analysis.
00011 //
00012 // This pass collects lexical scope information and maps machine instructions
00013 // to respective lexical scopes.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/CodeGen/LexicalScopes.h"
00018 #include "llvm/CodeGen/MachineFunction.h"
00019 #include "llvm/CodeGen/MachineInstr.h"
00020 #include "llvm/IR/DebugInfo.h"
00021 #include "llvm/IR/Function.h"
00022 #include "llvm/Support/Debug.h"
00023 #include "llvm/Support/ErrorHandling.h"
00024 #include "llvm/Support/FormattedStream.h"
00025 using namespace llvm;
00026 
00027 #define DEBUG_TYPE "lexicalscopes"
00028 
00029 /// reset - Reset the instance so that it's prepared for another function.
00030 void LexicalScopes::reset() {
00031   MF = nullptr;
00032   CurrentFnLexicalScope = nullptr;
00033   LexicalScopeMap.clear();
00034   AbstractScopeMap.clear();
00035   InlinedLexicalScopeMap.clear();
00036   AbstractScopesList.clear();
00037 }
00038 
00039 /// initialize - Scan machine function and constuct lexical scope nest.
00040 void LexicalScopes::initialize(const MachineFunction &Fn) {
00041   reset();
00042   MF = &Fn;
00043   SmallVector<InsnRange, 4> MIRanges;
00044   DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;
00045   extractLexicalScopes(MIRanges, MI2ScopeMap);
00046   if (CurrentFnLexicalScope) {
00047     constructScopeNest(CurrentFnLexicalScope);
00048     assignInstructionRanges(MIRanges, MI2ScopeMap);
00049   }
00050 }
00051 
00052 /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
00053 /// for the given machine function.
00054 void LexicalScopes::extractLexicalScopes(
00055     SmallVectorImpl<InsnRange> &MIRanges,
00056     DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
00057 
00058   // Scan each instruction and create scopes. First build working set of scopes.
00059   for (const auto &MBB : *MF) {
00060     const MachineInstr *RangeBeginMI = nullptr;
00061     const MachineInstr *PrevMI = nullptr;
00062     DebugLoc PrevDL;
00063     for (const auto &MInsn : MBB) {
00064       // Check if instruction has valid location information.
00065       const DebugLoc MIDL = MInsn.getDebugLoc();
00066       if (MIDL.isUnknown()) {
00067         PrevMI = &MInsn;
00068         continue;
00069       }
00070 
00071       // If scope has not changed then skip this instruction.
00072       if (MIDL == PrevDL) {
00073         PrevMI = &MInsn;
00074         continue;
00075       }
00076 
00077       // Ignore DBG_VALUE. It does not contribute to any instruction in output.
00078       if (MInsn.isDebugValue())
00079         continue;
00080 
00081       if (RangeBeginMI) {
00082         // If we have already seen a beginning of an instruction range and
00083         // current instruction scope does not match scope of first instruction
00084         // in this range then create a new instruction range.
00085         InsnRange R(RangeBeginMI, PrevMI);
00086         MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
00087         MIRanges.push_back(R);
00088       }
00089 
00090       // This is a beginning of a new instruction range.
00091       RangeBeginMI = &MInsn;
00092 
00093       // Reset previous markers.
00094       PrevMI = &MInsn;
00095       PrevDL = MIDL;
00096     }
00097 
00098     // Create last instruction range.
00099     if (RangeBeginMI && PrevMI && !PrevDL.isUnknown()) {
00100       InsnRange R(RangeBeginMI, PrevMI);
00101       MIRanges.push_back(R);
00102       MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
00103     }
00104   }
00105 }
00106 
00107 LexicalScope *LexicalScopes::findInlinedScope(DebugLoc DL) {
00108   MDNode *Scope = nullptr;
00109   MDNode *IA = nullptr;
00110   DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());
00111   auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
00112   return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
00113 }
00114 
00115 /// findLexicalScope - Find lexical scope, either regular or inlined, for the
00116 /// given DebugLoc. Return NULL if not found.
00117 LexicalScope *LexicalScopes::findLexicalScope(DebugLoc DL) {
00118   MDNode *Scope = nullptr;
00119   MDNode *IA = nullptr;
00120   DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());
00121   if (!Scope)
00122     return nullptr;
00123 
00124   // The scope that we were created with could have an extra file - which
00125   // isn't what we care about in this case.
00126   DIDescriptor D = DIDescriptor(Scope);
00127   if (D.isLexicalBlockFile())
00128     Scope = DILexicalBlockFile(Scope).getScope();
00129 
00130   if (IA) {
00131     auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
00132     return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
00133   }
00134   return findLexicalScope(Scope);
00135 }
00136 
00137 /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
00138 /// not available then create new lexical scope.
00139 LexicalScope *LexicalScopes::getOrCreateLexicalScope(DebugLoc DL) {
00140   if (DL.isUnknown())
00141     return nullptr;
00142   MDNode *Scope = nullptr;
00143   MDNode *InlinedAt = nullptr;
00144   DL.getScopeAndInlinedAt(Scope, InlinedAt, MF->getFunction()->getContext());
00145 
00146   if (InlinedAt) {
00147     // Create an abstract scope for inlined function.
00148     getOrCreateAbstractScope(Scope);
00149     // Create an inlined scope for inlined function.
00150     return getOrCreateInlinedScope(Scope, InlinedAt);
00151   }
00152 
00153   return getOrCreateRegularScope(Scope);
00154 }
00155 
00156 /// getOrCreateRegularScope - Find or create a regular lexical scope.
00157 LexicalScope *LexicalScopes::getOrCreateRegularScope(MDNode *Scope) {
00158   DIDescriptor D = DIDescriptor(Scope);
00159   if (D.isLexicalBlockFile()) {
00160     Scope = DILexicalBlockFile(Scope).getScope();
00161     D = DIDescriptor(Scope);
00162   }
00163 
00164   auto I = LexicalScopeMap.find(Scope);
00165   if (I != LexicalScopeMap.end())
00166     return &I->second;
00167 
00168   LexicalScope *Parent = nullptr;
00169   if (D.isLexicalBlock())
00170     Parent = getOrCreateLexicalScope(DebugLoc::getFromDILexicalBlock(Scope));
00171   // FIXME: Use forward_as_tuple instead of make_tuple, once MSVC2012
00172   // compatibility is no longer required.
00173   I = LexicalScopeMap.emplace(std::piecewise_construct, std::make_tuple(Scope),
00174                               std::make_tuple(Parent, DIDescriptor(Scope),
00175                                               nullptr, false)).first;
00176 
00177   if (!Parent) {
00178     assert(DIDescriptor(Scope).isSubprogram());
00179     assert(DISubprogram(Scope).describes(MF->getFunction()));
00180     assert(!CurrentFnLexicalScope);
00181     CurrentFnLexicalScope = &I->second;
00182   }
00183 
00184   return &I->second;
00185 }
00186 
00187 /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
00188 LexicalScope *LexicalScopes::getOrCreateInlinedScope(MDNode *ScopeNode,
00189                                                      MDNode *InlinedAt) {
00190   std::pair<const MDNode*, const MDNode*> P(ScopeNode, InlinedAt);
00191   auto I = InlinedLexicalScopeMap.find(P);
00192   if (I != InlinedLexicalScopeMap.end())
00193     return &I->second;
00194 
00195   LexicalScope *Parent;
00196   DILexicalBlock Scope(ScopeNode);
00197   if (Scope.isSubprogram())
00198     Parent = getOrCreateLexicalScope(DebugLoc::getFromDILocation(InlinedAt));
00199   else
00200     Parent = getOrCreateInlinedScope(Scope.getContext(), InlinedAt);
00201 
00202   // FIXME: Use forward_as_tuple instead of make_tuple, once MSVC2012
00203   // compatibility is no longer required.
00204   I = InlinedLexicalScopeMap.emplace(std::piecewise_construct,
00205                                      std::make_tuple(P),
00206                                      std::make_tuple(Parent, Scope, InlinedAt,
00207                                                      false)).first;
00208   return &I->second;
00209 }
00210 
00211 /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
00212 LexicalScope *LexicalScopes::getOrCreateAbstractScope(const MDNode *N) {
00213   assert(N && "Invalid Scope encoding!");
00214 
00215   DIDescriptor Scope(N);
00216   if (Scope.isLexicalBlockFile())
00217     Scope = DILexicalBlockFile(Scope).getScope();
00218   auto I = AbstractScopeMap.find(Scope);
00219   if (I != AbstractScopeMap.end())
00220     return &I->second;
00221 
00222   LexicalScope *Parent = nullptr;
00223   if (Scope.isLexicalBlock()) {
00224     DILexicalBlock DB(Scope);
00225     DIDescriptor ParentDesc = DB.getContext();
00226     Parent = getOrCreateAbstractScope(ParentDesc);
00227   }
00228   I = AbstractScopeMap.emplace(std::piecewise_construct,
00229                                std::forward_as_tuple(Scope),
00230                                std::forward_as_tuple(Parent, Scope,
00231                                                      nullptr, true)).first;
00232   if (Scope.isSubprogram())
00233     AbstractScopesList.push_back(&I->second);
00234   return &I->second;
00235 }
00236 
00237 /// constructScopeNest
00238 void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
00239   assert(Scope && "Unable to calculate scope dominance graph!");
00240   SmallVector<LexicalScope *, 4> WorkStack;
00241   WorkStack.push_back(Scope);
00242   unsigned Counter = 0;
00243   while (!WorkStack.empty()) {
00244     LexicalScope *WS = WorkStack.back();
00245     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
00246     bool visitedChildren = false;
00247     for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
00248                                                          SE = Children.end();
00249          SI != SE; ++SI) {
00250       LexicalScope *ChildScope = *SI;
00251       if (!ChildScope->getDFSOut()) {
00252         WorkStack.push_back(ChildScope);
00253         visitedChildren = true;
00254         ChildScope->setDFSIn(++Counter);
00255         break;
00256       }
00257     }
00258     if (!visitedChildren) {
00259       WorkStack.pop_back();
00260       WS->setDFSOut(++Counter);
00261     }
00262   }
00263 }
00264 
00265 /// assignInstructionRanges - Find ranges of instructions covered by each
00266 /// lexical scope.
00267 void LexicalScopes::assignInstructionRanges(
00268     SmallVectorImpl<InsnRange> &MIRanges,
00269     DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
00270 
00271   LexicalScope *PrevLexicalScope = nullptr;
00272   for (SmallVectorImpl<InsnRange>::const_iterator RI = MIRanges.begin(),
00273                                                   RE = MIRanges.end();
00274        RI != RE; ++RI) {
00275     const InsnRange &R = *RI;
00276     LexicalScope *S = MI2ScopeMap.lookup(R.first);
00277     assert(S && "Lost LexicalScope for a machine instruction!");
00278     if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
00279       PrevLexicalScope->closeInsnRange(S);
00280     S->openInsnRange(R.first);
00281     S->extendInsnRange(R.second);
00282     PrevLexicalScope = S;
00283   }
00284 
00285   if (PrevLexicalScope)
00286     PrevLexicalScope->closeInsnRange();
00287 }
00288 
00289 /// getMachineBasicBlocks - Populate given set using machine basic blocks which
00290 /// have machine instructions that belong to lexical scope identified by
00291 /// DebugLoc.
00292 void LexicalScopes::getMachineBasicBlocks(
00293     DebugLoc DL, SmallPtrSetImpl<const MachineBasicBlock *> &MBBs) {
00294   MBBs.clear();
00295   LexicalScope *Scope = getOrCreateLexicalScope(DL);
00296   if (!Scope)
00297     return;
00298 
00299   if (Scope == CurrentFnLexicalScope) {
00300     for (const auto &MBB : *MF)
00301       MBBs.insert(&MBB);
00302     return;
00303   }
00304 
00305   SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
00306   for (SmallVectorImpl<InsnRange>::iterator I = InsnRanges.begin(),
00307                                             E = InsnRanges.end();
00308        I != E; ++I) {
00309     InsnRange &R = *I;
00310     MBBs.insert(R.first->getParent());
00311   }
00312 }
00313 
00314 /// dominates - Return true if DebugLoc's lexical scope dominates at least one
00315 /// machine instruction's lexical scope in a given machine basic block.
00316 bool LexicalScopes::dominates(DebugLoc DL, MachineBasicBlock *MBB) {
00317   LexicalScope *Scope = getOrCreateLexicalScope(DL);
00318   if (!Scope)
00319     return false;
00320 
00321   // Current function scope covers all basic blocks in the function.
00322   if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
00323     return true;
00324 
00325   bool Result = false;
00326   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
00327        ++I) {
00328     DebugLoc IDL = I->getDebugLoc();
00329     if (IDL.isUnknown())
00330       continue;
00331     if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))
00332       if (Scope->dominates(IScope))
00333         return true;
00334   }
00335   return Result;
00336 }
00337 
00338 /// dump - Print data structures.
00339 void LexicalScope::dump(unsigned Indent) const {
00340 #ifndef NDEBUG
00341   raw_ostream &err = dbgs();
00342   err.indent(Indent);
00343   err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
00344   const MDNode *N = Desc;
00345   err.indent(Indent);
00346   N->dump();
00347   if (AbstractScope)
00348     err << std::string(Indent, ' ') << "Abstract Scope\n";
00349 
00350   if (!Children.empty())
00351     err << std::string(Indent + 2, ' ') << "Children ...\n";
00352   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00353     if (Children[i] != this)
00354       Children[i]->dump(Indent + 2);
00355 #endif
00356 }