DebugInfo: Remove dead code for accessing fields
[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 {
257   if (!isCompositeType())
258     return DIScopeRef(*this);
259   DICompositeType DTy(DbgNode);
260   if (!DTy.getIdentifier())
261     return DIScopeRef(*this);
262   return DIScopeRef(DTy.getIdentifier());
263 }
264
265 void DICompositeType::setContainingType(DICompositeType ContainingType) {
266   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
267   N->replaceVTableHolder(ContainingType.getRef());
268   DbgNode = N;
269 }
270
271 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
272   assert(CurFn && "Invalid function");
273   if (!getContext().isSubprogram())
274     return false;
275   // This variable is not inlined function argument if its scope
276   // does not describe current function.
277   return !DISubprogram(getContext()).describes(CurFn);
278 }
279
280 Function *DISubprogram::getFunction() const {
281   if (auto *N = get())
282     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
283       return dyn_cast<Function>(C->getValue());
284   return nullptr;
285 }
286
287 bool DISubprogram::describes(const Function *F) {
288   assert(F && "Invalid function");
289   if (F == getFunction())
290     return true;
291   StringRef Name = getLinkageName();
292   if (Name.empty())
293     Name = getName();
294   if (F->getName() == Name)
295     return true;
296   return false;
297 }
298
299 GlobalVariable *DIGlobalVariable::getGlobal() const {
300   return dyn_cast_or_null<GlobalVariable>(getConstant());
301 }
302
303 DIScopeRef DIScope::getContext() const {
304
305   if (isType())
306     return DIType(DbgNode).getContext();
307
308   if (isSubprogram())
309     return DIScopeRef(DISubprogram(DbgNode).getContext());
310
311   if (isLexicalBlock())
312     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
313
314   if (isLexicalBlockFile())
315     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
316
317   if (isNameSpace())
318     return DIScopeRef(DINameSpace(DbgNode).getContext());
319
320   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
321   return DIScopeRef(nullptr);
322 }
323
324 StringRef DIScope::getName() const {
325   if (isType())
326     return DIType(DbgNode).getName();
327   if (isSubprogram())
328     return DISubprogram(DbgNode).getName();
329   if (isNameSpace())
330     return DINameSpace(DbgNode).getName();
331   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
332           isCompileUnit()) &&
333          "Unhandled type of scope.");
334   return StringRef();
335 }
336
337 StringRef DIScope::getFilename() const {
338   if (auto *N = get())
339     if (auto *F = N->getFile())
340       return F->getFilename();
341   return "";
342 }
343
344 StringRef DIScope::getDirectory() const {
345   if (auto *N = get())
346     if (auto *F = N->getFile())
347       return F->getDirectory();
348   return "";
349 }
350
351 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
352   assert(Verify() && "Expected compile unit");
353   get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
354 }
355
356 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
357   assert(Verify() && "Expected compile unit");
358   get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
359 }
360
361 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
362                                         DILexicalBlockFile NewScope) {
363   assert(Verify());
364   assert(NewScope && "Expected valid scope");
365
366   const auto *Old = cast<MDLocation>(DbgNode);
367   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
368                                     NewScope, Old->getInlinedAt()));
369 }
370
371 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
372   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
373   return ++Ctx.pImpl->DiscriminatorTable[Key];
374 }
375
376 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
377                                        LLVMContext &VMContext) {
378   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
379   return cast<MDLocalVariable>(DV)
380       ->withInline(cast_or_null<MDLocation>(InlinedScope));
381 }
382
383 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
384   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
385   return cast<MDLocalVariable>(DV)->withoutInline();
386 }
387
388 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
389   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
390     return LocalScope->getSubprogram();
391   return nullptr;
392 }
393
394 DISubprogram llvm::getDISubprogram(const Function *F) {
395   // We look for the first instr that has a debug annotation leading back to F.
396   for (auto &BB : *F) {
397     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
398       return Inst.getDebugLoc();
399     });
400     if (Inst == BB.end())
401       continue;
402     DebugLoc DLoc = Inst->getDebugLoc();
403     const MDNode *Scope = DLoc.getInlinedAtScope();
404     DISubprogram Subprogram = getDISubprogram(Scope);
405     return Subprogram.describes(F) ? Subprogram : DISubprogram();
406   }
407
408   return DISubprogram();
409 }
410
411 DICompositeType llvm::getDICompositeType(DIType T) {
412   if (T.isCompositeType())
413     return DICompositeType(T);
414
415   if (T.isDerivedType()) {
416     // This function is currently used by dragonegg and dragonegg does
417     // not generate identifier for types, so using an empty map to resolve
418     // DerivedFrom should be fine.
419     DITypeIdentifierMap EmptyMap;
420     return getDICompositeType(
421         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
422   }
423
424   return DICompositeType();
425 }
426
427 DITypeIdentifierMap
428 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
429   DITypeIdentifierMap Map;
430   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
431     DICompileUnit CU(CU_Nodes->getOperand(CUi));
432     DIArray Retain = CU.getRetainedTypes();
433     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
434       if (!Retain.getElement(Ti).isCompositeType())
435         continue;
436       DICompositeType Ty(Retain.getElement(Ti));
437       if (MDString *TypeId = Ty.getIdentifier()) {
438         // Definition has priority over declaration.
439         // Try to insert (TypeId, Ty) to Map.
440         std::pair<DITypeIdentifierMap::iterator, bool> P =
441             Map.insert(std::make_pair(TypeId, Ty));
442         // If TypeId already exists in Map and this is a definition, replace
443         // whatever we had (declaration or definition) with the definition.
444         if (!P.second && !Ty.isForwardDecl())
445           P.first->second = Ty;
446       }
447     }
448   }
449   return Map;
450 }
451
452 //===----------------------------------------------------------------------===//
453 // DebugInfoFinder implementations.
454 //===----------------------------------------------------------------------===//
455
456 void DebugInfoFinder::reset() {
457   CUs.clear();
458   SPs.clear();
459   GVs.clear();
460   TYs.clear();
461   Scopes.clear();
462   NodesSeen.clear();
463   TypeIdentifierMap.clear();
464   TypeMapInitialized = false;
465 }
466
467 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
468   if (!TypeMapInitialized)
469     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
470       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
471       TypeMapInitialized = true;
472     }
473 }
474
475 void DebugInfoFinder::processModule(const Module &M) {
476   InitializeTypeMap(M);
477   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
478     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
479       DICompileUnit CU(CU_Nodes->getOperand(i));
480       addCompileUnit(CU);
481       DIArray GVs = CU.getGlobalVariables();
482       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
483         DIGlobalVariable DIG(GVs.getElement(i));
484         if (addGlobalVariable(DIG)) {
485           processScope(DIG.getContext());
486           processType(DIG.getType().resolve(TypeIdentifierMap));
487         }
488       }
489       DIArray SPs = CU.getSubprograms();
490       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
491         processSubprogram(DISubprogram(SPs.getElement(i)));
492       DIArray EnumTypes = CU.getEnumTypes();
493       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
494         processType(DIType(EnumTypes.getElement(i)));
495       DIArray RetainedTypes = CU.getRetainedTypes();
496       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
497         processType(DIType(RetainedTypes.getElement(i)));
498       DIArray Imports = CU.getImportedEntities();
499       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
500         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
501         if (!Import)
502           continue;
503         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
504         if (Entity.isType())
505           processType(DIType(Entity));
506         else if (Entity.isSubprogram())
507           processSubprogram(DISubprogram(Entity));
508         else if (Entity.isNameSpace())
509           processScope(DINameSpace(Entity).getContext());
510       }
511     }
512   }
513 }
514
515 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
516   if (!Loc)
517     return;
518   InitializeTypeMap(M);
519   processScope(Loc.getScope());
520   processLocation(M, Loc.getOrigLocation());
521 }
522
523 void DebugInfoFinder::processType(DIType DT) {
524   if (!addType(DT))
525     return;
526   processScope(DT.getContext().resolve(TypeIdentifierMap));
527   if (DT.isCompositeType()) {
528     DICompositeType DCT(DT);
529     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
530     if (DT.isSubroutineType()) {
531       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
532       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
533         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
534       return;
535     }
536     DIArray DA = DCT.getElements();
537     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
538       DIDescriptor D = DA.getElement(i);
539       if (D.isType())
540         processType(DIType(D));
541       else if (D.isSubprogram())
542         processSubprogram(DISubprogram(D));
543     }
544   } else if (DT.isDerivedType()) {
545     DIDerivedType DDT(DT);
546     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
547   }
548 }
549
550 void DebugInfoFinder::processScope(DIScope Scope) {
551   if (Scope.isType()) {
552     DIType Ty(Scope);
553     processType(Ty);
554     return;
555   }
556   if (Scope.isCompileUnit()) {
557     addCompileUnit(DICompileUnit(Scope));
558     return;
559   }
560   if (Scope.isSubprogram()) {
561     processSubprogram(DISubprogram(Scope));
562     return;
563   }
564   if (!addScope(Scope))
565     return;
566   if (Scope.isLexicalBlock()) {
567     DILexicalBlock LB(Scope);
568     processScope(LB.getContext());
569   } else if (Scope.isLexicalBlockFile()) {
570     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
571     processScope(LBF.getScope());
572   } else if (Scope.isNameSpace()) {
573     DINameSpace NS(Scope);
574     processScope(NS.getContext());
575   }
576 }
577
578 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
579   if (!addSubprogram(SP))
580     return;
581   processScope(SP.getContext().resolve(TypeIdentifierMap));
582   processType(SP.getType());
583   DIArray TParams = SP.getTemplateParams();
584   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
585     DIDescriptor Element = TParams.getElement(I);
586     if (Element.isTemplateTypeParameter()) {
587       DITemplateTypeParameter TType(Element);
588       processType(TType.getType().resolve(TypeIdentifierMap));
589     } else if (Element.isTemplateValueParameter()) {
590       DITemplateValueParameter TVal(Element);
591       processType(TVal.getType().resolve(TypeIdentifierMap));
592     }
593   }
594 }
595
596 void DebugInfoFinder::processDeclare(const Module &M,
597                                      const DbgDeclareInst *DDI) {
598   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
599   if (!N)
600     return;
601   InitializeTypeMap(M);
602
603   DIDescriptor DV(N);
604   if (!DV.isVariable())
605     return;
606
607   if (!NodesSeen.insert(DV).second)
608     return;
609   processScope(DIVariable(N).getContext());
610   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
611 }
612
613 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
614   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
615   if (!N)
616     return;
617   InitializeTypeMap(M);
618
619   DIDescriptor DV(N);
620   if (!DV.isVariable())
621     return;
622
623   if (!NodesSeen.insert(DV).second)
624     return;
625   processScope(DIVariable(N).getContext());
626   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
627 }
628
629 bool DebugInfoFinder::addType(DIType DT) {
630   if (!DT)
631     return false;
632
633   if (!NodesSeen.insert(DT).second)
634     return false;
635
636   TYs.push_back(DT);
637   return true;
638 }
639
640 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
641   if (!CU)
642     return false;
643   if (!NodesSeen.insert(CU).second)
644     return false;
645
646   CUs.push_back(CU);
647   return true;
648 }
649
650 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
651   if (!DIG)
652     return false;
653
654   if (!NodesSeen.insert(DIG).second)
655     return false;
656
657   GVs.push_back(DIG);
658   return true;
659 }
660
661 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
662   if (!SP)
663     return false;
664
665   if (!NodesSeen.insert(SP).second)
666     return false;
667
668   SPs.push_back(SP);
669   return true;
670 }
671
672 bool DebugInfoFinder::addScope(DIScope Scope) {
673   if (!Scope)
674     return false;
675   // FIXME: Ocaml binding generates a scope with no content, we treat it
676   // as null for now.
677   if (Scope->getNumOperands() == 0)
678     return false;
679   if (!NodesSeen.insert(Scope).second)
680     return false;
681   Scopes.push_back(Scope);
682   return true;
683 }
684
685 //===----------------------------------------------------------------------===//
686 // DIDescriptor: dump routines for all descriptors.
687 //===----------------------------------------------------------------------===//
688
689 void DIDescriptor::dump() const {
690   print(dbgs());
691   dbgs() << '\n';
692 }
693
694 void DIDescriptor::print(raw_ostream &OS) const {
695   if (!get())
696     return;
697   get()->print(OS);
698 }
699
700 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
701                           const LLVMContext &Ctx) {
702   if (!DL)
703     return;
704
705   DIScope Scope(DL.getScope());
706   assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
707   // Omit the directory, because it's likely to be long and uninteresting.
708   CommentOS << Scope.getFilename();
709   CommentOS << ':' << DL.getLine();
710   if (DL.getCol() != 0)
711     CommentOS << ':' << DL.getCol();
712
713   DebugLoc InlinedAtDL = DL.getInlinedAt();
714   if (!InlinedAtDL)
715     return;
716
717   CommentOS << " @[ ";
718   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
719   CommentOS << " ]";
720 }
721
722 void DIVariable::printExtendedName(raw_ostream &OS) const {
723   const LLVMContext &Ctx = DbgNode->getContext();
724   StringRef Res = getName();
725   if (!Res.empty())
726     OS << Res << "," << getLineNumber();
727   if (auto *InlinedAt = get()->getInlinedAt()) {
728     if (DebugLoc InlinedAtDL = InlinedAt) {
729       OS << " @[";
730       printDebugLoc(InlinedAtDL, OS, Ctx);
731       OS << "]";
732     }
733   }
734 }
735
736 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
737   assert(isDescriptorRef(V) &&
738          "DIDescriptorRef should be a MDString or MDNode");
739 }
740 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
741   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
742 }
743 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
744   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
745 }
746
747 template <>
748 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
749   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
750 }
751 template <>
752 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
753   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
754 }
755 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
756   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
757 }
758
759 bool llvm::stripDebugInfo(Function &F) {
760   bool Changed = false;
761   for (BasicBlock &BB : F) {
762     for (Instruction &I : BB) {
763       if (I.getDebugLoc()) {
764         Changed = true;
765         I.setDebugLoc(DebugLoc());
766       }
767     }
768   }
769   return Changed;
770 }
771
772 bool llvm::StripDebugInfo(Module &M) {
773   bool Changed = false;
774
775   // Remove all of the calls to the debugger intrinsics, and remove them from
776   // the module.
777   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
778     while (!Declare->use_empty()) {
779       CallInst *CI = cast<CallInst>(Declare->user_back());
780       CI->eraseFromParent();
781     }
782     Declare->eraseFromParent();
783     Changed = true;
784   }
785
786   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
787     while (!DbgVal->use_empty()) {
788       CallInst *CI = cast<CallInst>(DbgVal->user_back());
789       CI->eraseFromParent();
790     }
791     DbgVal->eraseFromParent();
792     Changed = true;
793   }
794
795   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
796          NME = M.named_metadata_end(); NMI != NME;) {
797     NamedMDNode *NMD = NMI;
798     ++NMI;
799     if (NMD->getName().startswith("llvm.dbg.")) {
800       NMD->eraseFromParent();
801       Changed = true;
802     }
803   }
804
805   for (Function &F : M)
806     Changed |= stripDebugInfo(F);
807
808   if (GVMaterializer *Materializer = M.getMaterializer())
809     Materializer->setStripDebugInfo();
810
811   return Changed;
812 }
813
814 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
815   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
816           M.getModuleFlag("Debug Info Version")))
817     return Val->getZExtValue();
818   return 0;
819 }
820
821 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
822 llvm::makeSubprogramMap(const Module &M) {
823   DenseMap<const Function *, DISubprogram> R;
824
825   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
826   if (!CU_Nodes)
827     return R;
828
829   for (MDNode *N : CU_Nodes->operands()) {
830     DICompileUnit CUNode(N);
831     DIArray SPs = CUNode.getSubprograms();
832     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
833       DISubprogram SP(SPs.getElement(i));
834       if (Function *F = SP.getFunction())
835         R.insert(std::make_pair(F, SP));
836     }
837   }
838   return R;
839 }