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