Revert r218778 while investigating buldbot breakage.
[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/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33 using namespace llvm::dwarf;
34
35 //===----------------------------------------------------------------------===//
36 // DIDescriptor
37 //===----------------------------------------------------------------------===//
38
39 bool DIDescriptor::Verify() const {
40   return DbgNode &&
41          (DIDerivedType(DbgNode).Verify() ||
42           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
43           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
44           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
45           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
46           DILexicalBlock(DbgNode).Verify() ||
47           DILexicalBlockFile(DbgNode).Verify() ||
48           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
49           DIObjCProperty(DbgNode).Verify() ||
50           DITemplateTypeParameter(DbgNode).Verify() ||
51           DITemplateValueParameter(DbgNode).Verify() ||
52           DIImportedEntity(DbgNode).Verify());
53 }
54
55 static Value *getField(const MDNode *DbgNode, unsigned Elt) {
56   if (!DbgNode || Elt >= DbgNode->getNumOperands())
57     return nullptr;
58   return DbgNode->getOperand(Elt);
59 }
60
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
63 }
64
65 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
66   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
67     return MDS->getString();
68   return StringRef();
69 }
70
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72   return ::getStringField(DbgNode, Elt);
73 }
74
75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76   if (!DbgNode)
77     return 0;
78
79   if (Elt < DbgNode->getNumOperands())
80     if (ConstantInt *CI =
81             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
82       return CI->getZExtValue();
83
84   return 0;
85 }
86
87 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
88   if (!DbgNode)
89     return 0;
90
91   if (Elt < DbgNode->getNumOperands())
92     if (ConstantInt *CI =
93             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
94       return CI->getSExtValue();
95
96   return 0;
97 }
98
99 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
100   MDNode *Field = getNodeField(DbgNode, Elt);
101   return DIDescriptor(Field);
102 }
103
104 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
105   if (!DbgNode)
106     return nullptr;
107
108   if (Elt < DbgNode->getNumOperands())
109     return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
110   return nullptr;
111 }
112
113 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
114   if (!DbgNode)
115     return nullptr;
116
117   if (Elt < DbgNode->getNumOperands())
118     return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
119   return nullptr;
120 }
121
122 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
123   if (!DbgNode)
124     return nullptr;
125
126   if (Elt < DbgNode->getNumOperands())
127     return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
128   return nullptr;
129 }
130
131 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
132   if (!DbgNode)
133     return;
134
135   if (Elt < DbgNode->getNumOperands()) {
136     MDNode *Node = const_cast<MDNode *>(DbgNode);
137     Node->replaceOperandWith(Elt, F);
138   }
139 }
140
141 uint64_t DIVariable::getAddrElement(unsigned Idx) const {
142   DIDescriptor ComplexExpr = getDescriptorField(8);
143   if (Idx < ComplexExpr->getNumOperands())
144     if (auto *CI = dyn_cast_or_null<ConstantInt>(ComplexExpr->getOperand(Idx)))
145       return CI->getZExtValue();
146
147   assert(false && "non-existing complex address element requested");
148   return 0;
149 }
150
151 /// getInlinedAt - If this variable is inlined then return inline location.
152 MDNode *DIVariable::getInlinedAt() const { return getNodeField(DbgNode, 7); }
153
154 bool DIVariable::isVariablePiece() const {
155   return hasComplexAddress() && getAddrElement(0) == DIBuilder::OpPiece;
156 }
157
158 uint64_t DIVariable::getPieceOffset() const {
159   assert(isVariablePiece());
160   return getAddrElement(1);
161 }
162
163 uint64_t DIVariable::getPieceSize() const {
164   assert(isVariablePiece());
165   return getAddrElement(2);
166 }
167
168 /// Return the size reported by the variable's type.
169 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
170   DIType Ty = getType().resolve(Map);
171   // Follow derived types until we reach a type that
172   // reports back a size.
173   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
174     DIDerivedType DT(&*Ty);
175     Ty = DT.getTypeDerivedFrom().resolve(Map);
176   }
177   assert(Ty.getSizeInBits() && "type with size 0");
178   return Ty.getSizeInBits();
179 }
180
181
182
183
184 //===----------------------------------------------------------------------===//
185 // Predicates
186 //===----------------------------------------------------------------------===//
187
188 bool DIDescriptor::isSubroutineType() const {
189   return isCompositeType() && getTag() == dwarf::DW_TAG_subroutine_type;
190 }
191
192 /// isBasicType - Return true if the specified tag is legal for
193 /// DIBasicType.
194 bool DIDescriptor::isBasicType() const {
195   if (!DbgNode)
196     return false;
197   switch (getTag()) {
198   case dwarf::DW_TAG_base_type:
199   case dwarf::DW_TAG_unspecified_type:
200     return true;
201   default:
202     return false;
203   }
204 }
205
206 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
207 bool DIDescriptor::isDerivedType() const {
208   if (!DbgNode)
209     return false;
210   switch (getTag()) {
211   case dwarf::DW_TAG_typedef:
212   case dwarf::DW_TAG_pointer_type:
213   case dwarf::DW_TAG_ptr_to_member_type:
214   case dwarf::DW_TAG_reference_type:
215   case dwarf::DW_TAG_rvalue_reference_type:
216   case dwarf::DW_TAG_const_type:
217   case dwarf::DW_TAG_volatile_type:
218   case dwarf::DW_TAG_restrict_type:
219   case dwarf::DW_TAG_member:
220   case dwarf::DW_TAG_inheritance:
221   case dwarf::DW_TAG_friend:
222     return true;
223   default:
224     // CompositeTypes are currently modelled as DerivedTypes.
225     return isCompositeType();
226   }
227 }
228
229 /// isCompositeType - Return true if the specified tag is legal for
230 /// DICompositeType.
231 bool DIDescriptor::isCompositeType() const {
232   if (!DbgNode)
233     return false;
234   switch (getTag()) {
235   case dwarf::DW_TAG_array_type:
236   case dwarf::DW_TAG_structure_type:
237   case dwarf::DW_TAG_union_type:
238   case dwarf::DW_TAG_enumeration_type:
239   case dwarf::DW_TAG_subroutine_type:
240   case dwarf::DW_TAG_class_type:
241     return true;
242   default:
243     return false;
244   }
245 }
246
247 /// isVariable - Return true if the specified tag is legal for DIVariable.
248 bool DIDescriptor::isVariable() const {
249   if (!DbgNode)
250     return false;
251   switch (getTag()) {
252   case dwarf::DW_TAG_auto_variable:
253   case dwarf::DW_TAG_arg_variable:
254     return true;
255   default:
256     return false;
257   }
258 }
259
260 /// isType - Return true if the specified tag is legal for DIType.
261 bool DIDescriptor::isType() const {
262   return isBasicType() || isCompositeType() || isDerivedType();
263 }
264
265 /// isSubprogram - Return true if the specified tag is legal for
266 /// DISubprogram.
267 bool DIDescriptor::isSubprogram() const {
268   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
269 }
270
271 /// isGlobalVariable - Return true if the specified tag is legal for
272 /// DIGlobalVariable.
273 bool DIDescriptor::isGlobalVariable() const {
274   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
275                      getTag() == dwarf::DW_TAG_constant);
276 }
277
278 /// isScope - Return true if the specified tag is one of the scope
279 /// related tag.
280 bool DIDescriptor::isScope() const {
281   if (!DbgNode)
282     return false;
283   switch (getTag()) {
284   case dwarf::DW_TAG_compile_unit:
285   case dwarf::DW_TAG_lexical_block:
286   case dwarf::DW_TAG_subprogram:
287   case dwarf::DW_TAG_namespace:
288   case dwarf::DW_TAG_file_type:
289     return true;
290   default:
291     break;
292   }
293   return isType();
294 }
295
296 /// isTemplateTypeParameter - Return true if the specified tag is
297 /// DW_TAG_template_type_parameter.
298 bool DIDescriptor::isTemplateTypeParameter() const {
299   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
300 }
301
302 /// isTemplateValueParameter - Return true if the specified tag is
303 /// DW_TAG_template_value_parameter.
304 bool DIDescriptor::isTemplateValueParameter() const {
305   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
306                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
307                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
308 }
309
310 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
311 bool DIDescriptor::isCompileUnit() const {
312   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
313 }
314
315 /// isFile - Return true if the specified tag is DW_TAG_file_type.
316 bool DIDescriptor::isFile() const {
317   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
318 }
319
320 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
321 bool DIDescriptor::isNameSpace() const {
322   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
323 }
324
325 /// isLexicalBlockFile - Return true if the specified descriptor is a
326 /// lexical block with an extra file.
327 bool DIDescriptor::isLexicalBlockFile() const {
328   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
329          (DbgNode->getNumOperands() == 4);
330 }
331
332 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
333 bool DIDescriptor::isLexicalBlock() const {
334   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
335          (DbgNode->getNumOperands() > 3);
336 }
337
338 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
339 bool DIDescriptor::isSubrange() const {
340   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
341 }
342
343 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
344 bool DIDescriptor::isEnumerator() const {
345   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
346 }
347
348 /// isObjCProperty - Return true if the specified tag is DW_TAG_APPLE_property.
349 bool DIDescriptor::isObjCProperty() const {
350   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
351 }
352
353 /// \brief Return true if the specified tag is DW_TAG_imported_module or
354 /// DW_TAG_imported_declaration.
355 bool DIDescriptor::isImportedEntity() const {
356   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
357                      getTag() == dwarf::DW_TAG_imported_declaration);
358 }
359
360 //===----------------------------------------------------------------------===//
361 // Simple Descriptor Constructors and other Methods
362 //===----------------------------------------------------------------------===//
363
364 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
365 /// type with the one in the passed descriptor.
366 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
367
368   assert(DbgNode && "Trying to replace an unverified type!");
369
370   // Since we use a TrackingVH for the node, its easy for clients to manufacture
371   // legitimate situations where they want to replaceAllUsesWith() on something
372   // which, due to uniquing, has merged with the source. We shield clients from
373   // this detail by allowing a value to be replaced with replaceAllUsesWith()
374   // itself.
375   const MDNode *DN = D;
376   if (DbgNode == DN) {
377     SmallVector<Value*, 10> Ops(DbgNode->getNumOperands());
378     for (size_t i = 0; i != Ops.size(); ++i)
379       Ops[i] = DbgNode->getOperand(i);
380     DN = MDNode::get(VMContext, Ops);
381   }
382
383   MDNode *Node = const_cast<MDNode *>(DbgNode);
384   const Value *V = cast_or_null<Value>(DN);
385   Node->replaceAllUsesWith(const_cast<Value *>(V));
386   MDNode::deleteTemporary(Node);
387   DbgNode = DN;
388 }
389
390 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
391 /// type with the one in D.
392 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
393
394   assert(DbgNode && "Trying to replace an unverified type!");
395   assert(DbgNode != D && "This replacement should always happen");
396   MDNode *Node = const_cast<MDNode *>(DbgNode);
397   const MDNode *DN = D;
398   const Value *V = cast_or_null<Value>(DN);
399   Node->replaceAllUsesWith(const_cast<Value *>(V));
400   MDNode::deleteTemporary(Node);
401 }
402
403 /// Verify - Verify that a compile unit is well formed.
404 bool DICompileUnit::Verify() const {
405   if (!isCompileUnit())
406     return false;
407
408   // Don't bother verifying the compilation directory or producer string
409   // as those could be empty.
410   if (getFilename().empty())
411     return false;
412
413   return DbgNode->getNumOperands() == 14;
414 }
415
416 /// Verify - Verify that an ObjC property is well formed.
417 bool DIObjCProperty::Verify() const {
418   if (!isObjCProperty())
419     return false;
420
421   // Don't worry about the rest of the strings for now.
422   return DbgNode->getNumOperands() == 8;
423 }
424
425 /// Check if a field at position Elt of a MDNode is a MDNode.
426 /// We currently allow an empty string and an integer.
427 /// But we don't allow a non-empty string in a MDNode field.
428 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
429   // FIXME: This function should return true, if the field is null or the field
430   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
431   Value *Fld = getField(DbgNode, Elt);
432   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
433     return false;
434   return true;
435 }
436
437 /// Check if a field at position Elt of a MDNode is a MDString.
438 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
439   Value *Fld = getField(DbgNode, Elt);
440   return !Fld || isa<MDString>(Fld);
441 }
442
443 /// Check if a value can be a reference to a type.
444 static bool isTypeRef(const Value *Val) {
445   return !Val ||
446          (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
447          (isa<MDNode>(Val) && DIType(cast<MDNode>(Val)).isType());
448 }
449
450 /// Check if a field at position Elt of a MDNode can be a reference to a type.
451 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
452   Value *Fld = getField(DbgNode, Elt);
453   return isTypeRef(Fld);
454 }
455
456 /// Check if a value can be a ScopeRef.
457 static bool isScopeRef(const Value *Val) {
458   return !Val ||
459     (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
460     // Not checking for Val->isScope() here, because it would work
461     // only for lexical scopes and not all subclasses of DIScope.
462     isa<MDNode>(Val);
463 }
464
465 /// Check if a field at position Elt of a MDNode can be a ScopeRef.
466 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
467   Value *Fld = getField(DbgNode, Elt);
468   return isScopeRef(Fld);
469 }
470
471 /// Verify - Verify that a type descriptor is well formed.
472 bool DIType::Verify() const {
473   if (!isType())
474     return false;
475   // Make sure Context @ field 2 is MDNode.
476   if (!fieldIsScopeRef(DbgNode, 2))
477     return false;
478
479   // FIXME: Sink this into the various subclass verifies.
480   uint16_t Tag = getTag();
481   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
482       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
483       Tag != dwarf::DW_TAG_ptr_to_member_type &&
484       Tag != dwarf::DW_TAG_reference_type &&
485       Tag != dwarf::DW_TAG_rvalue_reference_type &&
486       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
487       Tag != dwarf::DW_TAG_enumeration_type &&
488       Tag != dwarf::DW_TAG_subroutine_type &&
489       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
490       getFilename().empty())
491     return false;
492
493   // DIType is abstract, it should be a BasicType, a DerivedType or
494   // a CompositeType.
495   if (isBasicType())
496     return DIBasicType(DbgNode).Verify();
497   else if (isCompositeType())
498     return DICompositeType(DbgNode).Verify();
499   else if (isDerivedType())
500     return DIDerivedType(DbgNode).Verify();
501   else
502     return false;
503 }
504
505 /// Verify - Verify that a basic type descriptor is well formed.
506 bool DIBasicType::Verify() const {
507   return isBasicType() && DbgNode->getNumOperands() == 10;
508 }
509
510 /// Verify - Verify that a derived type descriptor is well formed.
511 bool DIDerivedType::Verify() const {
512   // Make sure DerivedFrom @ field 9 is TypeRef.
513   if (!fieldIsTypeRef(DbgNode, 9))
514     return false;
515   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
516     // Make sure ClassType @ field 10 is a TypeRef.
517     if (!fieldIsTypeRef(DbgNode, 10))
518       return false;
519
520   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
521          DbgNode->getNumOperands() <= 14;
522 }
523
524 /// Verify - Verify that a composite type descriptor is well formed.
525 bool DICompositeType::Verify() const {
526   if (!isCompositeType())
527     return false;
528
529   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are TypeRef.
530   if (!fieldIsTypeRef(DbgNode, 9))
531     return false;
532   if (!fieldIsTypeRef(DbgNode, 12))
533     return false;
534
535   // Make sure the type identifier at field 14 is MDString, it can be null.
536   if (!fieldIsMDString(DbgNode, 14))
537     return false;
538
539   // A subroutine type can't be both & and &&.
540   if (isLValueReference() && isRValueReference())
541     return false;
542
543   return DbgNode->getNumOperands() == 15;
544 }
545
546 /// Verify - Verify that a subprogram descriptor is well formed.
547 bool DISubprogram::Verify() const {
548   if (!isSubprogram())
549     return false;
550
551   // Make sure context @ field 2 is a ScopeRef and type @ field 7 is a MDNode.
552   if (!fieldIsScopeRef(DbgNode, 2))
553     return false;
554   if (!fieldIsMDNode(DbgNode, 7))
555     return false;
556   // Containing type @ field 12.
557   if (!fieldIsTypeRef(DbgNode, 12))
558     return false;
559
560   // A subprogram can't be both & and &&.
561   if (isLValueReference() && isRValueReference())
562     return false;
563
564   return DbgNode->getNumOperands() == 20;
565 }
566
567 /// Verify - Verify that a global variable descriptor is well formed.
568 bool DIGlobalVariable::Verify() const {
569   if (!isGlobalVariable())
570     return false;
571
572   if (getDisplayName().empty())
573     return false;
574   // Make sure context @ field 2 is an MDNode.
575   if (!fieldIsMDNode(DbgNode, 2))
576     return false;
577   // Make sure that type @ field 8 is a DITypeRef.
578   if (!fieldIsTypeRef(DbgNode, 8))
579     return false;
580   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
581   if (!fieldIsMDNode(DbgNode, 12))
582     return false;
583
584   return DbgNode->getNumOperands() == 13;
585 }
586
587 /// Verify - Verify that a variable descriptor is well formed.
588 bool DIVariable::Verify() const {
589   if (!isVariable())
590     return false;
591
592   // Make sure context @ field 1 is an MDNode.
593   if (!fieldIsMDNode(DbgNode, 1))
594     return false;
595   // Make sure that type @ field 5 is a DITypeRef.
596   if (!fieldIsTypeRef(DbgNode, 5))
597     return false;
598
599   // Variable without a complex expression.
600   if (DbgNode->getNumOperands() == 8)
601     return true;
602
603   // Make sure the complex expression is an MDNode.
604   return (DbgNode->getNumOperands() == 9 && fieldIsMDNode(DbgNode, 8));
605 }
606
607 /// Verify - Verify that a location descriptor is well formed.
608 bool DILocation::Verify() const {
609   if (!DbgNode)
610     return false;
611
612   return DbgNode->getNumOperands() == 4;
613 }
614
615 /// Verify - Verify that a namespace descriptor is well formed.
616 bool DINameSpace::Verify() const {
617   if (!isNameSpace())
618     return false;
619   return DbgNode->getNumOperands() == 5;
620 }
621
622 /// \brief Retrieve the MDNode for the directory/file pair.
623 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
624
625 /// \brief Verify that the file descriptor is well formed.
626 bool DIFile::Verify() const {
627   return isFile() && DbgNode->getNumOperands() == 2;
628 }
629
630 /// \brief Verify that the enumerator descriptor is well formed.
631 bool DIEnumerator::Verify() const {
632   return isEnumerator() && DbgNode->getNumOperands() == 3;
633 }
634
635 /// \brief Verify that the subrange descriptor is well formed.
636 bool DISubrange::Verify() const {
637   return isSubrange() && DbgNode->getNumOperands() == 3;
638 }
639
640 /// \brief Verify that the lexical block descriptor is well formed.
641 bool DILexicalBlock::Verify() const {
642   return isLexicalBlock() && DbgNode->getNumOperands() == 6;
643 }
644
645 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
646 bool DILexicalBlockFile::Verify() const {
647   return isLexicalBlockFile() && DbgNode->getNumOperands() == 4;
648 }
649
650 /// \brief Verify that the template type parameter descriptor is well formed.
651 bool DITemplateTypeParameter::Verify() const {
652   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
653 }
654
655 /// \brief Verify that the template value parameter descriptor is well formed.
656 bool DITemplateValueParameter::Verify() const {
657   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
658 }
659
660 /// \brief Verify that the imported module descriptor is well formed.
661 bool DIImportedEntity::Verify() const {
662   return isImportedEntity() &&
663          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
664 }
665
666 /// getObjCProperty - Return property node, if this ivar is associated with one.
667 MDNode *DIDerivedType::getObjCProperty() const {
668   return getNodeField(DbgNode, 10);
669 }
670
671 MDString *DICompositeType::getIdentifier() const {
672   return cast_or_null<MDString>(getField(DbgNode, 14));
673 }
674
675 #ifndef NDEBUG
676 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
677   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
678     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
679     if (i == 0 && isa<ConstantInt>(LHS->getOperand(i)))
680       continue;
681     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
682     bool found = false;
683     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
684       found = E == RHS->getOperand(j);
685     assert(found && "Losing a member during member list replacement");
686   }
687 }
688 #endif
689
690 /// \brief Set the array of member DITypes.
691 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
692   TrackingVH<MDNode> N(*this);
693   if (Elements) {
694 #ifndef NDEBUG
695     // Check that the new list of members contains all the old members as well.
696     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(10)))
697       VerifySubsetOf(El, Elements);
698 #endif
699     N->replaceOperandWith(10, Elements);
700   }
701   if (TParams)
702     N->replaceOperandWith(13, TParams);
703   DbgNode = N;
704 }
705
706 /// Generate a reference to this DIType. Uses the type identifier instead
707 /// of the actual MDNode if possible, to help type uniquing.
708 DIScopeRef DIScope::getRef() const {
709   if (!isCompositeType())
710     return DIScopeRef(*this);
711   DICompositeType DTy(DbgNode);
712   if (!DTy.getIdentifier())
713     return DIScopeRef(*this);
714   return DIScopeRef(DTy.getIdentifier());
715 }
716
717 /// \brief Set the containing type.
718 void DICompositeType::setContainingType(DICompositeType ContainingType) {
719   TrackingVH<MDNode> N(*this);
720   N->replaceOperandWith(12, ContainingType.getRef());
721   DbgNode = N;
722 }
723
724 /// isInlinedFnArgument - Return true if this variable provides debugging
725 /// information for an inlined function arguments.
726 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
727   assert(CurFn && "Invalid function");
728   if (!getContext().isSubprogram())
729     return false;
730   // This variable is not inlined function argument if its scope
731   // does not describe current function.
732   return !DISubprogram(getContext()).describes(CurFn);
733 }
734
735 /// describes - Return true if this subprogram provides debugging
736 /// information for the function F.
737 bool DISubprogram::describes(const Function *F) {
738   assert(F && "Invalid function");
739   if (F == getFunction())
740     return true;
741   StringRef Name = getLinkageName();
742   if (Name.empty())
743     Name = getName();
744   if (F->getName() == Name)
745     return true;
746   return false;
747 }
748
749 unsigned DISubprogram::isOptimized() const {
750   assert(DbgNode && "Invalid subprogram descriptor!");
751   if (DbgNode->getNumOperands() == 15)
752     return getUnsignedField(14);
753   return 0;
754 }
755
756 MDNode *DISubprogram::getVariablesNodes() const {
757   return getNodeField(DbgNode, 18);
758 }
759
760 DIArray DISubprogram::getVariables() const {
761   return DIArray(getNodeField(DbgNode, 18));
762 }
763
764 Value *DITemplateValueParameter::getValue() const {
765   return getField(DbgNode, 4);
766 }
767
768 // If the current node has a parent scope then return that,
769 // else return an empty scope.
770 DIScopeRef DIScope::getContext() const {
771
772   if (isType())
773     return DIType(DbgNode).getContext();
774
775   if (isSubprogram())
776     return DIScopeRef(DISubprogram(DbgNode).getContext());
777
778   if (isLexicalBlock())
779     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
780
781   if (isLexicalBlockFile())
782     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
783
784   if (isNameSpace())
785     return DIScopeRef(DINameSpace(DbgNode).getContext());
786
787   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
788   return DIScopeRef(nullptr);
789 }
790
791 // If the scope node has a name, return that, else return an empty string.
792 StringRef DIScope::getName() const {
793   if (isType())
794     return DIType(DbgNode).getName();
795   if (isSubprogram())
796     return DISubprogram(DbgNode).getName();
797   if (isNameSpace())
798     return DINameSpace(DbgNode).getName();
799   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
800           isCompileUnit()) &&
801          "Unhandled type of scope.");
802   return StringRef();
803 }
804
805 StringRef DIScope::getFilename() const {
806   if (!DbgNode)
807     return StringRef();
808   return ::getStringField(getNodeField(DbgNode, 1), 0);
809 }
810
811 StringRef DIScope::getDirectory() const {
812   if (!DbgNode)
813     return StringRef();
814   return ::getStringField(getNodeField(DbgNode, 1), 1);
815 }
816
817 DIArray DICompileUnit::getEnumTypes() const {
818   if (!DbgNode || DbgNode->getNumOperands() < 13)
819     return DIArray();
820
821   return DIArray(getNodeField(DbgNode, 7));
822 }
823
824 DIArray DICompileUnit::getRetainedTypes() const {
825   if (!DbgNode || DbgNode->getNumOperands() < 13)
826     return DIArray();
827
828   return DIArray(getNodeField(DbgNode, 8));
829 }
830
831 DIArray DICompileUnit::getSubprograms() const {
832   if (!DbgNode || DbgNode->getNumOperands() < 13)
833     return DIArray();
834
835   return DIArray(getNodeField(DbgNode, 9));
836 }
837
838 DIArray DICompileUnit::getGlobalVariables() const {
839   if (!DbgNode || DbgNode->getNumOperands() < 13)
840     return DIArray();
841
842   return DIArray(getNodeField(DbgNode, 10));
843 }
844
845 DIArray DICompileUnit::getImportedEntities() const {
846   if (!DbgNode || DbgNode->getNumOperands() < 13)
847     return DIArray();
848
849   return DIArray(getNodeField(DbgNode, 11));
850 }
851
852 /// copyWithNewScope - Return a copy of this location, replacing the
853 /// current scope with the given one.
854 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
855                                         DILexicalBlockFile NewScope) {
856   SmallVector<Value *, 10> Elts;
857   assert(Verify());
858   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
859     if (I != 2)
860       Elts.push_back(DbgNode->getOperand(I));
861     else
862       Elts.push_back(NewScope);
863   }
864   MDNode *NewDIL = MDNode::get(Ctx, Elts);
865   return DILocation(NewDIL);
866 }
867
868 /// computeNewDiscriminator - Generate a new discriminator value for this
869 /// file and line location.
870 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
871   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
872   return ++Ctx.pImpl->DiscriminatorTable[Key];
873 }
874
875 /// fixupSubprogramName - Replace contains special characters used
876 /// in a typical Objective-C names with '.' in a given string.
877 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
878   StringRef FName =
879       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
880   FName = Function::getRealLinkageName(FName);
881
882   StringRef Prefix("llvm.dbg.lv.");
883   Out.reserve(FName.size() + Prefix.size());
884   Out.append(Prefix.begin(), Prefix.end());
885
886   bool isObjCLike = false;
887   for (size_t i = 0, e = FName.size(); i < e; ++i) {
888     char C = FName[i];
889     if (C == '[')
890       isObjCLike = true;
891
892     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
893                        C == '+' || C == '(' || C == ')'))
894       Out.push_back('.');
895     else
896       Out.push_back(C);
897   }
898 }
899
900 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
901 /// suitable to hold function specific information.
902 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
903   SmallString<32> Name;
904   fixupSubprogramName(Fn, Name);
905   return M.getNamedMetadata(Name.str());
906 }
907
908 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
909 /// to hold function specific information.
910 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
911   SmallString<32> Name;
912   fixupSubprogramName(Fn, Name);
913   return M.getOrInsertNamedMetadata(Name.str());
914 }
915
916 /// createInlinedVariable - Create a new inlined variable based on current
917 /// variable.
918 /// @param DV            Current Variable.
919 /// @param InlinedScope  Location at current variable is inlined.
920 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
921                                        LLVMContext &VMContext) {
922   SmallVector<Value *, 16> Elts;
923   // Insert inlined scope as 7th element.
924   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
925     i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i));
926   return DIVariable(MDNode::get(VMContext, Elts));
927 }
928
929 /// cleanseInlinedVariable - Remove inlined scope from the variable.
930 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
931   SmallVector<Value *, 16> Elts;
932   // Insert inlined scope as 7th element.
933   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
934     i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)))
935            : Elts.push_back(DV->getOperand(i));
936   return DIVariable(MDNode::get(VMContext, Elts));
937 }
938
939
940 /// getEntireVariable - Remove OpPiece exprs from the variable.
941 DIVariable llvm::getEntireVariable(DIVariable DV) {
942   if (!DV.isVariablePiece())
943     return DV;
944
945   SmallVector<Value *, 8> Elts;
946   for (unsigned i = 0; i < 8; ++i)
947     Elts.push_back(DV->getOperand(i));
948
949   return DIVariable(MDNode::get(DV->getContext(), Elts));
950 }
951
952 /// getDISubprogram - Find subprogram that is enclosing this scope.
953 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
954   DIDescriptor D(Scope);
955   if (D.isSubprogram())
956     return DISubprogram(Scope);
957
958   if (D.isLexicalBlockFile())
959     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
960
961   if (D.isLexicalBlock())
962     return getDISubprogram(DILexicalBlock(Scope).getContext());
963
964   return DISubprogram();
965 }
966
967 /// getDICompositeType - Find underlying composite type.
968 DICompositeType llvm::getDICompositeType(DIType T) {
969   if (T.isCompositeType())
970     return DICompositeType(T);
971
972   if (T.isDerivedType()) {
973     // This function is currently used by dragonegg and dragonegg does
974     // not generate identifier for types, so using an empty map to resolve
975     // DerivedFrom should be fine.
976     DITypeIdentifierMap EmptyMap;
977     return getDICompositeType(
978         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
979   }
980
981   return DICompositeType();
982 }
983
984 /// Update DITypeIdentifierMap by going through retained types of each CU.
985 DITypeIdentifierMap
986 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
987   DITypeIdentifierMap Map;
988   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
989     DICompileUnit CU(CU_Nodes->getOperand(CUi));
990     DIArray Retain = CU.getRetainedTypes();
991     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
992       if (!Retain.getElement(Ti).isCompositeType())
993         continue;
994       DICompositeType Ty(Retain.getElement(Ti));
995       if (MDString *TypeId = Ty.getIdentifier()) {
996         // Definition has priority over declaration.
997         // Try to insert (TypeId, Ty) to Map.
998         std::pair<DITypeIdentifierMap::iterator, bool> P =
999             Map.insert(std::make_pair(TypeId, Ty));
1000         // If TypeId already exists in Map and this is a definition, replace
1001         // whatever we had (declaration or definition) with the definition.
1002         if (!P.second && !Ty.isForwardDecl())
1003           P.first->second = Ty;
1004       }
1005     }
1006   }
1007   return Map;
1008 }
1009
1010 //===----------------------------------------------------------------------===//
1011 // DebugInfoFinder implementations.
1012 //===----------------------------------------------------------------------===//
1013
1014 void DebugInfoFinder::reset() {
1015   CUs.clear();
1016   SPs.clear();
1017   GVs.clear();
1018   TYs.clear();
1019   Scopes.clear();
1020   NodesSeen.clear();
1021   TypeIdentifierMap.clear();
1022   TypeMapInitialized = false;
1023 }
1024
1025 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
1026   if (!TypeMapInitialized)
1027     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1028       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
1029       TypeMapInitialized = true;
1030     }
1031 }
1032
1033 /// processModule - Process entire module and collect debug info.
1034 void DebugInfoFinder::processModule(const Module &M) {
1035   InitializeTypeMap(M);
1036   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1037     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1038       DICompileUnit CU(CU_Nodes->getOperand(i));
1039       addCompileUnit(CU);
1040       DIArray GVs = CU.getGlobalVariables();
1041       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1042         DIGlobalVariable DIG(GVs.getElement(i));
1043         if (addGlobalVariable(DIG)) {
1044           processScope(DIG.getContext());
1045           processType(DIG.getType().resolve(TypeIdentifierMap));
1046         }
1047       }
1048       DIArray SPs = CU.getSubprograms();
1049       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1050         processSubprogram(DISubprogram(SPs.getElement(i)));
1051       DIArray EnumTypes = CU.getEnumTypes();
1052       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1053         processType(DIType(EnumTypes.getElement(i)));
1054       DIArray RetainedTypes = CU.getRetainedTypes();
1055       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1056         processType(DIType(RetainedTypes.getElement(i)));
1057       DIArray Imports = CU.getImportedEntities();
1058       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1059         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1060         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1061         if (Entity.isType())
1062           processType(DIType(Entity));
1063         else if (Entity.isSubprogram())
1064           processSubprogram(DISubprogram(Entity));
1065         else if (Entity.isNameSpace())
1066           processScope(DINameSpace(Entity).getContext());
1067       }
1068     }
1069   }
1070 }
1071
1072 /// processLocation - Process DILocation.
1073 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1074   if (!Loc)
1075     return;
1076   InitializeTypeMap(M);
1077   processScope(Loc.getScope());
1078   processLocation(M, Loc.getOrigLocation());
1079 }
1080
1081 /// processType - Process DIType.
1082 void DebugInfoFinder::processType(DIType DT) {
1083   if (!addType(DT))
1084     return;
1085   processScope(DT.getContext().resolve(TypeIdentifierMap));
1086   if (DT.isCompositeType()) {
1087     DICompositeType DCT(DT);
1088     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1089     if (DT.isSubroutineType()) {
1090       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1091       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1092         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1093       return;
1094     }
1095     DIArray DA = DCT.getElements();
1096     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1097       DIDescriptor D = DA.getElement(i);
1098       if (D.isType())
1099         processType(DIType(D));
1100       else if (D.isSubprogram())
1101         processSubprogram(DISubprogram(D));
1102     }
1103   } else if (DT.isDerivedType()) {
1104     DIDerivedType DDT(DT);
1105     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1106   }
1107 }
1108
1109 void DebugInfoFinder::processScope(DIScope Scope) {
1110   if (Scope.isType()) {
1111     DIType Ty(Scope);
1112     processType(Ty);
1113     return;
1114   }
1115   if (Scope.isCompileUnit()) {
1116     addCompileUnit(DICompileUnit(Scope));
1117     return;
1118   }
1119   if (Scope.isSubprogram()) {
1120     processSubprogram(DISubprogram(Scope));
1121     return;
1122   }
1123   if (!addScope(Scope))
1124     return;
1125   if (Scope.isLexicalBlock()) {
1126     DILexicalBlock LB(Scope);
1127     processScope(LB.getContext());
1128   } else if (Scope.isLexicalBlockFile()) {
1129     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1130     processScope(LBF.getScope());
1131   } else if (Scope.isNameSpace()) {
1132     DINameSpace NS(Scope);
1133     processScope(NS.getContext());
1134   }
1135 }
1136
1137 /// processSubprogram - Process DISubprogram.
1138 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1139   if (!addSubprogram(SP))
1140     return;
1141   processScope(SP.getContext().resolve(TypeIdentifierMap));
1142   processType(SP.getType());
1143   DIArray TParams = SP.getTemplateParams();
1144   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1145     DIDescriptor Element = TParams.getElement(I);
1146     if (Element.isTemplateTypeParameter()) {
1147       DITemplateTypeParameter TType(Element);
1148       processScope(TType.getContext().resolve(TypeIdentifierMap));
1149       processType(TType.getType().resolve(TypeIdentifierMap));
1150     } else if (Element.isTemplateValueParameter()) {
1151       DITemplateValueParameter TVal(Element);
1152       processScope(TVal.getContext().resolve(TypeIdentifierMap));
1153       processType(TVal.getType().resolve(TypeIdentifierMap));
1154     }
1155   }
1156 }
1157
1158 /// processDeclare - Process DbgDeclareInst.
1159 void DebugInfoFinder::processDeclare(const Module &M,
1160                                      const DbgDeclareInst *DDI) {
1161   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1162   if (!N)
1163     return;
1164   InitializeTypeMap(M);
1165
1166   DIDescriptor DV(N);
1167   if (!DV.isVariable())
1168     return;
1169
1170   if (!NodesSeen.insert(DV))
1171     return;
1172   processScope(DIVariable(N).getContext());
1173   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1174 }
1175
1176 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1177   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1178   if (!N)
1179     return;
1180   InitializeTypeMap(M);
1181
1182   DIDescriptor DV(N);
1183   if (!DV.isVariable())
1184     return;
1185
1186   if (!NodesSeen.insert(DV))
1187     return;
1188   processScope(DIVariable(N).getContext());
1189   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1190 }
1191
1192 /// addType - Add type into Tys.
1193 bool DebugInfoFinder::addType(DIType DT) {
1194   if (!DT)
1195     return false;
1196
1197   if (!NodesSeen.insert(DT))
1198     return false;
1199
1200   TYs.push_back(DT);
1201   return true;
1202 }
1203
1204 /// addCompileUnit - Add compile unit into CUs.
1205 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1206   if (!CU)
1207     return false;
1208   if (!NodesSeen.insert(CU))
1209     return false;
1210
1211   CUs.push_back(CU);
1212   return true;
1213 }
1214
1215 /// addGlobalVariable - Add global variable into GVs.
1216 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1217   if (!DIG)
1218     return false;
1219
1220   if (!NodesSeen.insert(DIG))
1221     return false;
1222
1223   GVs.push_back(DIG);
1224   return true;
1225 }
1226
1227 // addSubprogram - Add subprgoram into SPs.
1228 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1229   if (!SP)
1230     return false;
1231
1232   if (!NodesSeen.insert(SP))
1233     return false;
1234
1235   SPs.push_back(SP);
1236   return true;
1237 }
1238
1239 bool DebugInfoFinder::addScope(DIScope Scope) {
1240   if (!Scope)
1241     return false;
1242   // FIXME: Ocaml binding generates a scope with no content, we treat it
1243   // as null for now.
1244   if (Scope->getNumOperands() == 0)
1245     return false;
1246   if (!NodesSeen.insert(Scope))
1247     return false;
1248   Scopes.push_back(Scope);
1249   return true;
1250 }
1251
1252 //===----------------------------------------------------------------------===//
1253 // DIDescriptor: dump routines for all descriptors.
1254 //===----------------------------------------------------------------------===//
1255
1256 /// dump - Print descriptor to dbgs() with a newline.
1257 void DIDescriptor::dump() const {
1258   print(dbgs());
1259   dbgs() << '\n';
1260 }
1261
1262 /// print - Print descriptor.
1263 void DIDescriptor::print(raw_ostream &OS) const {
1264   if (!DbgNode)
1265     return;
1266
1267   if (const char *Tag = dwarf::TagString(getTag()))
1268     OS << "[ " << Tag << " ]";
1269
1270   if (this->isSubrange()) {
1271     DISubrange(DbgNode).printInternal(OS);
1272   } else if (this->isCompileUnit()) {
1273     DICompileUnit(DbgNode).printInternal(OS);
1274   } else if (this->isFile()) {
1275     DIFile(DbgNode).printInternal(OS);
1276   } else if (this->isEnumerator()) {
1277     DIEnumerator(DbgNode).printInternal(OS);
1278   } else if (this->isBasicType()) {
1279     DIType(DbgNode).printInternal(OS);
1280   } else if (this->isDerivedType()) {
1281     DIDerivedType(DbgNode).printInternal(OS);
1282   } else if (this->isCompositeType()) {
1283     DICompositeType(DbgNode).printInternal(OS);
1284   } else if (this->isSubprogram()) {
1285     DISubprogram(DbgNode).printInternal(OS);
1286   } else if (this->isGlobalVariable()) {
1287     DIGlobalVariable(DbgNode).printInternal(OS);
1288   } else if (this->isVariable()) {
1289     DIVariable(DbgNode).printInternal(OS);
1290   } else if (this->isObjCProperty()) {
1291     DIObjCProperty(DbgNode).printInternal(OS);
1292   } else if (this->isNameSpace()) {
1293     DINameSpace(DbgNode).printInternal(OS);
1294   } else if (this->isScope()) {
1295     DIScope(DbgNode).printInternal(OS);
1296   }
1297 }
1298
1299 void DISubrange::printInternal(raw_ostream &OS) const {
1300   int64_t Count = getCount();
1301   if (Count != -1)
1302     OS << " [" << getLo() << ", " << Count - 1 << ']';
1303   else
1304     OS << " [unbounded]";
1305 }
1306
1307 void DIScope::printInternal(raw_ostream &OS) const {
1308   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1309 }
1310
1311 void DICompileUnit::printInternal(raw_ostream &OS) const {
1312   DIScope::printInternal(OS);
1313   OS << " [";
1314   unsigned Lang = getLanguage();
1315   if (const char *LangStr = dwarf::LanguageString(Lang))
1316     OS << LangStr;
1317   else
1318     (OS << "lang 0x").write_hex(Lang);
1319   OS << ']';
1320 }
1321
1322 void DIEnumerator::printInternal(raw_ostream &OS) const {
1323   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1324 }
1325
1326 void DIType::printInternal(raw_ostream &OS) const {
1327   if (!DbgNode)
1328     return;
1329
1330   StringRef Res = getName();
1331   if (!Res.empty())
1332     OS << " [" << Res << "]";
1333
1334   // TODO: Print context?
1335
1336   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1337      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1338   if (isBasicType())
1339     if (const char *Enc =
1340             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1341       OS << ", enc " << Enc;
1342   OS << "]";
1343
1344   if (isPrivate())
1345     OS << " [private]";
1346   else if (isProtected())
1347     OS << " [protected]";
1348   else if (isPublic())
1349     OS << " [public]";
1350
1351   if (isArtificial())
1352     OS << " [artificial]";
1353
1354   if (isForwardDecl())
1355     OS << " [decl]";
1356   else if (getTag() == dwarf::DW_TAG_structure_type ||
1357            getTag() == dwarf::DW_TAG_union_type ||
1358            getTag() == dwarf::DW_TAG_enumeration_type ||
1359            getTag() == dwarf::DW_TAG_class_type)
1360     OS << " [def]";
1361   if (isVector())
1362     OS << " [vector]";
1363   if (isStaticMember())
1364     OS << " [static]";
1365
1366   if (isLValueReference())
1367     OS << " [reference]";
1368
1369   if (isRValueReference())
1370     OS << " [rvalue reference]";
1371 }
1372
1373 void DIDerivedType::printInternal(raw_ostream &OS) const {
1374   DIType::printInternal(OS);
1375   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1376 }
1377
1378 void DICompositeType::printInternal(raw_ostream &OS) const {
1379   DIType::printInternal(OS);
1380   DIArray A = getElements();
1381   OS << " [" << A.getNumElements() << " elements]";
1382 }
1383
1384 void DINameSpace::printInternal(raw_ostream &OS) const {
1385   StringRef Name = getName();
1386   if (!Name.empty())
1387     OS << " [" << Name << ']';
1388
1389   OS << " [line " << getLineNumber() << ']';
1390 }
1391
1392 void DISubprogram::printInternal(raw_ostream &OS) const {
1393   // TODO : Print context
1394   OS << " [line " << getLineNumber() << ']';
1395
1396   if (isLocalToUnit())
1397     OS << " [local]";
1398
1399   if (isDefinition())
1400     OS << " [def]";
1401
1402   if (getScopeLineNumber() != getLineNumber())
1403     OS << " [scope " << getScopeLineNumber() << "]";
1404
1405   if (isPrivate())
1406     OS << " [private]";
1407   else if (isProtected())
1408     OS << " [protected]";
1409   else if (isPublic())
1410     OS << " [public]";
1411
1412   if (isLValueReference())
1413     OS << " [reference]";
1414
1415   if (isRValueReference())
1416     OS << " [rvalue reference]";
1417
1418   StringRef Res = getName();
1419   if (!Res.empty())
1420     OS << " [" << Res << ']';
1421 }
1422
1423 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1424   StringRef Res = getName();
1425   if (!Res.empty())
1426     OS << " [" << Res << ']';
1427
1428   OS << " [line " << getLineNumber() << ']';
1429
1430   // TODO : Print context
1431
1432   if (isLocalToUnit())
1433     OS << " [local]";
1434
1435   if (isDefinition())
1436     OS << " [def]";
1437 }
1438
1439 void DIVariable::printInternal(raw_ostream &OS) const {
1440   StringRef Res = getName();
1441   if (!Res.empty())
1442     OS << " [" << Res << ']';
1443
1444   OS << " [line " << getLineNumber() << ']';
1445
1446   if (isVariablePiece())
1447     OS << " [piece, size " << getPieceSize()
1448        << ", offset " << getPieceOffset() << ']';
1449 }
1450
1451 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1452   StringRef Name = getObjCPropertyName();
1453   if (!Name.empty())
1454     OS << " [" << Name << ']';
1455
1456   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1457      << ']';
1458 }
1459
1460 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1461                           const LLVMContext &Ctx) {
1462   if (!DL.isUnknown()) { // Print source line info.
1463     DIScope Scope(DL.getScope(Ctx));
1464     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1465     // Omit the directory, because it's likely to be long and uninteresting.
1466     CommentOS << Scope.getFilename();
1467     CommentOS << ':' << DL.getLine();
1468     if (DL.getCol() != 0)
1469       CommentOS << ':' << DL.getCol();
1470     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1471     if (!InlinedAtDL.isUnknown()) {
1472       CommentOS << " @[ ";
1473       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1474       CommentOS << " ]";
1475     }
1476   }
1477 }
1478
1479 void DIVariable::printExtendedName(raw_ostream &OS) const {
1480   const LLVMContext &Ctx = DbgNode->getContext();
1481   StringRef Res = getName();
1482   if (!Res.empty())
1483     OS << Res << "," << getLineNumber();
1484   if (MDNode *InlinedAt = getInlinedAt()) {
1485     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1486     if (!InlinedAtDL.isUnknown()) {
1487       OS << " @[";
1488       printDebugLoc(InlinedAtDL, OS, Ctx);
1489       OS << "]";
1490     }
1491   }
1492 }
1493
1494 /// Specialize constructor to make sure it has the correct type.
1495 template <> DIRef<DIScope>::DIRef(const Value *V) : Val(V) {
1496   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1497 }
1498 template <> DIRef<DIType>::DIRef(const Value *V) : Val(V) {
1499   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1500 }
1501
1502 /// Specialize getFieldAs to handle fields that are references to DIScopes.
1503 template <>
1504 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1505   return DIScopeRef(getField(DbgNode, Elt));
1506 }
1507 /// Specialize getFieldAs to handle fields that are references to DITypes.
1508 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1509   return DITypeRef(getField(DbgNode, Elt));
1510 }
1511
1512 /// Strip debug info in the module if it exists.
1513 /// To do this, we remove all calls to the debugger intrinsics and any named
1514 /// metadata for debugging. We also remove debug locations for instructions.
1515 /// Return true if module is modified.
1516 bool llvm::StripDebugInfo(Module &M) {
1517
1518   bool Changed = false;
1519
1520   // Remove all of the calls to the debugger intrinsics, and remove them from
1521   // the module.
1522   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1523     while (!Declare->use_empty()) {
1524       CallInst *CI = cast<CallInst>(Declare->user_back());
1525       CI->eraseFromParent();
1526     }
1527     Declare->eraseFromParent();
1528     Changed = true;
1529   }
1530
1531   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1532     while (!DbgVal->use_empty()) {
1533       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1534       CI->eraseFromParent();
1535     }
1536     DbgVal->eraseFromParent();
1537     Changed = true;
1538   }
1539
1540   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1541          NME = M.named_metadata_end(); NMI != NME;) {
1542     NamedMDNode *NMD = NMI;
1543     ++NMI;
1544     if (NMD->getName().startswith("llvm.dbg.")) {
1545       NMD->eraseFromParent();
1546       Changed = true;
1547     }
1548   }
1549
1550   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1551     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1552          ++FI)
1553       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1554            ++BI) {
1555         if (!BI->getDebugLoc().isUnknown()) {
1556           Changed = true;
1557           BI->setDebugLoc(DebugLoc());
1558         }
1559       }
1560
1561   return Changed;
1562 }
1563
1564 /// Return Debug Info Metadata Version by checking module flags.
1565 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1566   Value *Val = M.getModuleFlag("Debug Info Version");
1567   if (!Val)
1568     return 0;
1569   return cast<ConstantInt>(Val)->getZExtValue();
1570 }
1571
1572 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1573 llvm::makeSubprogramMap(const Module &M) {
1574   DenseMap<const Function *, DISubprogram> R;
1575
1576   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1577   if (!CU_Nodes)
1578     return R;
1579
1580   for (MDNode *N : CU_Nodes->operands()) {
1581     DICompileUnit CUNode(N);
1582     DIArray SPs = CUNode.getSubprograms();
1583     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1584       DISubprogram SP(SPs.getElement(i));
1585       if (Function *F = SP.getFunction())
1586         R.insert(std::make_pair(F, SP));
1587     }
1588   }
1589   return R;
1590 }