]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/DebugInfo.cpp
Update dialog to version 1.1-20110302.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Analysis / 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/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
37 }
38
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
40 }
41
42 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
43 }
44
45 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
46 }
47
48 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
49 }
50
51 StringRef
52 DIDescriptor::getStringField(unsigned Elt) const {
53   if (DbgNode == 0)
54     return StringRef();
55
56   if (Elt < DbgNode->getNumOperands())
57     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
58       return MDS->getString();
59
60   return StringRef();
61 }
62
63 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
64   if (DbgNode == 0)
65     return 0;
66
67   if (Elt < DbgNode->getNumOperands())
68     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
69       return CI->getZExtValue();
70
71   return 0;
72 }
73
74 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
75   if (DbgNode == 0)
76     return DIDescriptor();
77
78   if (Elt < DbgNode->getNumOperands())
79     return
80       DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
81   return DIDescriptor();
82 }
83
84 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
85   if (DbgNode == 0)
86     return 0;
87
88   if (Elt < DbgNode->getNumOperands())
89       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
90   return 0;
91 }
92
93 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
94   if (DbgNode == 0)
95     return 0;
96
97   if (Elt < DbgNode->getNumOperands())
98       return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
99   return 0;
100 }
101
102 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
103   if (DbgNode == 0)
104     return 0;
105
106   if (Elt < DbgNode->getNumOperands())
107       return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
108   return 0;
109 }
110
111 unsigned DIVariable::getNumAddrElements() const {
112   if (getVersion() <= llvm::LLVMDebugVersion8)
113     return DbgNode->getNumOperands()-6;
114   return DbgNode->getNumOperands()-7;
115 }
116
117
118 //===----------------------------------------------------------------------===//
119 // Predicates
120 //===----------------------------------------------------------------------===//
121
122 /// isBasicType - Return true if the specified tag is legal for
123 /// DIBasicType.
124 bool DIDescriptor::isBasicType() const {
125   return DbgNode && getTag() == dwarf::DW_TAG_base_type;
126 }
127
128 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
129 bool DIDescriptor::isDerivedType() const {
130   if (!DbgNode) return false;
131   switch (getTag()) {
132   case dwarf::DW_TAG_typedef:
133   case dwarf::DW_TAG_pointer_type:
134   case dwarf::DW_TAG_reference_type:
135   case dwarf::DW_TAG_const_type:
136   case dwarf::DW_TAG_volatile_type:
137   case dwarf::DW_TAG_restrict_type:
138   case dwarf::DW_TAG_member:
139   case dwarf::DW_TAG_inheritance:
140   case dwarf::DW_TAG_friend:
141     return true;
142   default:
143     // CompositeTypes are currently modelled as DerivedTypes.
144     return isCompositeType();
145   }
146 }
147
148 /// isCompositeType - Return true if the specified tag is legal for
149 /// DICompositeType.
150 bool DIDescriptor::isCompositeType() const {
151   if (!DbgNode) return false;
152   switch (getTag()) {
153   case dwarf::DW_TAG_array_type:
154   case dwarf::DW_TAG_structure_type:
155   case dwarf::DW_TAG_union_type:
156   case dwarf::DW_TAG_enumeration_type:
157   case dwarf::DW_TAG_vector_type:
158   case dwarf::DW_TAG_subroutine_type:
159   case dwarf::DW_TAG_class_type:
160     return true;
161   default:
162     return false;
163   }
164 }
165
166 /// isVariable - Return true if the specified tag is legal for DIVariable.
167 bool DIDescriptor::isVariable() const {
168   if (!DbgNode) return false;
169   switch (getTag()) {
170   case dwarf::DW_TAG_auto_variable:
171   case dwarf::DW_TAG_arg_variable:
172   case dwarf::DW_TAG_return_variable:
173     return true;
174   default:
175     return false;
176   }
177 }
178
179 /// isType - Return true if the specified tag is legal for DIType.
180 bool DIDescriptor::isType() const {
181   return isBasicType() || isCompositeType() || isDerivedType();
182 }
183
184 /// isSubprogram - Return true if the specified tag is legal for
185 /// DISubprogram.
186 bool DIDescriptor::isSubprogram() const {
187   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
188 }
189
190 /// isGlobalVariable - Return true if the specified tag is legal for
191 /// DIGlobalVariable.
192 bool DIDescriptor::isGlobalVariable() const {
193   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
194                      getTag() == dwarf::DW_TAG_constant);
195 }
196
197 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
198 bool DIDescriptor::isGlobal() const {
199   return isGlobalVariable();
200 }
201
202 /// isUnspecifiedParmeter - Return true if the specified tag is
203 /// DW_TAG_unspecified_parameters.
204 bool DIDescriptor::isUnspecifiedParameter() const {
205   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
206 }
207
208 /// isScope - Return true if the specified tag is one of the scope
209 /// related tag.
210 bool DIDescriptor::isScope() const {
211   if (!DbgNode) return false;
212   switch (getTag()) {
213   case dwarf::DW_TAG_compile_unit:
214   case dwarf::DW_TAG_lexical_block:
215   case dwarf::DW_TAG_subprogram:
216   case dwarf::DW_TAG_namespace:
217     return true;
218   default:
219     break;
220   }
221   return false;
222 }
223
224 /// isTemplateTypeParameter - Return true if the specified tag is
225 /// DW_TAG_template_type_parameter.
226 bool DIDescriptor::isTemplateTypeParameter() const {
227   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
228 }
229
230 /// isTemplateValueParameter - Return true if the specified tag is
231 /// DW_TAG_template_value_parameter.
232 bool DIDescriptor::isTemplateValueParameter() const {
233   return DbgNode && getTag() == dwarf::DW_TAG_template_value_parameter;
234 }
235
236 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
237 bool DIDescriptor::isCompileUnit() const {
238   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
239 }
240
241 /// isFile - Return true if the specified tag is DW_TAG_file_type.
242 bool DIDescriptor::isFile() const {
243   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
244 }
245
246 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
247 bool DIDescriptor::isNameSpace() const {
248   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
249 }
250
251 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
252 bool DIDescriptor::isLexicalBlock() const {
253   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
254 }
255
256 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
257 bool DIDescriptor::isSubrange() const {
258   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
259 }
260
261 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
262 bool DIDescriptor::isEnumerator() const {
263   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
264 }
265
266 //===----------------------------------------------------------------------===//
267 // Simple Descriptor Constructors and other Methods
268 //===----------------------------------------------------------------------===//
269
270 DIType::DIType(const MDNode *N) : DIScope(N) {
271   if (!N) return;
272   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
273     DbgNode = 0;
274   }
275 }
276
277 unsigned DIArray::getNumElements() const {
278   if (!DbgNode)
279     return 0;
280   return DbgNode->getNumOperands();
281 }
282
283 /// replaceAllUsesWith - Replace all uses of debug info referenced by
284 /// this descriptor.
285 void DIType::replaceAllUsesWith(DIDescriptor &D) {
286   if (!DbgNode)
287     return;
288
289   // Since we use a TrackingVH for the node, its easy for clients to manufacture
290   // legitimate situations where they want to replaceAllUsesWith() on something
291   // which, due to uniquing, has merged with the source. We shield clients from
292   // this detail by allowing a value to be replaced with replaceAllUsesWith()
293   // itself.
294   if (DbgNode != D) {
295     MDNode *Node = const_cast<MDNode*>(DbgNode);
296     const MDNode *DN = D;
297     const Value *V = cast_or_null<Value>(DN);
298     Node->replaceAllUsesWith(const_cast<Value*>(V));
299     MDNode::deleteTemporary(Node);
300   }
301 }
302
303 /// replaceAllUsesWith - Replace all uses of debug info referenced by
304 /// this descriptor.
305 void DIType::replaceAllUsesWith(MDNode *D) {
306   if (!DbgNode)
307     return;
308
309   // Since we use a TrackingVH for the node, its easy for clients to manufacture
310   // legitimate situations where they want to replaceAllUsesWith() on something
311   // which, due to uniquing, has merged with the source. We shield clients from
312   // this detail by allowing a value to be replaced with replaceAllUsesWith()
313   // itself.
314   if (DbgNode != D) {
315     MDNode *Node = const_cast<MDNode*>(DbgNode);
316     const MDNode *DN = D;
317     const Value *V = cast_or_null<Value>(DN);
318     Node->replaceAllUsesWith(const_cast<Value*>(V));
319     MDNode::deleteTemporary(Node);
320   }
321 }
322
323 /// Verify - Verify that a compile unit is well formed.
324 bool DICompileUnit::Verify() const {
325   if (!DbgNode)
326     return false;
327   StringRef N = getFilename();
328   if (N.empty())
329     return false;
330   // It is possible that directory and produce string is empty.
331   return true;
332 }
333
334 /// Verify - Verify that a type descriptor is well formed.
335 bool DIType::Verify() const {
336   if (!DbgNode)
337     return false;
338   if (!getContext().Verify())
339     return false;
340   unsigned Tag = getTag();
341   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
342       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
343       Tag != dwarf::DW_TAG_reference_type && Tag != dwarf::DW_TAG_restrict_type 
344       && Tag != dwarf::DW_TAG_vector_type && Tag != dwarf::DW_TAG_array_type
345       && Tag != dwarf::DW_TAG_enumeration_type 
346       && getFilename().empty())
347     return false;
348   return true;
349 }
350
351 /// Verify - Verify that a basic type descriptor is well formed.
352 bool DIBasicType::Verify() const {
353   return isBasicType();
354 }
355
356 /// Verify - Verify that a derived type descriptor is well formed.
357 bool DIDerivedType::Verify() const {
358   return isDerivedType();
359 }
360
361 /// Verify - Verify that a composite type descriptor is well formed.
362 bool DICompositeType::Verify() const {
363   if (!DbgNode)
364     return false;
365   if (!getContext().Verify())
366     return false;
367
368   DICompileUnit CU = getCompileUnit();
369   if (!CU.Verify())
370     return false;
371   return true;
372 }
373
374 /// Verify - Verify that a subprogram descriptor is well formed.
375 bool DISubprogram::Verify() const {
376   if (!DbgNode)
377     return false;
378
379   if (!getContext().Verify())
380     return false;
381
382   DICompileUnit CU = getCompileUnit();
383   if (!CU.Verify())
384     return false;
385
386   DICompositeType Ty = getType();
387   if (!Ty.Verify())
388     return false;
389   return true;
390 }
391
392 /// Verify - Verify that a global variable descriptor is well formed.
393 bool DIGlobalVariable::Verify() const {
394   if (!DbgNode)
395     return false;
396
397   if (getDisplayName().empty())
398     return false;
399
400   if (!getContext().Verify())
401     return false;
402
403   DICompileUnit CU = getCompileUnit();
404   if (!CU.Verify())
405     return false;
406
407   DIType Ty = getType();
408   if (!Ty.Verify())
409     return false;
410
411   if (!getGlobal() && !getConstant())
412     return false;
413
414   return true;
415 }
416
417 /// Verify - Verify that a variable descriptor is well formed.
418 bool DIVariable::Verify() const {
419   if (!DbgNode)
420     return false;
421
422   if (!getContext().Verify())
423     return false;
424
425   if (!getCompileUnit().Verify())
426     return false;
427
428   DIType Ty = getType();
429   if (!Ty.Verify())
430     return false;
431
432   return true;
433 }
434
435 /// Verify - Verify that a location descriptor is well formed.
436 bool DILocation::Verify() const {
437   if (!DbgNode)
438     return false;
439
440   return DbgNode->getNumOperands() == 4;
441 }
442
443 /// Verify - Verify that a namespace descriptor is well formed.
444 bool DINameSpace::Verify() const {
445   if (!DbgNode)
446     return false;
447   if (getName().empty())
448     return false;
449   if (!getCompileUnit().Verify())
450     return false;
451   return true;
452 }
453
454 /// getOriginalTypeSize - If this type is derived from a base type then
455 /// return base type size.
456 uint64_t DIDerivedType::getOriginalTypeSize() const {
457   unsigned Tag = getTag();
458   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
459       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
460       Tag == dwarf::DW_TAG_restrict_type) {
461     DIType BaseType = getTypeDerivedFrom();
462     // If this type is not derived from any type then take conservative
463     // approach.
464     if (!BaseType.isValid())
465       return getSizeInBits();
466     if (BaseType.isDerivedType())
467       return DIDerivedType(BaseType).getOriginalTypeSize();
468     else
469       return BaseType.getSizeInBits();
470   }
471
472   return getSizeInBits();
473 }
474
475 /// isInlinedFnArgument - Return true if this variable provides debugging
476 /// information for an inlined function arguments.
477 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
478   assert(CurFn && "Invalid function");
479   if (!getContext().isSubprogram())
480     return false;
481   // This variable is not inlined function argument if its scope
482   // does not describe current function.
483   return !(DISubprogram(getContext()).describes(CurFn));
484 }
485
486 /// describes - Return true if this subprogram provides debugging
487 /// information for the function F.
488 bool DISubprogram::describes(const Function *F) {
489   assert(F && "Invalid function");
490   if (F == getFunction())
491     return true;
492   StringRef Name = getLinkageName();
493   if (Name.empty())
494     Name = getName();
495   if (F->getName() == Name)
496     return true;
497   return false;
498 }
499
500 unsigned DISubprogram::isOptimized() const {
501   assert (DbgNode && "Invalid subprogram descriptor!");
502   if (DbgNode->getNumOperands() == 16)
503     return getUnsignedField(15);
504   return 0;
505 }
506
507 StringRef DIScope::getFilename() const {
508   if (!DbgNode)
509     return StringRef();
510   if (isLexicalBlock())
511     return DILexicalBlock(DbgNode).getFilename();
512   if (isSubprogram())
513     return DISubprogram(DbgNode).getFilename();
514   if (isCompileUnit())
515     return DICompileUnit(DbgNode).getFilename();
516   if (isNameSpace())
517     return DINameSpace(DbgNode).getFilename();
518   if (isType())
519     return DIType(DbgNode).getFilename();
520   if (isFile())
521     return DIFile(DbgNode).getFilename();
522   assert(0 && "Invalid DIScope!");
523   return StringRef();
524 }
525
526 StringRef DIScope::getDirectory() const {
527   if (!DbgNode)
528     return StringRef();
529   if (isLexicalBlock())
530     return DILexicalBlock(DbgNode).getDirectory();
531   if (isSubprogram())
532     return DISubprogram(DbgNode).getDirectory();
533   if (isCompileUnit())
534     return DICompileUnit(DbgNode).getDirectory();
535   if (isNameSpace())
536     return DINameSpace(DbgNode).getDirectory();
537   if (isType())
538     return DIType(DbgNode).getDirectory();
539   if (isFile())
540     return DIFile(DbgNode).getDirectory();
541   assert(0 && "Invalid DIScope!");
542   return StringRef();
543 }
544
545 //===----------------------------------------------------------------------===//
546 // DIDescriptor: dump routines for all descriptors.
547 //===----------------------------------------------------------------------===//
548
549
550 /// print - Print descriptor.
551 void DIDescriptor::print(raw_ostream &OS) const {
552   OS << "[" << dwarf::TagString(getTag()) << "] ";
553   OS.write_hex((intptr_t) &*DbgNode) << ']';
554 }
555
556 /// print - Print compile unit.
557 void DICompileUnit::print(raw_ostream &OS) const {
558   if (getLanguage())
559     OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
560
561   OS << " [" << getDirectory() << "/" << getFilename() << "]";
562 }
563
564 /// print - Print type.
565 void DIType::print(raw_ostream &OS) const {
566   if (!DbgNode) return;
567
568   StringRef Res = getName();
569   if (!Res.empty())
570     OS << " [" << Res << "] ";
571
572   unsigned Tag = getTag();
573   OS << " [" << dwarf::TagString(Tag) << "] ";
574
575   // TODO : Print context
576   getCompileUnit().print(OS);
577   OS << " ["
578          << "line " << getLineNumber() << ", "
579          << getSizeInBits() << " bits, "
580          << getAlignInBits() << " bit alignment, "
581          << getOffsetInBits() << " bit offset"
582          << "] ";
583
584   if (isPrivate())
585     OS << " [private] ";
586   else if (isProtected())
587     OS << " [protected] ";
588
589   if (isForwardDecl())
590     OS << " [fwd] ";
591
592   if (isBasicType())
593     DIBasicType(DbgNode).print(OS);
594   else if (isDerivedType())
595     DIDerivedType(DbgNode).print(OS);
596   else if (isCompositeType())
597     DICompositeType(DbgNode).print(OS);
598   else {
599     OS << "Invalid DIType\n";
600     return;
601   }
602
603   OS << "\n";
604 }
605
606 /// print - Print basic type.
607 void DIBasicType::print(raw_ostream &OS) const {
608   OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
609 }
610
611 /// print - Print derived type.
612 void DIDerivedType::print(raw_ostream &OS) const {
613   OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
614 }
615
616 /// print - Print composite type.
617 void DICompositeType::print(raw_ostream &OS) const {
618   DIArray A = getTypeArray();
619   OS << " [" << A.getNumElements() << " elements]";
620 }
621
622 /// print - Print subprogram.
623 void DISubprogram::print(raw_ostream &OS) const {
624   StringRef Res = getName();
625   if (!Res.empty())
626     OS << " [" << Res << "] ";
627
628   unsigned Tag = getTag();
629   OS << " [" << dwarf::TagString(Tag) << "] ";
630
631   // TODO : Print context
632   getCompileUnit().print(OS);
633   OS << " [" << getLineNumber() << "] ";
634
635   if (isLocalToUnit())
636     OS << " [local] ";
637
638   if (isDefinition())
639     OS << " [def] ";
640
641   OS << "\n";
642 }
643
644 /// print - Print global variable.
645 void DIGlobalVariable::print(raw_ostream &OS) const {
646   OS << " [";
647   StringRef Res = getName();
648   if (!Res.empty())
649     OS << " [" << Res << "] ";
650
651   unsigned Tag = getTag();
652   OS << " [" << dwarf::TagString(Tag) << "] ";
653
654   // TODO : Print context
655   getCompileUnit().print(OS);
656   OS << " [" << getLineNumber() << "] ";
657
658   if (isLocalToUnit())
659     OS << " [local] ";
660
661   if (isDefinition())
662     OS << " [def] ";
663
664   if (isGlobalVariable())
665     DIGlobalVariable(DbgNode).print(OS);
666   OS << "]\n";
667 }
668
669 /// print - Print variable.
670 void DIVariable::print(raw_ostream &OS) const {
671   StringRef Res = getName();
672   if (!Res.empty())
673     OS << " [" << Res << "] ";
674
675   getCompileUnit().print(OS);
676   OS << " [" << getLineNumber() << "] ";
677   getType().print(OS);
678   OS << "\n";
679
680   // FIXME: Dump complex addresses
681 }
682
683 /// dump - Print descriptor to dbgs() with a newline.
684 void DIDescriptor::dump() const {
685   print(dbgs()); dbgs() << '\n';
686 }
687
688 /// dump - Print compile unit to dbgs() with a newline.
689 void DICompileUnit::dump() const {
690   print(dbgs()); dbgs() << '\n';
691 }
692
693 /// dump - Print type to dbgs() with a newline.
694 void DIType::dump() const {
695   print(dbgs()); dbgs() << '\n';
696 }
697
698 /// dump - Print basic type to dbgs() with a newline.
699 void DIBasicType::dump() const {
700   print(dbgs()); dbgs() << '\n';
701 }
702
703 /// dump - Print derived type to dbgs() with a newline.
704 void DIDerivedType::dump() const {
705   print(dbgs()); dbgs() << '\n';
706 }
707
708 /// dump - Print composite type to dbgs() with a newline.
709 void DICompositeType::dump() const {
710   print(dbgs()); dbgs() << '\n';
711 }
712
713 /// dump - Print subprogram to dbgs() with a newline.
714 void DISubprogram::dump() const {
715   print(dbgs()); dbgs() << '\n';
716 }
717
718 /// dump - Print global variable.
719 void DIGlobalVariable::dump() const {
720   print(dbgs()); dbgs() << '\n';
721 }
722
723 /// dump - Print variable.
724 void DIVariable::dump() const {
725   print(dbgs()); dbgs() << '\n';
726 }
727
728 //===----------------------------------------------------------------------===//
729 // DIFactory: Basic Helpers
730 //===----------------------------------------------------------------------===//
731
732 DIFactory::DIFactory(Module &m)
733   : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
734
735 Constant *DIFactory::GetTagConstant(unsigned TAG) {
736   assert((TAG & LLVMDebugVersionMask) == 0 &&
737          "Tag too large for debug encoding!");
738   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
739 }
740
741 //===----------------------------------------------------------------------===//
742 // DIFactory: Primary Constructors
743 //===----------------------------------------------------------------------===//
744
745 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
746 /// This implicitly uniques the arrays created.
747 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
748   if (NumTys == 0) {
749     Value *Null = llvm::Constant::getNullValue(Type::getInt32Ty(VMContext));
750     return DIArray(MDNode::get(VMContext, &Null, 1));
751   }
752
753   SmallVector<Value *, 16> Elts(Tys, Tys+NumTys);
754   return DIArray(MDNode::get(VMContext, Elts.data(), Elts.size()));
755 }
756
757 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
758 /// implicitly uniques the values returned.
759 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
760   Value *Elts[] = {
761     GetTagConstant(dwarf::DW_TAG_subrange_type),
762     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
763     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
764   };
765
766   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
767 }
768
769 /// CreateUnspecifiedParameter - Create unspeicified type descriptor
770 /// for the subroutine type.
771 DIDescriptor DIFactory::CreateUnspecifiedParameter() {
772   Value *Elts[] = {
773     GetTagConstant(dwarf::DW_TAG_unspecified_parameters)
774   };
775   return DIDescriptor(MDNode::get(VMContext, &Elts[0], 1));
776 }
777
778 /// CreateCompileUnit - Create a new descriptor for the specified compile
779 /// unit.  Note that this does not unique compile units within the module.
780 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
781                                            StringRef Filename,
782                                            StringRef Directory,
783                                            StringRef Producer,
784                                            bool isMain,
785                                            bool isOptimized,
786                                            StringRef Flags,
787                                            unsigned RunTimeVer) {
788   Value *Elts[] = {
789     GetTagConstant(dwarf::DW_TAG_compile_unit),
790     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
791     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
792     MDString::get(VMContext, Filename),
793     MDString::get(VMContext, Directory),
794     MDString::get(VMContext, Producer),
795     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
796     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
797     MDString::get(VMContext, Flags),
798     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
799   };
800
801   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
802 }
803
804 /// CreateFile -  Create a new descriptor for the specified file.
805 DIFile DIFactory::CreateFile(StringRef Filename,
806                              StringRef Directory,
807                              DICompileUnit CU) {
808   Value *Elts[] = {
809     GetTagConstant(dwarf::DW_TAG_file_type),
810     MDString::get(VMContext, Filename),
811     MDString::get(VMContext, Directory),
812     CU
813   };
814
815   return DIFile(MDNode::get(VMContext, &Elts[0], 4));
816 }
817
818 /// CreateEnumerator - Create a single enumerator value.
819 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
820   Value *Elts[] = {
821     GetTagConstant(dwarf::DW_TAG_enumerator),
822     MDString::get(VMContext, Name),
823     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
824   };
825   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
826 }
827
828
829 /// CreateBasicType - Create a basic type like int, float, etc.
830 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
831                                        StringRef Name,
832                                        DIFile F,
833                                        unsigned LineNumber,
834                                        uint64_t SizeInBits,
835                                        uint64_t AlignInBits,
836                                        uint64_t OffsetInBits, unsigned Flags,
837                                        unsigned Encoding) {
838   Value *Elts[] = {
839     GetTagConstant(dwarf::DW_TAG_base_type),
840     Context,
841     MDString::get(VMContext, Name),
842     F,
843     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
844     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
845     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
846     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
847     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
848     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
849   };
850   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
851 }
852
853
854 /// CreateBasicType - Create a basic type like int, float, etc.
855 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
856                                          StringRef Name,
857                                          DIFile F,
858                                          unsigned LineNumber,
859                                          Constant *SizeInBits,
860                                          Constant *AlignInBits,
861                                          Constant *OffsetInBits, unsigned Flags,
862                                          unsigned Encoding) {
863   Value *Elts[] = {
864     GetTagConstant(dwarf::DW_TAG_base_type),
865     Context,
866     MDString::get(VMContext, Name),
867     F,
868     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
869     SizeInBits,
870     AlignInBits,
871     OffsetInBits,
872     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
873     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
874   };
875   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
876 }
877
878 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
879 DIType DIFactory::CreateArtificialType(DIType Ty) {
880   if (Ty.isArtificial())
881     return Ty;
882
883   SmallVector<Value *, 9> Elts;
884   MDNode *N = Ty;
885   assert (N && "Unexpected input DIType!");
886   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
887     if (Value *V = N->getOperand(i))
888       Elts.push_back(V);
889     else
890       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
891   }
892
893   unsigned CurFlags = Ty.getFlags();
894   CurFlags = CurFlags | DIType::FlagArtificial;
895
896   // Flags are stored at this slot.
897   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
898
899   return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
900 }
901
902 /// CreateDerivedType - Create a derived type like const qualified type,
903 /// pointer, typedef, etc.
904 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
905                                            DIDescriptor Context,
906                                            StringRef Name,
907                                            DIFile F,
908                                            unsigned LineNumber,
909                                            uint64_t SizeInBits,
910                                            uint64_t AlignInBits,
911                                            uint64_t OffsetInBits,
912                                            unsigned Flags,
913                                            DIType DerivedFrom) {
914   Value *Elts[] = {
915     GetTagConstant(Tag),
916     Context,
917     MDString::get(VMContext, Name),
918     F,
919     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
920     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
921     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
922     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
923     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
924     DerivedFrom,
925   };
926   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
927 }
928
929
930 /// CreateDerivedType - Create a derived type like const qualified type,
931 /// pointer, typedef, etc.
932 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
933                                              DIDescriptor Context,
934                                              StringRef Name,
935                                              DIFile F,
936                                              unsigned LineNumber,
937                                              Constant *SizeInBits,
938                                              Constant *AlignInBits,
939                                              Constant *OffsetInBits,
940                                              unsigned Flags,
941                                              DIType DerivedFrom) {
942   Value *Elts[] = {
943     GetTagConstant(Tag),
944     Context,
945     MDString::get(VMContext, Name),
946     F,
947     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
948     SizeInBits,
949     AlignInBits,
950     OffsetInBits,
951     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
952     DerivedFrom,
953   };
954   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
955 }
956
957
958 /// CreateCompositeType - Create a composite type like array, struct, etc.
959 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
960                                                DIDescriptor Context,
961                                                StringRef Name,
962                                                DIFile F,
963                                                unsigned LineNumber,
964                                                uint64_t SizeInBits,
965                                                uint64_t AlignInBits,
966                                                uint64_t OffsetInBits,
967                                                unsigned Flags,
968                                                DIType DerivedFrom,
969                                                DIArray Elements,
970                                                unsigned RuntimeLang,
971                                                MDNode *ContainingType) {
972
973   Value *Elts[] = {
974     GetTagConstant(Tag),
975     Context,
976     MDString::get(VMContext, Name),
977     F,
978     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
979     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
980     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
981     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
982     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
983     DerivedFrom,
984     Elements,
985     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
986     ContainingType
987   };
988
989   MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
990   // Create a named metadata so that we do not lose this enum info.
991   if (Tag == dwarf::DW_TAG_enumeration_type) {
992     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
993     NMD->addOperand(Node);
994   }
995   return DICompositeType(Node);
996 }
997
998 /// CreateTemporaryType - Create a temporary forward-declared type.
999 DIType DIFactory::CreateTemporaryType() {
1000   // Give the temporary MDNode a tag. It doesn't matter what tag we
1001   // use here as long as DIType accepts it.
1002   Value *Elts[] = {
1003     GetTagConstant(DW_TAG_base_type)
1004   };
1005   MDNode *Node = MDNode::getTemporary(VMContext, Elts, array_lengthof(Elts));
1006   return DIType(Node);
1007 }
1008
1009 /// CreateTemporaryType - Create a temporary forward-declared type.
1010 DIType DIFactory::CreateTemporaryType(DIFile F) {
1011   // Give the temporary MDNode a tag. It doesn't matter what tag we
1012   // use here as long as DIType accepts it.
1013   Value *Elts[] = {
1014     GetTagConstant(DW_TAG_base_type),
1015     F.getCompileUnit(),
1016     NULL,
1017     F
1018   };
1019   MDNode *Node = MDNode::getTemporary(VMContext, Elts, array_lengthof(Elts));
1020   return DIType(Node);
1021 }
1022
1023 /// CreateCompositeType - Create a composite type like array, struct, etc.
1024 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
1025                                                  DIDescriptor Context,
1026                                                  StringRef Name,
1027                                                  DIFile F,
1028                                                  unsigned LineNumber,
1029                                                  Constant *SizeInBits,
1030                                                  Constant *AlignInBits,
1031                                                  Constant *OffsetInBits,
1032                                                  unsigned Flags,
1033                                                  DIType DerivedFrom,
1034                                                  DIArray Elements,
1035                                                  unsigned RuntimeLang,
1036                                                  MDNode *ContainingType) {
1037   Value *Elts[] = {
1038     GetTagConstant(Tag),
1039     Context,
1040     MDString::get(VMContext, Name),
1041     F,
1042     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
1043     SizeInBits,
1044     AlignInBits,
1045     OffsetInBits,
1046     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1047     DerivedFrom,
1048     Elements,
1049     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
1050     ContainingType
1051   };
1052   MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
1053   // Create a named metadata so that we do not lose this enum info.
1054   if (Tag == dwarf::DW_TAG_enumeration_type) {
1055     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
1056     NMD->addOperand(Node);
1057   }
1058   return DICompositeType(Node);
1059 }
1060
1061
1062 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
1063 /// See comments in DISubprogram for descriptions of these fields.  This
1064 /// method does not unique the generated descriptors.
1065 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
1066                                          StringRef Name,
1067                                          StringRef DisplayName,
1068                                          StringRef LinkageName,
1069                                          DIFile F,
1070                                          unsigned LineNo, DIType Ty,
1071                                          bool isLocalToUnit,
1072                                          bool isDefinition,
1073                                          unsigned VK, unsigned VIndex,
1074                                          DIType ContainingType,
1075                                          unsigned Flags,
1076                                          bool isOptimized,
1077                                          Function *Fn) {
1078
1079   Value *Elts[] = {
1080     GetTagConstant(dwarf::DW_TAG_subprogram),
1081     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1082     Context,
1083     MDString::get(VMContext, Name),
1084     MDString::get(VMContext, DisplayName),
1085     MDString::get(VMContext, LinkageName),
1086     F,
1087     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1088     Ty,
1089     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1090     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1091     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
1092     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1093     ContainingType,
1094     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
1095     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1096     Fn
1097   };
1098   MDNode *Node = MDNode::get(VMContext, &Elts[0], 17);
1099
1100   // Create a named metadata so that we do not lose this mdnode.
1101   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1102   NMD->addOperand(Node);
1103   return DISubprogram(Node);
1104 }
1105
1106 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
1107 /// given declaration.
1108 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration){
1109   if (SPDeclaration.isDefinition())
1110     return DISubprogram(SPDeclaration);
1111
1112   MDNode *DeclNode = SPDeclaration;
1113   Value *Elts[] = {
1114     GetTagConstant(dwarf::DW_TAG_subprogram),
1115     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1116     DeclNode->getOperand(2), // Context
1117     DeclNode->getOperand(3), // Name
1118     DeclNode->getOperand(4), // DisplayName
1119     DeclNode->getOperand(5), // LinkageName
1120     DeclNode->getOperand(6), // CompileUnit
1121     DeclNode->getOperand(7), // LineNo
1122     DeclNode->getOperand(8), // Type
1123     DeclNode->getOperand(9), // isLocalToUnit
1124     ConstantInt::get(Type::getInt1Ty(VMContext), true),
1125     DeclNode->getOperand(11), // Virtuality
1126     DeclNode->getOperand(12), // VIndex
1127     DeclNode->getOperand(13), // Containting Type
1128     DeclNode->getOperand(14), // Flags
1129     DeclNode->getOperand(15), // isOptimized
1130     SPDeclaration.getFunction()
1131   };
1132   MDNode *Node =MDNode::get(VMContext, &Elts[0], 16);
1133
1134   // Create a named metadata so that we do not lose this mdnode.
1135   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1136   NMD->addOperand(Node);
1137   return DISubprogram(Node);
1138 }
1139
1140 /// CreateGlobalVariable - Create a new descriptor for the specified global.
1141 DIGlobalVariable
1142 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1143                                 StringRef DisplayName,
1144                                 StringRef LinkageName,
1145                                 DIFile F,
1146                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1147                                 bool isDefinition, llvm::GlobalVariable *Val) {
1148   Value *Elts[] = {
1149     GetTagConstant(dwarf::DW_TAG_variable),
1150     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1151     Context,
1152     MDString::get(VMContext, Name),
1153     MDString::get(VMContext, DisplayName),
1154     MDString::get(VMContext, LinkageName),
1155     F,
1156     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1157     Ty,
1158     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1159     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1160     Val
1161   };
1162
1163   Value *const *Vs = &Elts[0];
1164   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1165
1166   // Create a named metadata so that we do not lose this mdnode.
1167   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1168   NMD->addOperand(Node);
1169
1170   return DIGlobalVariable(Node);
1171 }
1172
1173 /// CreateGlobalVariable - Create a new descriptor for the specified constant.
1174 DIGlobalVariable
1175 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1176                                 StringRef DisplayName,
1177                                 StringRef LinkageName,
1178                                 DIFile F,
1179                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1180                                 bool isDefinition, llvm::Constant *Val) {
1181   Value *Elts[] = {
1182     GetTagConstant(dwarf::DW_TAG_variable),
1183     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1184     Context,
1185     MDString::get(VMContext, Name),
1186     MDString::get(VMContext, DisplayName),
1187     MDString::get(VMContext, LinkageName),
1188     F,
1189     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1190     Ty,
1191     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1192     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1193     Val
1194   };
1195
1196   Value *const *Vs = &Elts[0];
1197   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1198
1199   // Create a named metadata so that we do not lose this mdnode.
1200   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1201   NMD->addOperand(Node);
1202
1203   return DIGlobalVariable(Node);
1204 }
1205
1206 /// fixupObjcLikeName - Replace contains special characters used
1207 /// in a typical Objective-C names with '.' in a given string.
1208 static void fixupObjcLikeName(std::string &Str) {
1209   for (size_t i = 0, e = Str.size(); i < e; ++i) {
1210     char C = Str[i];
1211     if (C == '[' || C == ']' || C == ' ' || C == ':' || C == '+' ||
1212         C == '(' || C == ')')
1213       Str[i] = '.';
1214   }
1215 }
1216
1217 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
1218 /// to hold function specific information.
1219 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, StringRef FuncName) {
1220   SmallString<32> Out;
1221   if (FuncName.find('[') == StringRef::npos)
1222     return M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FuncName)
1223                                       .toStringRef(Out)); 
1224   std::string Name = FuncName;
1225   fixupObjcLikeName(Name);
1226   return M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", Name)
1227                                     .toStringRef(Out));
1228 }
1229
1230 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is 
1231 /// suitable to hold function specific information.
1232 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, StringRef FuncName) {
1233   if (FuncName.find('[') == StringRef::npos)
1234     return M.getNamedMetadata(Twine("llvm.dbg.lv.", FuncName));
1235   std::string Name = FuncName;
1236   fixupObjcLikeName(Name);
1237   return M.getNamedMetadata(Twine("llvm.dbg.lv.", Name));
1238 }
1239
1240 /// CreateVariable - Create a new descriptor for the specified variable.
1241 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1242                                      StringRef Name,
1243                                      DIFile F,
1244                                      unsigned LineNo,
1245                                      DIType Ty, bool AlwaysPreserve,
1246                                      unsigned Flags) {
1247   Value *Elts[] = {
1248     GetTagConstant(Tag),
1249     Context,
1250     MDString::get(VMContext, Name),
1251     F,
1252     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1253     Ty,
1254     ConstantInt::get(Type::getInt32Ty(VMContext), Flags)
1255   };
1256   MDNode *Node = MDNode::get(VMContext, &Elts[0], 7);
1257   if (AlwaysPreserve) {
1258     // The optimizer may remove local variable. If there is an interest
1259     // to preserve variable info in such situation then stash it in a
1260     // named mdnode.
1261     DISubprogram Fn(getDISubprogram(Context));
1262     StringRef FName = "fn";
1263     if (Fn.getFunction())
1264       FName = Fn.getFunction()->getName();
1265     char One = '\1';
1266     if (FName.startswith(StringRef(&One, 1)))
1267       FName = FName.substr(1);
1268
1269
1270     NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, FName);
1271     FnLocals->addOperand(Node);
1272   }
1273   return DIVariable(Node);
1274 }
1275
1276
1277 /// CreateComplexVariable - Create a new descriptor for the specified variable
1278 /// which has a complex address expression for its address.
1279 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1280                                             StringRef Name, DIFile F,
1281                                             unsigned LineNo,
1282                                             DIType Ty, Value *const *Addr,
1283                                             unsigned NumAddr) {
1284   SmallVector<Value *, 15> Elts;
1285   Elts.push_back(GetTagConstant(Tag));
1286   Elts.push_back(Context);
1287   Elts.push_back(MDString::get(VMContext, Name));
1288   Elts.push_back(F);
1289   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1290   Elts.push_back(Ty);
1291   Elts.append(Addr, Addr+NumAddr);
1292
1293   return DIVariable(MDNode::get(VMContext, Elts.data(), Elts.size()));
1294 }
1295
1296
1297 /// CreateBlock - This creates a descriptor for a lexical block with the
1298 /// specified parent VMContext.
1299 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1300                                              DIFile F, unsigned LineNo,
1301                                              unsigned Col) {
1302   // Defeat MDNode uniqing for lexical blocks.
1303   static unsigned int unique_id = 0;
1304   Value *Elts[] = {
1305     GetTagConstant(dwarf::DW_TAG_lexical_block),
1306     Context,
1307     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1308     ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1309     F,
1310     ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1311   };
1312   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1313 }
1314
1315 /// CreateNameSpace - This creates new descriptor for a namespace
1316 /// with the specified parent context.
1317 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1318                                        DIFile F,
1319                                        unsigned LineNo) {
1320   Value *Elts[] = {
1321     GetTagConstant(dwarf::DW_TAG_namespace),
1322     Context,
1323     MDString::get(VMContext, Name),
1324     F,
1325     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1326   };
1327   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1328 }
1329
1330 /// CreateLocation - Creates a debug info location.
1331 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1332                                      DIScope S, DILocation OrigLoc) {
1333   Value *Elts[] = {
1334     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1335     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1336     S,
1337     OrigLoc,
1338   };
1339   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1340 }
1341
1342 //===----------------------------------------------------------------------===//
1343 // DIFactory: Routines for inserting code into a function
1344 //===----------------------------------------------------------------------===//
1345
1346 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1347 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1348                                       Instruction *InsertBefore) {
1349   assert(Storage && "no storage passed to dbg.declare");
1350   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1351   if (!DeclareFn)
1352     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1353
1354   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1355                     D };
1356   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1357 }
1358
1359 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1360 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1361                                       BasicBlock *InsertAtEnd) {
1362   assert(Storage && "no storage passed to dbg.declare");
1363   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1364   if (!DeclareFn)
1365     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1366
1367   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1368                     D };
1369
1370   // If this block already has a terminator then insert this intrinsic
1371   // before the terminator.
1372   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1373     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1374   else
1375     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1376
1377 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1378 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1379                                                 DIVariable D,
1380                                                 Instruction *InsertBefore) {
1381   assert(V && "no value passed to dbg.value");
1382   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1383   if (!ValueFn)
1384     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1385
1386   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1387                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1388                     D };
1389   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1390 }
1391
1392 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1393 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1394                                                 DIVariable D,
1395                                                 BasicBlock *InsertAtEnd) {
1396   assert(V && "no value passed to dbg.value");
1397   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1398   if (!ValueFn)
1399     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1400
1401   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1402                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1403                     D };
1404   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1405 }
1406
1407 // RecordType - Record DIType in a module such that it is not lost even if
1408 // it is not referenced through debug info anchors.
1409 void DIFactory::RecordType(DIType T) {
1410   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.ty");
1411   NMD->addOperand(T);
1412 }
1413
1414
1415 //===----------------------------------------------------------------------===//
1416 // DebugInfoFinder implementations.
1417 //===----------------------------------------------------------------------===//
1418
1419 /// processModule - Process entire module and collect debug info.
1420 void DebugInfoFinder::processModule(Module &M) {
1421   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1422     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1423       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1424            ++BI) {
1425         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1426           processDeclare(DDI);
1427
1428         DebugLoc Loc = BI->getDebugLoc();
1429         if (Loc.isUnknown())
1430           continue;
1431
1432         LLVMContext &Ctx = BI->getContext();
1433         DIDescriptor Scope(Loc.getScope(Ctx));
1434
1435         if (Scope.isCompileUnit())
1436           addCompileUnit(DICompileUnit(Scope));
1437         else if (Scope.isSubprogram())
1438           processSubprogram(DISubprogram(Scope));
1439         else if (Scope.isLexicalBlock())
1440           processLexicalBlock(DILexicalBlock(Scope));
1441
1442         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1443           processLocation(DILocation(IA));
1444       }
1445
1446   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1447     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1448       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1449       if (addGlobalVariable(DIG)) {
1450         addCompileUnit(DIG.getCompileUnit());
1451         processType(DIG.getType());
1452       }
1453     }
1454   }
1455
1456   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1457     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1458       processSubprogram(DISubprogram(NMD->getOperand(i)));
1459 }
1460
1461 /// processLocation - Process DILocation.
1462 void DebugInfoFinder::processLocation(DILocation Loc) {
1463   if (!Loc.Verify()) return;
1464   DIDescriptor S(Loc.getScope());
1465   if (S.isCompileUnit())
1466     addCompileUnit(DICompileUnit(S));
1467   else if (S.isSubprogram())
1468     processSubprogram(DISubprogram(S));
1469   else if (S.isLexicalBlock())
1470     processLexicalBlock(DILexicalBlock(S));
1471   processLocation(Loc.getOrigLocation());
1472 }
1473
1474 /// processType - Process DIType.
1475 void DebugInfoFinder::processType(DIType DT) {
1476   if (!addType(DT))
1477     return;
1478
1479   addCompileUnit(DT.getCompileUnit());
1480   if (DT.isCompositeType()) {
1481     DICompositeType DCT(DT);
1482     processType(DCT.getTypeDerivedFrom());
1483     DIArray DA = DCT.getTypeArray();
1484     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1485       DIDescriptor D = DA.getElement(i);
1486       if (D.isType())
1487         processType(DIType(D));
1488       else if (D.isSubprogram())
1489         processSubprogram(DISubprogram(D));
1490     }
1491   } else if (DT.isDerivedType()) {
1492     DIDerivedType DDT(DT);
1493     processType(DDT.getTypeDerivedFrom());
1494   }
1495 }
1496
1497 /// processLexicalBlock
1498 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1499   DIScope Context = LB.getContext();
1500   if (Context.isLexicalBlock())
1501     return processLexicalBlock(DILexicalBlock(Context));
1502   else
1503     return processSubprogram(DISubprogram(Context));
1504 }
1505
1506 /// processSubprogram - Process DISubprogram.
1507 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1508   if (!addSubprogram(SP))
1509     return;
1510   addCompileUnit(SP.getCompileUnit());
1511   processType(SP.getType());
1512 }
1513
1514 /// processDeclare - Process DbgDeclareInst.
1515 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1516   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1517   if (!N) return;
1518
1519   DIDescriptor DV(N);
1520   if (!DV.isVariable())
1521     return;
1522
1523   if (!NodesSeen.insert(DV))
1524     return;
1525
1526   addCompileUnit(DIVariable(N).getCompileUnit());
1527   processType(DIVariable(N).getType());
1528 }
1529
1530 /// addType - Add type into Tys.
1531 bool DebugInfoFinder::addType(DIType DT) {
1532   if (!DT.isValid())
1533     return false;
1534
1535   if (!NodesSeen.insert(DT))
1536     return false;
1537
1538   TYs.push_back(DT);
1539   return true;
1540 }
1541
1542 /// addCompileUnit - Add compile unit into CUs.
1543 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1544   if (!CU.Verify())
1545     return false;
1546
1547   if (!NodesSeen.insert(CU))
1548     return false;
1549
1550   CUs.push_back(CU);
1551   return true;
1552 }
1553
1554 /// addGlobalVariable - Add global variable into GVs.
1555 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1556   if (!DIDescriptor(DIG).isGlobalVariable())
1557     return false;
1558
1559   if (!NodesSeen.insert(DIG))
1560     return false;
1561
1562   GVs.push_back(DIG);
1563   return true;
1564 }
1565
1566 // addSubprogram - Add subprgoram into SPs.
1567 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1568   if (!DIDescriptor(SP).isSubprogram())
1569     return false;
1570
1571   if (!NodesSeen.insert(SP))
1572     return false;
1573
1574   SPs.push_back(SP);
1575   return true;
1576 }
1577
1578 /// getDISubprogram - Find subprogram that is enclosing this scope.
1579 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1580   DIDescriptor D(Scope);
1581   if (D.isSubprogram())
1582     return DISubprogram(Scope);
1583
1584   if (D.isLexicalBlock())
1585     return getDISubprogram(DILexicalBlock(Scope).getContext());
1586
1587   return DISubprogram();
1588 }
1589
1590 /// getDICompositeType - Find underlying composite type.
1591 DICompositeType llvm::getDICompositeType(DIType T) {
1592   if (T.isCompositeType())
1593     return DICompositeType(T);
1594
1595   if (T.isDerivedType())
1596     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1597
1598   return DICompositeType();
1599 }