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