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