DebugInfo: Remove constructors for DIRef<>
[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 // DIDescriptor
38 //===----------------------------------------------------------------------===//
39
40 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
41   if (!DbgNode || Elt >= DbgNode->getNumOperands())
42     return nullptr;
43   return DbgNode->getOperand(Elt);
44 }
45
46 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
47   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
48 }
49
50 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
51   MDNode *Field = getNodeField(DbgNode, Elt);
52   return DIDescriptor(Field);
53 }
54
55 /// \brief Return the size reported by the variable's type.
56 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
57   DIType Ty = getType().resolve(Map);
58   // Follow derived types until we reach a type that
59   // reports back a size.
60   while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
61     DIDerivedType DT = cast<MDDerivedType>(Ty);
62     Ty = DT.getTypeDerivedFrom().resolve(Map);
63   }
64   assert(Ty.getSizeInBits() && "type with size 0");
65   return Ty.getSizeInBits();
66 }
67
68 //===----------------------------------------------------------------------===//
69 // Simple Descriptor Constructors and other Methods
70 //===----------------------------------------------------------------------===//
71
72 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
73   assert(DbgNode && "Trying to replace an unverified type!");
74   assert(DbgNode->isTemporary() && "Expected temporary node");
75   TempMDNode Temp(get());
76
77   // Since we use a TrackingVH for the node, its easy for clients to manufacture
78   // legitimate situations where they want to replaceAllUsesWith() on something
79   // which, due to uniquing, has merged with the source. We shield clients from
80   // this detail by allowing a value to be replaced with replaceAllUsesWith()
81   // itself.
82   if (Temp.get() == D.get()) {
83     DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
84     return;
85   }
86
87   Temp->replaceAllUsesWith(D.get());
88   DbgNode = D.get();
89 }
90
91 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
92   assert(DbgNode && "Trying to replace an unverified type!");
93   assert(DbgNode != D && "This replacement should always happen");
94   assert(DbgNode->isTemporary() && "Expected temporary node");
95   TempMDNode Node(get());
96   Node->replaceAllUsesWith(D);
97 }
98
99 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
100
101 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
102   assert(CurFn && "Invalid function");
103   DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
104   if (!SP)
105     return false;
106   // This variable is not inlined function argument if its scope
107   // does not describe current function.
108   return !SP.describes(CurFn);
109 }
110
111 Function *DISubprogram::getFunction() const {
112   if (auto *N = get())
113     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
114       return dyn_cast<Function>(C->getValue());
115   return nullptr;
116 }
117
118 bool DISubprogram::describes(const Function *F) {
119   assert(F && "Invalid function");
120   if (F == getFunction())
121     return true;
122   StringRef Name = getLinkageName();
123   if (Name.empty())
124     Name = getName();
125   if (F->getName() == Name)
126     return true;
127   return false;
128 }
129
130 GlobalVariable *DIGlobalVariable::getGlobal() const {
131   return dyn_cast_or_null<GlobalVariable>(getConstant());
132 }
133
134 DIScopeRef DIScope::getContext() const {
135   if (DIType T = dyn_cast<MDType>(*this))
136     return T.getContext();
137
138   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
139     return MDScopeRef(SP.getContext());
140
141   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
142     return MDScopeRef(LB.getContext());
143
144   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
145     return MDScopeRef(NS.getContext());
146
147   assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
148          "Unhandled type of scope.");
149   return MDScopeRef();
150 }
151
152 StringRef DIScope::getName() const {
153   if (DIType T = dyn_cast<MDType>(*this))
154     return T.getName();
155   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
156     return SP.getName();
157   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
158     return NS.getName();
159   assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
160           isa<MDCompileUnit>(*this)) &&
161          "Unhandled type of scope.");
162   return StringRef();
163 }
164
165 StringRef DIScope::getFilename() const {
166   if (auto *N = get())
167     if (auto *F = N->getFile())
168       return F->getFilename();
169   return "";
170 }
171
172 StringRef DIScope::getDirectory() const {
173   if (auto *N = get())
174     if (auto *F = N->getFile())
175       return F->getDirectory();
176   return "";
177 }
178
179 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
180   get()->replaceSubprograms(MDSubprogramArray(Subprograms));
181 }
182
183 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
184   get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
185 }
186
187 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
188                                         DILexicalBlockFile NewScope) {
189   assert(NewScope && "Expected valid scope");
190
191   const auto *Old = cast<MDLocation>(DbgNode);
192   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
193                                     NewScope, Old->getInlinedAt()));
194 }
195
196 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
197   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
198   return ++Ctx.pImpl->DiscriminatorTable[Key];
199 }
200
201 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
202                                        LLVMContext &VMContext) {
203   return cast<MDLocalVariable>(DV)
204       ->withInline(cast_or_null<MDLocation>(InlinedScope));
205 }
206
207 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
208   return cast<MDLocalVariable>(DV)->withoutInline();
209 }
210
211 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
212   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
213     return LocalScope->getSubprogram();
214   return nullptr;
215 }
216
217 DISubprogram llvm::getDISubprogram(const Function *F) {
218   // We look for the first instr that has a debug annotation leading back to F.
219   for (auto &BB : *F) {
220     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
221       return Inst.getDebugLoc();
222     });
223     if (Inst == BB.end())
224       continue;
225     DebugLoc DLoc = Inst->getDebugLoc();
226     const MDNode *Scope = DLoc.getInlinedAtScope();
227     DISubprogram Subprogram = getDISubprogram(Scope);
228     return Subprogram.describes(F) ? Subprogram : DISubprogram();
229   }
230
231   return DISubprogram();
232 }
233
234 DICompositeType llvm::getDICompositeType(DIType T) {
235   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
236     return C;
237
238   if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
239     // This function is currently used by dragonegg and dragonegg does
240     // not generate identifier for types, so using an empty map to resolve
241     // DerivedFrom should be fine.
242     DITypeIdentifierMap EmptyMap;
243     return getDICompositeType(
244         DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
245   }
246
247   return nullptr;
248 }
249
250 DITypeIdentifierMap
251 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
252   DITypeIdentifierMap Map;
253   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
254     DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
255     DIArray Retain = CU.getRetainedTypes();
256     for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
257       if (!isa<MDCompositeType>(Retain[Ti]))
258         continue;
259       DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
260       if (MDString *TypeId = Ty.getIdentifier()) {
261         // Definition has priority over declaration.
262         // Try to insert (TypeId, Ty) to Map.
263         std::pair<DITypeIdentifierMap::iterator, bool> P =
264             Map.insert(std::make_pair(TypeId, Ty));
265         // If TypeId already exists in Map and this is a definition, replace
266         // whatever we had (declaration or definition) with the definition.
267         if (!P.second && !Ty.isForwardDecl())
268           P.first->second = Ty;
269       }
270     }
271   }
272   return Map;
273 }
274
275 //===----------------------------------------------------------------------===//
276 // DebugInfoFinder implementations.
277 //===----------------------------------------------------------------------===//
278
279 void DebugInfoFinder::reset() {
280   CUs.clear();
281   SPs.clear();
282   GVs.clear();
283   TYs.clear();
284   Scopes.clear();
285   NodesSeen.clear();
286   TypeIdentifierMap.clear();
287   TypeMapInitialized = false;
288 }
289
290 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
291   if (!TypeMapInitialized)
292     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
293       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
294       TypeMapInitialized = true;
295     }
296 }
297
298 void DebugInfoFinder::processModule(const Module &M) {
299   InitializeTypeMap(M);
300   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
301     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
302       DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
303       addCompileUnit(CU);
304       for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
305         if (addGlobalVariable(DIG)) {
306           processScope(DIG.getContext());
307           processType(DIG.getType().resolve(TypeIdentifierMap));
308         }
309       }
310       for (auto *SP : CU->getSubprograms())
311         processSubprogram(SP);
312       for (auto *ET : CU->getEnumTypes())
313         processType(ET);
314       for (auto *RT : CU->getRetainedTypes())
315         processType(RT);
316       for (DIImportedEntity Import : CU->getImportedEntities()) {
317         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
318         if (auto *T = dyn_cast<MDType>(Entity))
319           processType(T);
320         else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
321           processSubprogram(SP);
322         else if (auto *NS = dyn_cast<MDNamespace>(Entity))
323           processScope(NS->getScope());
324       }
325     }
326   }
327 }
328
329 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
330   if (!Loc)
331     return;
332   InitializeTypeMap(M);
333   processScope(Loc.getScope());
334   processLocation(M, Loc.getOrigLocation());
335 }
336
337 void DebugInfoFinder::processType(DIType DT) {
338   if (!addType(DT))
339     return;
340   processScope(DT.getContext().resolve(TypeIdentifierMap));
341   if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
342     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
343     if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
344       for (MDTypeRef Ref : ST->getTypeArray())
345         processType(Ref.resolve(TypeIdentifierMap));
346       return;
347     }
348     for (Metadata *D : DCT->getElements()->operands()) {
349       if (DIType T = dyn_cast<MDType>(D))
350         processType(T);
351       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
352         processSubprogram(SP);
353     }
354   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
355     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
356   }
357 }
358
359 void DebugInfoFinder::processScope(DIScope Scope) {
360   if (!Scope)
361     return;
362   if (DIType Ty = dyn_cast<MDType>(Scope)) {
363     processType(Ty);
364     return;
365   }
366   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
367     addCompileUnit(CU);
368     return;
369   }
370   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
371     processSubprogram(SP);
372     return;
373   }
374   if (!addScope(Scope))
375     return;
376   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
377     processScope(LB.getContext());
378   } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
379     processScope(NS.getContext());
380   }
381 }
382
383 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
384   if (!addSubprogram(SP))
385     return;
386   processScope(SP.getContext().resolve(TypeIdentifierMap));
387   processType(SP.getType());
388   for (auto *Element : SP.getTemplateParams()) {
389     if (DITemplateTypeParameter TType =
390             dyn_cast<MDTemplateTypeParameter>(Element)) {
391       processType(TType.getType().resolve(TypeIdentifierMap));
392     } else if (DITemplateValueParameter TVal =
393                    dyn_cast<MDTemplateValueParameter>(Element)) {
394       processType(TVal.getType().resolve(TypeIdentifierMap));
395     }
396   }
397 }
398
399 void DebugInfoFinder::processDeclare(const Module &M,
400                                      const DbgDeclareInst *DDI) {
401   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
402   if (!N)
403     return;
404   InitializeTypeMap(M);
405
406   DIVariable DV = dyn_cast<MDLocalVariable>(N);
407   if (!DV)
408     return;
409
410   if (!NodesSeen.insert(DV).second)
411     return;
412   processScope(DV.getContext());
413   processType(DV.getType().resolve(TypeIdentifierMap));
414 }
415
416 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
417   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
418   if (!N)
419     return;
420   InitializeTypeMap(M);
421
422   DIVariable DV = dyn_cast<MDLocalVariable>(N);
423   if (!DV)
424     return;
425
426   if (!NodesSeen.insert(DV).second)
427     return;
428   processScope(DV.getContext());
429   processType(DV.getType().resolve(TypeIdentifierMap));
430 }
431
432 bool DebugInfoFinder::addType(DIType DT) {
433   if (!DT)
434     return false;
435
436   if (!NodesSeen.insert(DT).second)
437     return false;
438
439   TYs.push_back(DT);
440   return true;
441 }
442
443 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
444   if (!CU)
445     return false;
446   if (!NodesSeen.insert(CU).second)
447     return false;
448
449   CUs.push_back(CU);
450   return true;
451 }
452
453 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
454   if (!DIG)
455     return false;
456
457   if (!NodesSeen.insert(DIG).second)
458     return false;
459
460   GVs.push_back(DIG);
461   return true;
462 }
463
464 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
465   if (!SP)
466     return false;
467
468   if (!NodesSeen.insert(SP).second)
469     return false;
470
471   SPs.push_back(SP);
472   return true;
473 }
474
475 bool DebugInfoFinder::addScope(DIScope Scope) {
476   if (!Scope)
477     return false;
478   // FIXME: Ocaml binding generates a scope with no content, we treat it
479   // as null for now.
480   if (Scope->getNumOperands() == 0)
481     return false;
482   if (!NodesSeen.insert(Scope).second)
483     return false;
484   Scopes.push_back(Scope);
485   return true;
486 }
487
488 //===----------------------------------------------------------------------===//
489 // DIDescriptor: dump routines for all descriptors.
490 //===----------------------------------------------------------------------===//
491
492 void DIDescriptor::dump() const {
493   print(dbgs());
494   dbgs() << '\n';
495 }
496
497 void DIDescriptor::print(raw_ostream &OS) const {
498   if (!get())
499     return;
500   get()->print(OS);
501 }
502
503 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
504                           const LLVMContext &Ctx) {
505   if (!DL)
506     return;
507
508   DIScope Scope = cast<MDScope>(DL.getScope());
509   // Omit the directory, because it's likely to be long and uninteresting.
510   CommentOS << Scope.getFilename();
511   CommentOS << ':' << DL.getLine();
512   if (DL.getCol() != 0)
513     CommentOS << ':' << DL.getCol();
514
515   DebugLoc InlinedAtDL = DL.getInlinedAt();
516   if (!InlinedAtDL)
517     return;
518
519   CommentOS << " @[ ";
520   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
521   CommentOS << " ]";
522 }
523
524 void DIVariable::printExtendedName(raw_ostream &OS) const {
525   const LLVMContext &Ctx = DbgNode->getContext();
526   StringRef Res = getName();
527   if (!Res.empty())
528     OS << Res << "," << getLineNumber();
529   if (auto *InlinedAt = get()->getInlinedAt()) {
530     if (DebugLoc InlinedAtDL = InlinedAt) {
531       OS << " @[";
532       printDebugLoc(InlinedAtDL, OS, Ctx);
533       OS << "]";
534     }
535   }
536 }
537
538 template <>
539 DIDescriptor
540 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
541   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
542 }
543 template <>
544 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
545   return MDScopeRef(Val).resolve(Map);
546 }
547 template <>
548 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
549   return MDTypeRef(Val).resolve(Map);
550 }
551
552 bool llvm::stripDebugInfo(Function &F) {
553   bool Changed = false;
554   for (BasicBlock &BB : F) {
555     for (Instruction &I : BB) {
556       if (I.getDebugLoc()) {
557         Changed = true;
558         I.setDebugLoc(DebugLoc());
559       }
560     }
561   }
562   return Changed;
563 }
564
565 bool llvm::StripDebugInfo(Module &M) {
566   bool Changed = false;
567
568   // Remove all of the calls to the debugger intrinsics, and remove them from
569   // the module.
570   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
571     while (!Declare->use_empty()) {
572       CallInst *CI = cast<CallInst>(Declare->user_back());
573       CI->eraseFromParent();
574     }
575     Declare->eraseFromParent();
576     Changed = true;
577   }
578
579   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
580     while (!DbgVal->use_empty()) {
581       CallInst *CI = cast<CallInst>(DbgVal->user_back());
582       CI->eraseFromParent();
583     }
584     DbgVal->eraseFromParent();
585     Changed = true;
586   }
587
588   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
589          NME = M.named_metadata_end(); NMI != NME;) {
590     NamedMDNode *NMD = NMI;
591     ++NMI;
592     if (NMD->getName().startswith("llvm.dbg.")) {
593       NMD->eraseFromParent();
594       Changed = true;
595     }
596   }
597
598   for (Function &F : M)
599     Changed |= stripDebugInfo(F);
600
601   if (GVMaterializer *Materializer = M.getMaterializer())
602     Materializer->setStripDebugInfo();
603
604   return Changed;
605 }
606
607 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
608   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
609           M.getModuleFlag("Debug Info Version")))
610     return Val->getZExtValue();
611   return 0;
612 }
613
614 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
615 llvm::makeSubprogramMap(const Module &M) {
616   DenseMap<const Function *, DISubprogram> R;
617
618   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
619   if (!CU_Nodes)
620     return R;
621
622   for (MDNode *N : CU_Nodes->operands()) {
623     DICompileUnit CUNode = cast<MDCompileUnit>(N);
624     for (DISubprogram SP : CUNode->getSubprograms()) {
625       if (Function *F = SP.getFunction())
626         R.insert(std::make_pair(F, SP));
627     }
628   }
629   return R;
630 }