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