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