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