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