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