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