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 /// findLexicalScope - Find lexical scope, either regular or inlined, for the
00108 /// given DebugLoc. Return NULL if not found.
00109 LexicalScope *LexicalScopes::findLexicalScope(DebugLoc DL) {
00110   MDNode *Scope = nullptr;
00111   MDNode *IA = nullptr;
00112   DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());
00113   if (!Scope)
00114     return nullptr;
00115 
00116   // The scope that we were created with could have an extra file - which
00117   // isn't what we care about in this case.
00118   DIDescriptor D = DIDescriptor(Scope);
00119   if (D.isLexicalBlockFile())
00120     Scope = DILexicalBlockFile(Scope).getScope();
00121 
00122   if (IA) {
00123     auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
00124     return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
00125   }
00126   return findLexicalScope(Scope);
00127 }
00128 
00129 /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
00130 /// not available then create new lexical scope.
00131 LexicalScope *LexicalScopes::getOrCreateLexicalScope(DebugLoc DL) {
00132   if (DL.isUnknown())
00133     return nullptr;
00134   MDNode *Scope = nullptr;
00135   MDNode *InlinedAt = nullptr;
00136   DL.getScopeAndInlinedAt(Scope, InlinedAt, MF->getFunction()->getContext());
00137 
00138   if (InlinedAt) {
00139     // Create an abstract scope for inlined function.
00140     getOrCreateAbstractScope(Scope);
00141     // Create an inlined scope for inlined function.
00142     return getOrCreateInlinedScope(Scope, InlinedAt);
00143   }
00144 
00145   return getOrCreateRegularScope(Scope);
00146 }
00147 
00148 /// getOrCreateRegularScope - Find or create a regular lexical scope.
00149 LexicalScope *LexicalScopes::getOrCreateRegularScope(MDNode *Scope) {
00150   DIDescriptor D = DIDescriptor(Scope);
00151   if (D.isLexicalBlockFile()) {
00152     Scope = DILexicalBlockFile(Scope).getScope();
00153     D = DIDescriptor(Scope);
00154   }
00155 
00156   auto I = LexicalScopeMap.find(Scope);
00157   if (I != LexicalScopeMap.end())
00158     return &I->second;
00159 
00160   LexicalScope *Parent = nullptr;
00161   if (D.isLexicalBlock())
00162     Parent = getOrCreateLexicalScope(DebugLoc::getFromDILexicalBlock(Scope));
00163   I = LexicalScopeMap.emplace(std::piecewise_construct,
00164                               std::forward_as_tuple(Scope),
00165                               std::forward_as_tuple(Parent, DIDescriptor(Scope),
00166                                                     nullptr, false)).first;
00167 
00168   if (!Parent) {
00169     assert(DIDescriptor(Scope).isSubprogram());
00170     assert(DISubprogram(Scope).describes(MF->getFunction()));
00171     assert(!CurrentFnLexicalScope);
00172     CurrentFnLexicalScope = &I->second;
00173   }
00174 
00175   return &I->second;
00176 }
00177 
00178 /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
00179 LexicalScope *LexicalScopes::getOrCreateInlinedScope(MDNode *ScopeNode,
00180                                                      MDNode *InlinedAt) {
00181   std::pair<const MDNode*, const MDNode*> P(ScopeNode, InlinedAt);
00182   auto I = InlinedLexicalScopeMap.find(P);
00183   if (I != InlinedLexicalScopeMap.end())
00184     return &I->second;
00185 
00186   LexicalScope *Parent;
00187   DILexicalBlock Scope(ScopeNode);
00188   if (Scope.isSubprogram())
00189     Parent = getOrCreateLexicalScope(DebugLoc::getFromDILocation(InlinedAt));
00190   else
00191     Parent = getOrCreateInlinedScope(Scope.getContext(), InlinedAt);
00192 
00193   I = InlinedLexicalScopeMap.emplace(std::piecewise_construct,
00194                                      std::forward_as_tuple(P),
00195                                      std::forward_as_tuple(Parent, Scope,
00196                                                            InlinedAt, false))
00197           .first;
00198   return &I->second;
00199 }
00200 
00201 /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
00202 LexicalScope *LexicalScopes::getOrCreateAbstractScope(const MDNode *N) {
00203   assert(N && "Invalid Scope encoding!");
00204 
00205   DIDescriptor Scope(N);
00206   if (Scope.isLexicalBlockFile())
00207     Scope = DILexicalBlockFile(Scope).getScope();
00208   auto I = AbstractScopeMap.find(Scope);
00209   if (I != AbstractScopeMap.end())
00210     return &I->second;
00211 
00212   LexicalScope *Parent = nullptr;
00213   if (Scope.isLexicalBlock()) {
00214     DILexicalBlock DB(Scope);
00215     DIDescriptor ParentDesc = DB.getContext();
00216     Parent = getOrCreateAbstractScope(ParentDesc);
00217   }
00218   I = AbstractScopeMap.emplace(std::piecewise_construct,
00219                                std::forward_as_tuple(Scope),
00220                                std::forward_as_tuple(Parent, Scope,
00221                                                      nullptr, true)).first;
00222   if (Scope.isSubprogram())
00223     AbstractScopesList.push_back(&I->second);
00224   return &I->second;
00225 }
00226 
00227 /// constructScopeNest
00228 void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
00229   assert(Scope && "Unable to calculate scope dominance graph!");
00230   SmallVector<LexicalScope *, 4> WorkStack;
00231   WorkStack.push_back(Scope);
00232   unsigned Counter = 0;
00233   while (!WorkStack.empty()) {
00234     LexicalScope *WS = WorkStack.back();
00235     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
00236     bool visitedChildren = false;
00237     for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
00238                                                          SE = Children.end();
00239          SI != SE; ++SI) {
00240       LexicalScope *ChildScope = *SI;
00241       if (!ChildScope->getDFSOut()) {
00242         WorkStack.push_back(ChildScope);
00243         visitedChildren = true;
00244         ChildScope->setDFSIn(++Counter);
00245         break;
00246       }
00247     }
00248     if (!visitedChildren) {
00249       WorkStack.pop_back();
00250       WS->setDFSOut(++Counter);
00251     }
00252   }
00253 }
00254 
00255 /// assignInstructionRanges - Find ranges of instructions covered by each
00256 /// lexical scope.
00257 void LexicalScopes::assignInstructionRanges(
00258     SmallVectorImpl<InsnRange> &MIRanges,
00259     DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
00260 
00261   LexicalScope *PrevLexicalScope = nullptr;
00262   for (SmallVectorImpl<InsnRange>::const_iterator RI = MIRanges.begin(),
00263                                                   RE = MIRanges.end();
00264        RI != RE; ++RI) {
00265     const InsnRange &R = *RI;
00266     LexicalScope *S = MI2ScopeMap.lookup(R.first);
00267     assert(S && "Lost LexicalScope for a machine instruction!");
00268     if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
00269       PrevLexicalScope->closeInsnRange(S);
00270     S->openInsnRange(R.first);
00271     S->extendInsnRange(R.second);
00272     PrevLexicalScope = S;
00273   }
00274 
00275   if (PrevLexicalScope)
00276     PrevLexicalScope->closeInsnRange();
00277 }
00278 
00279 /// getMachineBasicBlocks - Populate given set using machine basic blocks which
00280 /// have machine instructions that belong to lexical scope identified by
00281 /// DebugLoc.
00282 void LexicalScopes::getMachineBasicBlocks(
00283     DebugLoc DL, SmallPtrSetImpl<const MachineBasicBlock *> &MBBs) {
00284   MBBs.clear();
00285   LexicalScope *Scope = getOrCreateLexicalScope(DL);
00286   if (!Scope)
00287     return;
00288 
00289   if (Scope == CurrentFnLexicalScope) {
00290     for (const auto &MBB : *MF)
00291       MBBs.insert(&MBB);
00292     return;
00293   }
00294 
00295   SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
00296   for (SmallVectorImpl<InsnRange>::iterator I = InsnRanges.begin(),
00297                                             E = InsnRanges.end();
00298        I != E; ++I) {
00299     InsnRange &R = *I;
00300     MBBs.insert(R.first->getParent());
00301   }
00302 }
00303 
00304 /// dominates - Return true if DebugLoc's lexical scope dominates at least one
00305 /// machine instruction's lexical scope in a given machine basic block.
00306 bool LexicalScopes::dominates(DebugLoc DL, MachineBasicBlock *MBB) {
00307   LexicalScope *Scope = getOrCreateLexicalScope(DL);
00308   if (!Scope)
00309     return false;
00310 
00311   // Current function scope covers all basic blocks in the function.
00312   if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
00313     return true;
00314 
00315   bool Result = false;
00316   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
00317        ++I) {
00318     DebugLoc IDL = I->getDebugLoc();
00319     if (IDL.isUnknown())
00320       continue;
00321     if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))
00322       if (Scope->dominates(IScope))
00323         return true;
00324   }
00325   return Result;
00326 }
00327 
00328 /// dump - Print data structures.
00329 void LexicalScope::dump(unsigned Indent) const {
00330 #ifndef NDEBUG
00331   raw_ostream &err = dbgs();
00332   err.indent(Indent);
00333   err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
00334   const MDNode *N = Desc;
00335   err.indent(Indent);
00336   N->dump();
00337   if (AbstractScope)
00338     err << std::string(Indent, ' ') << "Abstract Scope\n";
00339 
00340   if (!Children.empty())
00341     err << std::string(Indent + 2, ' ') << "Children ...\n";
00342   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00343     if (Children[i] != this)
00344       Children[i]->dump(Indent + 2);
00345 #endif
00346 }