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