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