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