DebugInfo: Gut DISubprogram and DILexicalBlock*
[oota-llvm.git] / lib / IR / DebugInfo.cpp
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
36 //===----------------------------------------------------------------------===//
37 // Simple Descriptor Constructors and other Methods
38 //===----------------------------------------------------------------------===//
39
40 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
41
42 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
43   get()->replaceSubprograms(MDSubprogramArray(Subprograms));
44 }
45
46 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
47   get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
48 }
49
50 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
51                                        LLVMContext &VMContext) {
52   return cast<MDLocalVariable>(DV)
53       ->withInline(cast_or_null<MDLocation>(InlinedScope));
54 }
55
56 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
57   return cast<MDLocalVariable>(DV)->withoutInline();
58 }
59
60 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
61   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
62     return LocalScope->getSubprogram();
63   return nullptr;
64 }
65
66 DISubprogram llvm::getDISubprogram(const Function *F) {
67   // We look for the first instr that has a debug annotation leading back to F.
68   for (auto &BB : *F) {
69     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
70       return Inst.getDebugLoc();
71     });
72     if (Inst == BB.end())
73       continue;
74     DebugLoc DLoc = Inst->getDebugLoc();
75     const MDNode *Scope = DLoc.getInlinedAtScope();
76     DISubprogram Subprogram = getDISubprogram(Scope);
77     return Subprogram->describes(F) ? Subprogram : DISubprogram();
78   }
79
80   return DISubprogram();
81 }
82
83 DICompositeType llvm::getDICompositeType(DIType T) {
84   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
85     return C;
86
87   if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
88     // This function is currently used by dragonegg and dragonegg does
89     // not generate identifier for types, so using an empty map to resolve
90     // DerivedFrom should be fine.
91     DITypeIdentifierMap EmptyMap;
92     return getDICompositeType(
93         DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
94   }
95
96   return nullptr;
97 }
98
99 DITypeIdentifierMap
100 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
101   DITypeIdentifierMap Map;
102   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
103     DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
104     DIArray Retain = CU.getRetainedTypes();
105     for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
106       if (!isa<MDCompositeType>(Retain[Ti]))
107         continue;
108       DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
109       if (MDString *TypeId = Ty.getIdentifier()) {
110         // Definition has priority over declaration.
111         // Try to insert (TypeId, Ty) to Map.
112         std::pair<DITypeIdentifierMap::iterator, bool> P =
113             Map.insert(std::make_pair(TypeId, Ty));
114         // If TypeId already exists in Map and this is a definition, replace
115         // whatever we had (declaration or definition) with the definition.
116         if (!P.second && !Ty.isForwardDecl())
117           P.first->second = Ty;
118       }
119     }
120   }
121   return Map;
122 }
123
124 //===----------------------------------------------------------------------===//
125 // DebugInfoFinder implementations.
126 //===----------------------------------------------------------------------===//
127
128 void DebugInfoFinder::reset() {
129   CUs.clear();
130   SPs.clear();
131   GVs.clear();
132   TYs.clear();
133   Scopes.clear();
134   NodesSeen.clear();
135   TypeIdentifierMap.clear();
136   TypeMapInitialized = false;
137 }
138
139 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
140   if (!TypeMapInitialized)
141     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
142       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
143       TypeMapInitialized = true;
144     }
145 }
146
147 void DebugInfoFinder::processModule(const Module &M) {
148   InitializeTypeMap(M);
149   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
150     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
151       DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
152       addCompileUnit(CU);
153       for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
154         if (addGlobalVariable(DIG)) {
155           processScope(DIG->getScope());
156           processType(DIG->getType().resolve(TypeIdentifierMap));
157         }
158       }
159       for (auto *SP : CU->getSubprograms())
160         processSubprogram(SP);
161       for (auto *ET : CU->getEnumTypes())
162         processType(ET);
163       for (auto *RT : CU->getRetainedTypes())
164         processType(RT);
165       for (DIImportedEntity Import : CU->getImportedEntities()) {
166         auto *Entity = Import->getEntity().resolve(TypeIdentifierMap);
167         if (auto *T = dyn_cast<MDType>(Entity))
168           processType(T);
169         else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
170           processSubprogram(SP);
171         else if (auto *NS = dyn_cast<MDNamespace>(Entity))
172           processScope(NS->getScope());
173       }
174     }
175   }
176 }
177
178 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
179   if (!Loc)
180     return;
181   InitializeTypeMap(M);
182   processScope(Loc->getScope());
183   processLocation(M, Loc->getInlinedAt());
184 }
185
186 void DebugInfoFinder::processType(DIType DT) {
187   if (!addType(DT))
188     return;
189   processScope(DT.getContext().resolve(TypeIdentifierMap));
190   if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
191     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
192     if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
193       for (MDTypeRef Ref : ST->getTypeArray())
194         processType(Ref.resolve(TypeIdentifierMap));
195       return;
196     }
197     for (Metadata *D : DCT->getElements()->operands()) {
198       if (DIType T = dyn_cast<MDType>(D))
199         processType(T);
200       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
201         processSubprogram(SP);
202     }
203   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
204     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
205   }
206 }
207
208 void DebugInfoFinder::processScope(DIScope Scope) {
209   if (!Scope)
210     return;
211   if (DIType Ty = dyn_cast<MDType>(Scope)) {
212     processType(Ty);
213     return;
214   }
215   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
216     addCompileUnit(CU);
217     return;
218   }
219   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
220     processSubprogram(SP);
221     return;
222   }
223   if (!addScope(Scope))
224     return;
225   if (auto *LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
226     processScope(LB->getScope());
227   } else if (auto *NS = dyn_cast<MDNamespace>(Scope)) {
228     processScope(NS->getScope());
229   }
230 }
231
232 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
233   if (!addSubprogram(SP))
234     return;
235   processScope(SP->getScope().resolve(TypeIdentifierMap));
236   processType(SP->getType());
237   for (auto *Element : SP->getTemplateParams()) {
238     if (auto *TType = dyn_cast<MDTemplateTypeParameter>(Element)) {
239       processType(TType->getType().resolve(TypeIdentifierMap));
240     } else if (auto *TVal = dyn_cast<MDTemplateValueParameter>(Element)) {
241       processType(TVal->getType().resolve(TypeIdentifierMap));
242     }
243   }
244 }
245
246 void DebugInfoFinder::processDeclare(const Module &M,
247                                      const DbgDeclareInst *DDI) {
248   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
249   if (!N)
250     return;
251   InitializeTypeMap(M);
252
253   DIVariable DV = dyn_cast<MDLocalVariable>(N);
254   if (!DV)
255     return;
256
257   if (!NodesSeen.insert(DV).second)
258     return;
259   processScope(DV->getScope());
260   processType(DV->getType().resolve(TypeIdentifierMap));
261 }
262
263 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
264   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
265   if (!N)
266     return;
267   InitializeTypeMap(M);
268
269   DIVariable DV = dyn_cast<MDLocalVariable>(N);
270   if (!DV)
271     return;
272
273   if (!NodesSeen.insert(DV).second)
274     return;
275   processScope(DV->getScope());
276   processType(DV->getType().resolve(TypeIdentifierMap));
277 }
278
279 bool DebugInfoFinder::addType(DIType DT) {
280   if (!DT)
281     return false;
282
283   if (!NodesSeen.insert(DT).second)
284     return false;
285
286   TYs.push_back(DT);
287   return true;
288 }
289
290 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
291   if (!CU)
292     return false;
293   if (!NodesSeen.insert(CU).second)
294     return false;
295
296   CUs.push_back(CU);
297   return true;
298 }
299
300 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
301   if (!DIG)
302     return false;
303
304   if (!NodesSeen.insert(DIG).second)
305     return false;
306
307   GVs.push_back(DIG);
308   return true;
309 }
310
311 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
312   if (!SP)
313     return false;
314
315   if (!NodesSeen.insert(SP).second)
316     return false;
317
318   SPs.push_back(SP);
319   return true;
320 }
321
322 bool DebugInfoFinder::addScope(DIScope Scope) {
323   if (!Scope)
324     return false;
325   // FIXME: Ocaml binding generates a scope with no content, we treat it
326   // as null for now.
327   if (Scope->getNumOperands() == 0)
328     return false;
329   if (!NodesSeen.insert(Scope).second)
330     return false;
331   Scopes.push_back(Scope);
332   return true;
333 }
334
335 //===----------------------------------------------------------------------===//
336 // DIDescriptor: dump routines for all descriptors.
337 //===----------------------------------------------------------------------===//
338
339 void DIDescriptor::dump() const {
340   print(dbgs());
341   dbgs() << '\n';
342 }
343
344 void DIDescriptor::print(raw_ostream &OS) const {
345   if (!get())
346     return;
347   get()->print(OS);
348 }
349
350 template <>
351 DIDescriptor
352 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
353   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
354 }
355 template <>
356 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
357   return MDScopeRef(Val).resolve(Map);
358 }
359 template <>
360 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
361   return MDTypeRef(Val).resolve(Map);
362 }
363
364 bool llvm::stripDebugInfo(Function &F) {
365   bool Changed = false;
366   for (BasicBlock &BB : F) {
367     for (Instruction &I : BB) {
368       if (I.getDebugLoc()) {
369         Changed = true;
370         I.setDebugLoc(DebugLoc());
371       }
372     }
373   }
374   return Changed;
375 }
376
377 bool llvm::StripDebugInfo(Module &M) {
378   bool Changed = false;
379
380   // Remove all of the calls to the debugger intrinsics, and remove them from
381   // the module.
382   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
383     while (!Declare->use_empty()) {
384       CallInst *CI = cast<CallInst>(Declare->user_back());
385       CI->eraseFromParent();
386     }
387     Declare->eraseFromParent();
388     Changed = true;
389   }
390
391   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
392     while (!DbgVal->use_empty()) {
393       CallInst *CI = cast<CallInst>(DbgVal->user_back());
394       CI->eraseFromParent();
395     }
396     DbgVal->eraseFromParent();
397     Changed = true;
398   }
399
400   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
401          NME = M.named_metadata_end(); NMI != NME;) {
402     NamedMDNode *NMD = NMI;
403     ++NMI;
404     if (NMD->getName().startswith("llvm.dbg.")) {
405       NMD->eraseFromParent();
406       Changed = true;
407     }
408   }
409
410   for (Function &F : M)
411     Changed |= stripDebugInfo(F);
412
413   if (GVMaterializer *Materializer = M.getMaterializer())
414     Materializer->setStripDebugInfo();
415
416   return Changed;
417 }
418
419 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
420   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
421           M.getModuleFlag("Debug Info Version")))
422     return Val->getZExtValue();
423   return 0;
424 }
425
426 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
427 llvm::makeSubprogramMap(const Module &M) {
428   DenseMap<const Function *, DISubprogram> R;
429
430   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
431   if (!CU_Nodes)
432     return R;
433
434   for (MDNode *N : CU_Nodes->operands()) {
435     DICompileUnit CUNode = cast<MDCompileUnit>(N);
436     for (DISubprogram SP : CUNode->getSubprograms()) {
437       if (Function *F = SP->getFunction())
438         R.insert(std::make_pair(F, SP));
439     }
440   }
441   return R;
442 }