Fix PR23045.
[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 {
224   if (!isCompileUnit())
225     return false;
226
227   // Don't bother verifying the compilation directory or producer string
228   // as those could be empty.
229   return !getFilename().empty();
230 }
231
232 bool DIObjCProperty::Verify() const { return isObjCProperty(); }
233
234 /// \brief Check if a value can be a reference to a type.
235 static bool isTypeRef(const Metadata *MD) {
236   if (!MD)
237     return true;
238   if (auto *S = dyn_cast<MDString>(MD))
239     return !S->getString().empty();
240   return isa<MDType>(MD);
241 }
242
243 /// \brief Check if a value can be a ScopeRef.
244 static bool isScopeRef(const Metadata *MD) {
245   if (!MD)
246     return true;
247   if (auto *S = dyn_cast<MDString>(MD))
248     return !S->getString().empty();
249   return isa<MDScope>(MD);
250 }
251
252 #ifndef NDEBUG
253 /// \brief Check if a value can be a DescriptorRef.
254 static bool isDescriptorRef(const Metadata *MD) {
255   if (!MD)
256     return true;
257   if (auto *S = dyn_cast<MDString>(MD))
258     return !S->getString().empty();
259   return isa<MDNode>(MD);
260 }
261 #endif
262
263 bool DIType::Verify() const {
264   auto *N = dyn_cast_or_null<MDType>(DbgNode);
265   if (!N)
266     return false;
267   if (!isScopeRef(N->getScope()))
268     return false;
269
270   // DIType is abstract, it should be a BasicType, a DerivedType or
271   // a CompositeType.
272   if (isBasicType())
273     return DIBasicType(DbgNode).Verify();
274
275   // FIXME: Sink this into the various subclass verifies.
276   if (getFilename().empty()) {
277     // Check whether the filename is allowed to be empty.
278     uint16_t Tag = getTag();
279     if (Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
280         Tag != dwarf::DW_TAG_pointer_type &&
281         Tag != dwarf::DW_TAG_ptr_to_member_type &&
282         Tag != dwarf::DW_TAG_reference_type &&
283         Tag != dwarf::DW_TAG_rvalue_reference_type &&
284         Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
285         Tag != dwarf::DW_TAG_enumeration_type &&
286         Tag != dwarf::DW_TAG_subroutine_type &&
287         Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
288         Tag != dwarf::DW_TAG_structure_type && Tag != dwarf::DW_TAG_member &&
289         Tag != dwarf::DW_TAG_typedef)
290       return false;
291   }
292
293   if (isCompositeType())
294     return DICompositeType(DbgNode).Verify();
295   if (isDerivedType())
296     return DIDerivedType(DbgNode).Verify();
297   return false;
298 }
299
300 bool DIBasicType::Verify() const {
301   return dyn_cast_or_null<MDBasicType>(DbgNode);
302 }
303
304 bool DIDerivedType::Verify() const {
305   auto *N = dyn_cast_or_null<MDDerivedTypeBase>(DbgNode);
306   if (!N)
307     return false;
308   if (getTag() == dwarf::DW_TAG_ptr_to_member_type) {
309     auto *D = dyn_cast<MDDerivedType>(N);
310     if (!D)
311       return false;
312     if (!isTypeRef(D->getExtraData()))
313       return false;
314   }
315   return isTypeRef(N->getBaseType());
316 }
317
318 bool DICompositeType::Verify() const {
319   auto *N = dyn_cast_or_null<MDCompositeTypeBase>(DbgNode);
320   return N && isTypeRef(N->getBaseType()) && isTypeRef(N->getVTableHolder()) &&
321          !(isLValueReference() && isRValueReference());
322 }
323
324 bool DISubprogram::Verify() const {
325   auto *N = dyn_cast_or_null<MDSubprogram>(DbgNode);
326   if (!N)
327     return false;
328
329   if (!isScopeRef(N->getScope()))
330     return false;
331
332   if (auto *Op = N->getType())
333     if (!isa<MDNode>(Op))
334       return false;
335
336   if (!isTypeRef(getContainingType()))
337     return false;
338
339   if (isLValueReference() && isRValueReference())
340     return false;
341
342   // If a DISubprogram has an llvm::Function*, then scope chains from all
343   // instructions within the function should lead to this DISubprogram.
344   if (auto *F = getFunction()) {
345     for (auto &BB : *F) {
346       for (auto &I : BB) {
347         MDLocation *DL = I.getDebugLoc();
348         if (!DL)
349           continue;
350
351         // walk the inlined-at scopes
352         MDScope *Scope = DL->getInlinedAtScope();
353         if (!Scope)
354           return false;
355         while (!isa<MDSubprogram>(Scope)) {
356           Scope = cast<MDLexicalBlockBase>(Scope)->getScope();
357           if (!Scope)
358             return false;
359         }
360         if (!DISubprogram(Scope).describes(F))
361           return false;
362       }
363     }
364   }
365
366   return true;
367 }
368
369 bool DIGlobalVariable::Verify() const {
370   auto *N = dyn_cast_or_null<MDGlobalVariable>(DbgNode);
371
372   if (!N)
373     return false;
374
375   if (N->getDisplayName().empty())
376     return false;
377
378   if (auto *Op = N->getScope())
379     if (!isa<MDNode>(Op))
380       return false;
381
382   if (auto *Op = N->getStaticDataMemberDeclaration())
383     if (!isa<MDNode>(Op))
384       return false;
385
386   return isTypeRef(N->getType());
387 }
388
389 bool DIVariable::Verify() const {
390   auto *N = dyn_cast_or_null<MDLocalVariable>(DbgNode);
391
392   if (!N)
393     return false;
394
395   if (auto *Op = N->getScope())
396     if (!isa<MDNode>(Op))
397       return false;
398
399   return isTypeRef(N->getType());
400 }
401
402 bool DILocation::Verify() const {
403   return dyn_cast_or_null<MDLocation>(DbgNode);
404 }
405 bool DINameSpace::Verify() const {
406   return dyn_cast_or_null<MDNamespace>(DbgNode);
407 }
408 bool DIFile::Verify() const { return dyn_cast_or_null<MDFile>(DbgNode); }
409 bool DIEnumerator::Verify() const {
410   return dyn_cast_or_null<MDEnumerator>(DbgNode);
411 }
412 bool DISubrange::Verify() const {
413   return dyn_cast_or_null<MDSubrange>(DbgNode);
414 }
415 bool DILexicalBlock::Verify() const {
416   return dyn_cast_or_null<MDLexicalBlock>(DbgNode);
417 }
418 bool DILexicalBlockFile::Verify() const {
419   return dyn_cast_or_null<MDLexicalBlockFile>(DbgNode);
420 }
421 bool DITemplateTypeParameter::Verify() const {
422   return dyn_cast_or_null<MDTemplateTypeParameter>(DbgNode);
423 }
424 bool DITemplateValueParameter::Verify() const {
425   return dyn_cast_or_null<MDTemplateValueParameter>(DbgNode);
426 }
427 bool DIImportedEntity::Verify() const {
428   return dyn_cast_or_null<MDImportedEntity>(DbgNode);
429 }
430
431 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
432   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
433   if (Elements)
434     N->replaceElements(cast<MDTuple>(Elements));
435   if (TParams)
436     N->replaceTemplateParams(cast<MDTuple>(TParams));
437   DbgNode = N;
438 }
439
440 DIScopeRef DIScope::getRef() const {
441   if (!isCompositeType())
442     return DIScopeRef(*this);
443   DICompositeType DTy(DbgNode);
444   if (!DTy.getIdentifier())
445     return DIScopeRef(*this);
446   return DIScopeRef(DTy.getIdentifier());
447 }
448
449 void DICompositeType::setContainingType(DICompositeType ContainingType) {
450   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
451   N->replaceVTableHolder(ContainingType.getRef());
452   DbgNode = N;
453 }
454
455 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
456   assert(CurFn && "Invalid function");
457   if (!getContext().isSubprogram())
458     return false;
459   // This variable is not inlined function argument if its scope
460   // does not describe current function.
461   return !DISubprogram(getContext()).describes(CurFn);
462 }
463
464 Function *DISubprogram::getFunction() const {
465   if (auto *N = get())
466     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
467       return dyn_cast<Function>(C->getValue());
468   return nullptr;
469 }
470
471 bool DISubprogram::describes(const Function *F) {
472   assert(F && "Invalid function");
473   if (F == getFunction())
474     return true;
475   StringRef Name = getLinkageName();
476   if (Name.empty())
477     Name = getName();
478   if (F->getName() == Name)
479     return true;
480   return false;
481 }
482
483 GlobalVariable *DIGlobalVariable::getGlobal() const {
484   return dyn_cast_or_null<GlobalVariable>(getConstant());
485 }
486
487 DIScopeRef DIScope::getContext() const {
488
489   if (isType())
490     return DIType(DbgNode).getContext();
491
492   if (isSubprogram())
493     return DIScopeRef(DISubprogram(DbgNode).getContext());
494
495   if (isLexicalBlock())
496     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
497
498   if (isLexicalBlockFile())
499     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
500
501   if (isNameSpace())
502     return DIScopeRef(DINameSpace(DbgNode).getContext());
503
504   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
505   return DIScopeRef(nullptr);
506 }
507
508 StringRef DIScope::getName() const {
509   if (isType())
510     return DIType(DbgNode).getName();
511   if (isSubprogram())
512     return DISubprogram(DbgNode).getName();
513   if (isNameSpace())
514     return DINameSpace(DbgNode).getName();
515   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
516           isCompileUnit()) &&
517          "Unhandled type of scope.");
518   return StringRef();
519 }
520
521 StringRef DIScope::getFilename() const {
522   if (auto *N = get())
523     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
524   return "";
525 }
526
527 StringRef DIScope::getDirectory() const {
528   if (auto *N = get())
529     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
530   return "";
531 }
532
533 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
534   assert(Verify() && "Expected compile unit");
535   get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
536 }
537
538 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
539   assert(Verify() && "Expected compile unit");
540   get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
541 }
542
543 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
544                                         DILexicalBlockFile NewScope) {
545   assert(Verify());
546   assert(NewScope && "Expected valid scope");
547
548   const auto *Old = cast<MDLocation>(DbgNode);
549   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
550                                     NewScope, Old->getInlinedAt()));
551 }
552
553 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
554   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
555   return ++Ctx.pImpl->DiscriminatorTable[Key];
556 }
557
558 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
559                                        LLVMContext &VMContext) {
560   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
561   return cast<MDLocalVariable>(DV)
562       ->withInline(cast_or_null<MDLocation>(InlinedScope));
563 }
564
565 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
566   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
567   return cast<MDLocalVariable>(DV)->withoutInline();
568 }
569
570 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
571   DIDescriptor D(Scope);
572   if (D.isSubprogram())
573     return DISubprogram(Scope);
574
575   if (D.isLexicalBlockFile())
576     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
577
578   if (D.isLexicalBlock())
579     return getDISubprogram(DILexicalBlock(Scope).getContext());
580
581   return DISubprogram();
582 }
583
584 DISubprogram llvm::getDISubprogram(const Function *F) {
585   // We look for the first instr that has a debug annotation leading back to F.
586   for (auto &BB : *F) {
587     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
588       return Inst.getDebugLoc();
589     });
590     if (Inst == BB.end())
591       continue;
592     DebugLoc DLoc = Inst->getDebugLoc();
593     const MDNode *Scope = DLoc.getInlinedAtScope();
594     DISubprogram Subprogram = getDISubprogram(Scope);
595     return Subprogram.describes(F) ? Subprogram : DISubprogram();
596   }
597
598   return DISubprogram();
599 }
600
601 DICompositeType llvm::getDICompositeType(DIType T) {
602   if (T.isCompositeType())
603     return DICompositeType(T);
604
605   if (T.isDerivedType()) {
606     // This function is currently used by dragonegg and dragonegg does
607     // not generate identifier for types, so using an empty map to resolve
608     // DerivedFrom should be fine.
609     DITypeIdentifierMap EmptyMap;
610     return getDICompositeType(
611         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
612   }
613
614   return DICompositeType();
615 }
616
617 DITypeIdentifierMap
618 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
619   DITypeIdentifierMap Map;
620   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
621     DICompileUnit CU(CU_Nodes->getOperand(CUi));
622     DIArray Retain = CU.getRetainedTypes();
623     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
624       if (!Retain.getElement(Ti).isCompositeType())
625         continue;
626       DICompositeType Ty(Retain.getElement(Ti));
627       if (MDString *TypeId = Ty.getIdentifier()) {
628         // Definition has priority over declaration.
629         // Try to insert (TypeId, Ty) to Map.
630         std::pair<DITypeIdentifierMap::iterator, bool> P =
631             Map.insert(std::make_pair(TypeId, Ty));
632         // If TypeId already exists in Map and this is a definition, replace
633         // whatever we had (declaration or definition) with the definition.
634         if (!P.second && !Ty.isForwardDecl())
635           P.first->second = Ty;
636       }
637     }
638   }
639   return Map;
640 }
641
642 //===----------------------------------------------------------------------===//
643 // DebugInfoFinder implementations.
644 //===----------------------------------------------------------------------===//
645
646 void DebugInfoFinder::reset() {
647   CUs.clear();
648   SPs.clear();
649   GVs.clear();
650   TYs.clear();
651   Scopes.clear();
652   NodesSeen.clear();
653   TypeIdentifierMap.clear();
654   TypeMapInitialized = false;
655 }
656
657 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
658   if (!TypeMapInitialized)
659     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
660       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
661       TypeMapInitialized = true;
662     }
663 }
664
665 void DebugInfoFinder::processModule(const Module &M) {
666   InitializeTypeMap(M);
667   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
668     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
669       DICompileUnit CU(CU_Nodes->getOperand(i));
670       addCompileUnit(CU);
671       DIArray GVs = CU.getGlobalVariables();
672       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
673         DIGlobalVariable DIG(GVs.getElement(i));
674         if (addGlobalVariable(DIG)) {
675           processScope(DIG.getContext());
676           processType(DIG.getType().resolve(TypeIdentifierMap));
677         }
678       }
679       DIArray SPs = CU.getSubprograms();
680       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
681         processSubprogram(DISubprogram(SPs.getElement(i)));
682       DIArray EnumTypes = CU.getEnumTypes();
683       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
684         processType(DIType(EnumTypes.getElement(i)));
685       DIArray RetainedTypes = CU.getRetainedTypes();
686       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
687         processType(DIType(RetainedTypes.getElement(i)));
688       DIArray Imports = CU.getImportedEntities();
689       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
690         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
691         if (!Import)
692           continue;
693         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
694         if (Entity.isType())
695           processType(DIType(Entity));
696         else if (Entity.isSubprogram())
697           processSubprogram(DISubprogram(Entity));
698         else if (Entity.isNameSpace())
699           processScope(DINameSpace(Entity).getContext());
700       }
701     }
702   }
703 }
704
705 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
706   if (!Loc)
707     return;
708   InitializeTypeMap(M);
709   processScope(Loc.getScope());
710   processLocation(M, Loc.getOrigLocation());
711 }
712
713 void DebugInfoFinder::processType(DIType DT) {
714   if (!addType(DT))
715     return;
716   processScope(DT.getContext().resolve(TypeIdentifierMap));
717   if (DT.isCompositeType()) {
718     DICompositeType DCT(DT);
719     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
720     if (DT.isSubroutineType()) {
721       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
722       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
723         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
724       return;
725     }
726     DIArray DA = DCT.getElements();
727     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
728       DIDescriptor D = DA.getElement(i);
729       if (D.isType())
730         processType(DIType(D));
731       else if (D.isSubprogram())
732         processSubprogram(DISubprogram(D));
733     }
734   } else if (DT.isDerivedType()) {
735     DIDerivedType DDT(DT);
736     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
737   }
738 }
739
740 void DebugInfoFinder::processScope(DIScope Scope) {
741   if (Scope.isType()) {
742     DIType Ty(Scope);
743     processType(Ty);
744     return;
745   }
746   if (Scope.isCompileUnit()) {
747     addCompileUnit(DICompileUnit(Scope));
748     return;
749   }
750   if (Scope.isSubprogram()) {
751     processSubprogram(DISubprogram(Scope));
752     return;
753   }
754   if (!addScope(Scope))
755     return;
756   if (Scope.isLexicalBlock()) {
757     DILexicalBlock LB(Scope);
758     processScope(LB.getContext());
759   } else if (Scope.isLexicalBlockFile()) {
760     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
761     processScope(LBF.getScope());
762   } else if (Scope.isNameSpace()) {
763     DINameSpace NS(Scope);
764     processScope(NS.getContext());
765   }
766 }
767
768 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
769   if (!addSubprogram(SP))
770     return;
771   processScope(SP.getContext().resolve(TypeIdentifierMap));
772   processType(SP.getType());
773   DIArray TParams = SP.getTemplateParams();
774   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
775     DIDescriptor Element = TParams.getElement(I);
776     if (Element.isTemplateTypeParameter()) {
777       DITemplateTypeParameter TType(Element);
778       processType(TType.getType().resolve(TypeIdentifierMap));
779     } else if (Element.isTemplateValueParameter()) {
780       DITemplateValueParameter TVal(Element);
781       processType(TVal.getType().resolve(TypeIdentifierMap));
782     }
783   }
784 }
785
786 void DebugInfoFinder::processDeclare(const Module &M,
787                                      const DbgDeclareInst *DDI) {
788   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
789   if (!N)
790     return;
791   InitializeTypeMap(M);
792
793   DIDescriptor DV(N);
794   if (!DV.isVariable())
795     return;
796
797   if (!NodesSeen.insert(DV).second)
798     return;
799   processScope(DIVariable(N).getContext());
800   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
801 }
802
803 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
804   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
805   if (!N)
806     return;
807   InitializeTypeMap(M);
808
809   DIDescriptor DV(N);
810   if (!DV.isVariable())
811     return;
812
813   if (!NodesSeen.insert(DV).second)
814     return;
815   processScope(DIVariable(N).getContext());
816   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
817 }
818
819 bool DebugInfoFinder::addType(DIType DT) {
820   if (!DT)
821     return false;
822
823   if (!NodesSeen.insert(DT).second)
824     return false;
825
826   TYs.push_back(DT);
827   return true;
828 }
829
830 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
831   if (!CU)
832     return false;
833   if (!NodesSeen.insert(CU).second)
834     return false;
835
836   CUs.push_back(CU);
837   return true;
838 }
839
840 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
841   if (!DIG)
842     return false;
843
844   if (!NodesSeen.insert(DIG).second)
845     return false;
846
847   GVs.push_back(DIG);
848   return true;
849 }
850
851 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
852   if (!SP)
853     return false;
854
855   if (!NodesSeen.insert(SP).second)
856     return false;
857
858   SPs.push_back(SP);
859   return true;
860 }
861
862 bool DebugInfoFinder::addScope(DIScope Scope) {
863   if (!Scope)
864     return false;
865   // FIXME: Ocaml binding generates a scope with no content, we treat it
866   // as null for now.
867   if (Scope->getNumOperands() == 0)
868     return false;
869   if (!NodesSeen.insert(Scope).second)
870     return false;
871   Scopes.push_back(Scope);
872   return true;
873 }
874
875 //===----------------------------------------------------------------------===//
876 // DIDescriptor: dump routines for all descriptors.
877 //===----------------------------------------------------------------------===//
878
879 void DIDescriptor::dump() const {
880   print(dbgs());
881   dbgs() << '\n';
882 }
883
884 void DIDescriptor::print(raw_ostream &OS) const {
885   if (!get())
886     return;
887   get()->print(OS);
888 }
889
890 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
891                           const LLVMContext &Ctx) {
892   if (!DL)
893     return;
894
895   DIScope Scope(DL.getScope());
896   assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
897   // Omit the directory, because it's likely to be long and uninteresting.
898   CommentOS << Scope.getFilename();
899   CommentOS << ':' << DL.getLine();
900   if (DL.getCol() != 0)
901     CommentOS << ':' << DL.getCol();
902
903   DebugLoc InlinedAtDL = DL.getInlinedAt();
904   if (!InlinedAtDL)
905     return;
906
907   CommentOS << " @[ ";
908   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
909   CommentOS << " ]";
910 }
911
912 void DIVariable::printExtendedName(raw_ostream &OS) const {
913   const LLVMContext &Ctx = DbgNode->getContext();
914   StringRef Res = getName();
915   if (!Res.empty())
916     OS << Res << "," << getLineNumber();
917   if (auto *InlinedAt = get()->getInlinedAt()) {
918     if (DebugLoc InlinedAtDL = InlinedAt) {
919       OS << " @[";
920       printDebugLoc(InlinedAtDL, OS, Ctx);
921       OS << "]";
922     }
923   }
924 }
925
926 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
927   assert(isDescriptorRef(V) &&
928          "DIDescriptorRef should be a MDString or MDNode");
929 }
930 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
931   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
932 }
933 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
934   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
935 }
936
937 template <>
938 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
939   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
940 }
941 template <>
942 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
943   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
944 }
945 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
946   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
947 }
948
949 bool llvm::stripDebugInfo(Function &F) {
950   bool Changed = false;
951   for (BasicBlock &BB : F) {
952     for (Instruction &I : BB) {
953       if (I.getDebugLoc()) {
954         Changed = true;
955         I.setDebugLoc(DebugLoc());
956       }
957     }
958   }
959   return Changed;
960 }
961
962 bool llvm::StripDebugInfo(Module &M) {
963   bool Changed = false;
964
965   // Remove all of the calls to the debugger intrinsics, and remove them from
966   // the module.
967   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
968     while (!Declare->use_empty()) {
969       CallInst *CI = cast<CallInst>(Declare->user_back());
970       CI->eraseFromParent();
971     }
972     Declare->eraseFromParent();
973     Changed = true;
974   }
975
976   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
977     while (!DbgVal->use_empty()) {
978       CallInst *CI = cast<CallInst>(DbgVal->user_back());
979       CI->eraseFromParent();
980     }
981     DbgVal->eraseFromParent();
982     Changed = true;
983   }
984
985   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
986          NME = M.named_metadata_end(); NMI != NME;) {
987     NamedMDNode *NMD = NMI;
988     ++NMI;
989     if (NMD->getName().startswith("llvm.dbg.")) {
990       NMD->eraseFromParent();
991       Changed = true;
992     }
993   }
994
995   for (Function &F : M)
996     Changed |= stripDebugInfo(F);
997
998   if ( GVMaterializer *Materializer = M.getMaterializer())
999     Materializer->setStripDebugInfo();
1000
1001   return Changed;
1002 }
1003
1004 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1005   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1006           M.getModuleFlag("Debug Info Version")))
1007     return Val->getZExtValue();
1008   return 0;
1009 }
1010
1011 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1012 llvm::makeSubprogramMap(const Module &M) {
1013   DenseMap<const Function *, DISubprogram> R;
1014
1015   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1016   if (!CU_Nodes)
1017     return R;
1018
1019   for (MDNode *N : CU_Nodes->operands()) {
1020     DICompileUnit CUNode(N);
1021     DIArray SPs = CUNode.getSubprograms();
1022     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1023       DISubprogram SP(SPs.getElement(i));
1024       if (Function *F = SP.getFunction())
1025         R.insert(std::make_pair(F, SP));
1026     }
1027   }
1028   return R;
1029 }