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