1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
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 the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/GVMaterializer.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34 using namespace llvm::dwarf;
35 
getDISubprogram(const MDNode * Scope)36 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
37   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
38     return LocalScope->getSubprogram();
39   return nullptr;
40 }
41 
getDISubprogram(const Function * F)42 DISubprogram *llvm::getDISubprogram(const Function *F) {
43   // We look for the first instr that has a debug annotation leading back to F.
44   for (auto &BB : *F) {
45     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
46       return Inst.getDebugLoc();
47     });
48     if (Inst == BB.end())
49       continue;
50     DebugLoc DLoc = Inst->getDebugLoc();
51     const MDNode *Scope = DLoc.getInlinedAtScope();
52     auto *Subprogram = getDISubprogram(Scope);
53     return Subprogram->describes(F) ? Subprogram : nullptr;
54   }
55 
56   return nullptr;
57 }
58 
59 DITypeIdentifierMap
generateDITypeIdentifierMap(const NamedMDNode * CU_Nodes)60 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
61   DITypeIdentifierMap Map;
62   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
63     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(CUi));
64     DINodeArray Retain = CU->getRetainedTypes();
65     for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
66       if (!isa<DICompositeType>(Retain[Ti]))
67         continue;
68       auto *Ty = cast<DICompositeType>(Retain[Ti]);
69       if (MDString *TypeId = Ty->getRawIdentifier()) {
70         // Definition has priority over declaration.
71         // Try to insert (TypeId, Ty) to Map.
72         std::pair<DITypeIdentifierMap::iterator, bool> P =
73             Map.insert(std::make_pair(TypeId, Ty));
74         // If TypeId already exists in Map and this is a definition, replace
75         // whatever we had (declaration or definition) with the definition.
76         if (!P.second && !Ty->isForwardDecl())
77           P.first->second = Ty;
78       }
79     }
80   }
81   return Map;
82 }
83 
84 //===----------------------------------------------------------------------===//
85 // DebugInfoFinder implementations.
86 //===----------------------------------------------------------------------===//
87 
reset()88 void DebugInfoFinder::reset() {
89   CUs.clear();
90   SPs.clear();
91   GVs.clear();
92   TYs.clear();
93   Scopes.clear();
94   NodesSeen.clear();
95   TypeIdentifierMap.clear();
96   TypeMapInitialized = false;
97 }
98 
InitializeTypeMap(const Module & M)99 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
100   if (!TypeMapInitialized)
101     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
102       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
103       TypeMapInitialized = true;
104     }
105 }
106 
processModule(const Module & M)107 void DebugInfoFinder::processModule(const Module &M) {
108   InitializeTypeMap(M);
109   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
110     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
111       auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
112       addCompileUnit(CU);
113       for (auto *DIG : CU->getGlobalVariables()) {
114         if (addGlobalVariable(DIG)) {
115           processScope(DIG->getScope());
116           processType(DIG->getType().resolve(TypeIdentifierMap));
117         }
118       }
119       for (auto *SP : CU->getSubprograms())
120         processSubprogram(SP);
121       for (auto *ET : CU->getEnumTypes())
122         processType(ET);
123       for (auto *RT : CU->getRetainedTypes())
124         processType(RT);
125       for (auto *Import : CU->getImportedEntities()) {
126         auto *Entity = Import->getEntity().resolve(TypeIdentifierMap);
127         if (auto *T = dyn_cast<DIType>(Entity))
128           processType(T);
129         else if (auto *SP = dyn_cast<DISubprogram>(Entity))
130           processSubprogram(SP);
131         else if (auto *NS = dyn_cast<DINamespace>(Entity))
132           processScope(NS->getScope());
133         else if (auto *M = dyn_cast<DIModule>(Entity))
134           processScope(M->getScope());
135       }
136     }
137   }
138 }
139 
processLocation(const Module & M,const DILocation * Loc)140 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
141   if (!Loc)
142     return;
143   InitializeTypeMap(M);
144   processScope(Loc->getScope());
145   processLocation(M, Loc->getInlinedAt());
146 }
147 
processType(DIType * DT)148 void DebugInfoFinder::processType(DIType *DT) {
149   if (!addType(DT))
150     return;
151   processScope(DT->getScope().resolve(TypeIdentifierMap));
152   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
153     for (DITypeRef Ref : ST->getTypeArray())
154       processType(Ref.resolve(TypeIdentifierMap));
155     return;
156   }
157   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
158     processType(DCT->getBaseType().resolve(TypeIdentifierMap));
159     for (Metadata *D : DCT->getElements()) {
160       if (auto *T = dyn_cast<DIType>(D))
161         processType(T);
162       else if (auto *SP = dyn_cast<DISubprogram>(D))
163         processSubprogram(SP);
164     }
165     return;
166   }
167   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
168     processType(DDT->getBaseType().resolve(TypeIdentifierMap));
169   }
170 }
171 
processScope(DIScope * Scope)172 void DebugInfoFinder::processScope(DIScope *Scope) {
173   if (!Scope)
174     return;
175   if (auto *Ty = dyn_cast<DIType>(Scope)) {
176     processType(Ty);
177     return;
178   }
179   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
180     addCompileUnit(CU);
181     return;
182   }
183   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
184     processSubprogram(SP);
185     return;
186   }
187   if (!addScope(Scope))
188     return;
189   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
190     processScope(LB->getScope());
191   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
192     processScope(NS->getScope());
193   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
194     processScope(M->getScope());
195   }
196 }
197 
processSubprogram(DISubprogram * SP)198 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
199   if (!addSubprogram(SP))
200     return;
201   processScope(SP->getScope().resolve(TypeIdentifierMap));
202   processType(SP->getType());
203   for (auto *Element : SP->getTemplateParams()) {
204     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
205       processType(TType->getType().resolve(TypeIdentifierMap));
206     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
207       processType(TVal->getType().resolve(TypeIdentifierMap));
208     }
209   }
210 }
211 
processDeclare(const Module & M,const DbgDeclareInst * DDI)212 void DebugInfoFinder::processDeclare(const Module &M,
213                                      const DbgDeclareInst *DDI) {
214   auto *N = dyn_cast<MDNode>(DDI->getVariable());
215   if (!N)
216     return;
217   InitializeTypeMap(M);
218 
219   auto *DV = dyn_cast<DILocalVariable>(N);
220   if (!DV)
221     return;
222 
223   if (!NodesSeen.insert(DV).second)
224     return;
225   processScope(DV->getScope());
226   processType(DV->getType().resolve(TypeIdentifierMap));
227 }
228 
processValue(const Module & M,const DbgValueInst * DVI)229 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
230   auto *N = dyn_cast<MDNode>(DVI->getVariable());
231   if (!N)
232     return;
233   InitializeTypeMap(M);
234 
235   auto *DV = dyn_cast<DILocalVariable>(N);
236   if (!DV)
237     return;
238 
239   if (!NodesSeen.insert(DV).second)
240     return;
241   processScope(DV->getScope());
242   processType(DV->getType().resolve(TypeIdentifierMap));
243 }
244 
addType(DIType * DT)245 bool DebugInfoFinder::addType(DIType *DT) {
246   if (!DT)
247     return false;
248 
249   if (!NodesSeen.insert(DT).second)
250     return false;
251 
252   TYs.push_back(const_cast<DIType *>(DT));
253   return true;
254 }
255 
addCompileUnit(DICompileUnit * CU)256 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
257   if (!CU)
258     return false;
259   if (!NodesSeen.insert(CU).second)
260     return false;
261 
262   CUs.push_back(CU);
263   return true;
264 }
265 
addGlobalVariable(DIGlobalVariable * DIG)266 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable *DIG) {
267   if (!DIG)
268     return false;
269 
270   if (!NodesSeen.insert(DIG).second)
271     return false;
272 
273   GVs.push_back(DIG);
274   return true;
275 }
276 
addSubprogram(DISubprogram * SP)277 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
278   if (!SP)
279     return false;
280 
281   if (!NodesSeen.insert(SP).second)
282     return false;
283 
284   SPs.push_back(SP);
285   return true;
286 }
287 
addScope(DIScope * Scope)288 bool DebugInfoFinder::addScope(DIScope *Scope) {
289   if (!Scope)
290     return false;
291   // FIXME: Ocaml binding generates a scope with no content, we treat it
292   // as null for now.
293   if (Scope->getNumOperands() == 0)
294     return false;
295   if (!NodesSeen.insert(Scope).second)
296     return false;
297   Scopes.push_back(Scope);
298   return true;
299 }
300 
stripDebugInfo(Function & F)301 bool llvm::stripDebugInfo(Function &F) {
302   bool Changed = false;
303   if (F.getSubprogram()) {
304     Changed = true;
305     F.setSubprogram(nullptr);
306   }
307   for (BasicBlock &BB : F) {
308     for (Instruction &I : BB) {
309       if (I.getDebugLoc()) {
310         Changed = true;
311         I.setDebugLoc(DebugLoc());
312       }
313     }
314   }
315   return Changed;
316 }
317 
StripDebugInfo(Module & M)318 bool llvm::StripDebugInfo(Module &M) {
319   bool Changed = false;
320 
321   // Remove all of the calls to the debugger intrinsics, and remove them from
322   // the module.
323   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
324     while (!Declare->use_empty()) {
325       CallInst *CI = cast<CallInst>(Declare->user_back());
326       CI->eraseFromParent();
327     }
328     Declare->eraseFromParent();
329     Changed = true;
330   }
331 
332   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
333     while (!DbgVal->use_empty()) {
334       CallInst *CI = cast<CallInst>(DbgVal->user_back());
335       CI->eraseFromParent();
336     }
337     DbgVal->eraseFromParent();
338     Changed = true;
339   }
340 
341   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
342          NME = M.named_metadata_end(); NMI != NME;) {
343     NamedMDNode *NMD = &*NMI;
344     ++NMI;
345     if (NMD->getName().startswith("llvm.dbg.")) {
346       NMD->eraseFromParent();
347       Changed = true;
348     }
349   }
350 
351   for (Function &F : M)
352     Changed |= stripDebugInfo(F);
353 
354   if (GVMaterializer *Materializer = M.getMaterializer())
355     Materializer->setStripDebugInfo();
356 
357   return Changed;
358 }
359 
getDebugMetadataVersionFromModule(const Module & M)360 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
361   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
362           M.getModuleFlag("Debug Info Version")))
363     return Val->getZExtValue();
364   return 0;
365 }
366