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