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