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 
DIDescriptor(const DIFile F)36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
37 }
38 
DIDescriptor(const DISubprogram F)39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
40 }
41 
DIDescriptor(const DILexicalBlock F)42 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
43 }
44 
DIDescriptor(const DIVariable F)45 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
46 }
47 
DIDescriptor(const DIType F)48 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
49 }
50 
51 StringRef
getStringField(unsigned Elt) const52 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 
getUInt64Field(unsigned Elt) const63 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 
getDescriptorField(unsigned Elt) const74 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 
getGlobalVariableField(unsigned Elt) const84 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 
getConstantField(unsigned Elt) const93 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 
getFunctionField(unsigned Elt) const102 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 
getNumAddrElements() const111 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.
isBasicType() const122 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.
isDerivedType() const127 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.
isCompositeType() const148 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.
isVariable() const165 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.
isType() const178 bool DIDescriptor::isType() const {
179   return isBasicType() || isCompositeType() || isDerivedType();
180 }
181 
182 /// isSubprogram - Return true if the specified tag is legal for
183 /// DISubprogram.
isSubprogram() const184 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.
isGlobalVariable() const190 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.
isGlobal() const196 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.
isScope() const202 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.
isCompileUnit() const217 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.
isFile() const222 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.
isNameSpace() const227 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.
isLexicalBlock() const232 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.
isSubrange() const237 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.
isEnumerator() const242 bool DIDescriptor::isEnumerator() const {
243   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
244 }
245 
246 //===----------------------------------------------------------------------===//
247 // Simple Descriptor Constructors and other Methods
248 //===----------------------------------------------------------------------===//
249 
DIType(const MDNode * N)250 DIType::DIType(const MDNode *N) : DIScope(N) {
251   if (!N) return;
252   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
253     DbgNode = 0;
254   }
255 }
256 
getNumElements() const257 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.
replaceAllUsesWith(DIDescriptor & D)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.
Verify() const284 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.
Verify() const295 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.
Verify() const308 bool DIBasicType::Verify() const {
309   return isBasicType();
310 }
311 
312 /// Verify - Verify that a derived type descriptor is well formed.
Verify() const313 bool DIDerivedType::Verify() const {
314   return isDerivedType();
315 }
316 
317 /// Verify - Verify that a composite type descriptor is well formed.
Verify() const318 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.
Verify() const331 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.
Verify() const349 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.
Verify() const374 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.
Verify() const392 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.
Verify() const400 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.
getOriginalTypeSize() const412 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.
isInlinedFnArgument(const Function * CurFn)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.
describes(const 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 
isOptimized() const456 unsigned DISubprogram::isOptimized() const {
457   assert (DbgNode && "Invalid subprogram descriptor!");
458   if (DbgNode->getNumOperands() == 16)
459     return getUnsignedField(15);
460   return 0;
461 }
462 
getFilename() const463 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 
getDirectory() const482 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.
print(raw_ostream & OS) const507 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.
print(raw_ostream & OS) const513 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.
print(raw_ostream & OS) const521 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.
print(raw_ostream & OS) const563 void DIBasicType::print(raw_ostream &OS) const {
564   OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
565 }
566 
567 /// print - Print derived type.
print(raw_ostream & OS) const568 void DIDerivedType::print(raw_ostream &OS) const {
569   OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
570 }
571 
572 /// print - Print composite type.
print(raw_ostream & OS) const573 void DICompositeType::print(raw_ostream &OS) const {
574   DIArray A = getTypeArray();
575   OS << " [" << A.getNumElements() << " elements]";
576 }
577 
578 /// print - Print subprogram.
print(raw_ostream & OS) const579 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.
print(raw_ostream & OS) const601 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.
print(raw_ostream & OS) const626 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.
dump() const640 void DIDescriptor::dump() const {
641   print(dbgs()); dbgs() << '\n';
642 }
643 
644 /// dump - Print compile unit to dbgs() with a newline.
dump() const645 void DICompileUnit::dump() const {
646   print(dbgs()); dbgs() << '\n';
647 }
648 
649 /// dump - Print type to dbgs() with a newline.
dump() const650 void DIType::dump() const {
651   print(dbgs()); dbgs() << '\n';
652 }
653 
654 /// dump - Print basic type to dbgs() with a newline.
dump() const655 void DIBasicType::dump() const {
656   print(dbgs()); dbgs() << '\n';
657 }
658 
659 /// dump - Print derived type to dbgs() with a newline.
dump() const660 void DIDerivedType::dump() const {
661   print(dbgs()); dbgs() << '\n';
662 }
663 
664 /// dump - Print composite type to dbgs() with a newline.
dump() const665 void DICompositeType::dump() const {
666   print(dbgs()); dbgs() << '\n';
667 }
668 
669 /// dump - Print subprogram to dbgs() with a newline.
dump() const670 void DISubprogram::dump() const {
671   print(dbgs()); dbgs() << '\n';
672 }
673 
674 /// dump - Print global variable.
dump() const675 void DIGlobalVariable::dump() const {
676   print(dbgs()); dbgs() << '\n';
677 }
678 
679 /// dump - Print variable.
dump() const680 void DIVariable::dump() const {
681   print(dbgs()); dbgs() << '\n';
682 }
683 
684 //===----------------------------------------------------------------------===//
685 // DIFactory: Basic Helpers
686 //===----------------------------------------------------------------------===//
687 
DIFactory(Module & m)688 DIFactory::DIFactory(Module &m)
689   : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
690 
GetTagConstant(unsigned TAG)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.
GetOrCreateArray(DIDescriptor * Tys,unsigned NumTys)703 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
704   SmallVector<Value*, 16> Elts;
705 
706   if (NumTys == 0)
707     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
708   else
709     for (unsigned i = 0; i != NumTys; ++i)
710       Elts.push_back(Tys[i]);
711 
712   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
713 }
714 
715 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
716 /// implicitly uniques the values returned.
GetOrCreateSubrange(int64_t Lo,int64_t Hi)717 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
718   Value *Elts[] = {
719     GetTagConstant(dwarf::DW_TAG_subrange_type),
720     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
721     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
722   };
723 
724   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
725 }
726 
727 
728 
729 /// CreateCompileUnit - Create a new descriptor for the specified compile
730 /// unit.  Note that this does not unique compile units within the module.
CreateCompileUnit(unsigned LangID,StringRef Filename,StringRef Directory,StringRef Producer,bool isMain,bool isOptimized,StringRef Flags,unsigned RunTimeVer)731 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
732                                            StringRef Filename,
733                                            StringRef Directory,
734                                            StringRef Producer,
735                                            bool isMain,
736                                            bool isOptimized,
737                                            StringRef Flags,
738                                            unsigned RunTimeVer) {
739   Value *Elts[] = {
740     GetTagConstant(dwarf::DW_TAG_compile_unit),
741     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
742     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
743     MDString::get(VMContext, Filename),
744     MDString::get(VMContext, Directory),
745     MDString::get(VMContext, Producer),
746     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
747     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
748     MDString::get(VMContext, Flags),
749     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
750   };
751 
752   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
753 }
754 
755 /// CreateFile -  Create a new descriptor for the specified file.
CreateFile(StringRef Filename,StringRef Directory,DICompileUnit CU)756 DIFile DIFactory::CreateFile(StringRef Filename,
757                              StringRef Directory,
758                              DICompileUnit CU) {
759   Value *Elts[] = {
760     GetTagConstant(dwarf::DW_TAG_file_type),
761     MDString::get(VMContext, Filename),
762     MDString::get(VMContext, Directory),
763     CU
764   };
765 
766   return DIFile(MDNode::get(VMContext, &Elts[0], 4));
767 }
768 
769 /// CreateEnumerator - Create a single enumerator value.
CreateEnumerator(StringRef Name,uint64_t Val)770 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
771   Value *Elts[] = {
772     GetTagConstant(dwarf::DW_TAG_enumerator),
773     MDString::get(VMContext, Name),
774     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
775   };
776   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
777 }
778 
779 
780 /// CreateBasicType - Create a basic type like int, float, etc.
CreateBasicType(DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,unsigned Encoding)781 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
782                                        StringRef Name,
783                                        DIFile F,
784                                        unsigned LineNumber,
785                                        uint64_t SizeInBits,
786                                        uint64_t AlignInBits,
787                                        uint64_t OffsetInBits, unsigned Flags,
788                                        unsigned Encoding) {
789   Value *Elts[] = {
790     GetTagConstant(dwarf::DW_TAG_base_type),
791     Context,
792     MDString::get(VMContext, Name),
793     F,
794     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
795     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
796     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
797     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
798     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
799     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
800   };
801   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
802 }
803 
804 
805 /// CreateBasicType - Create a basic type like int, float, etc.
CreateBasicTypeEx(DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,Constant * SizeInBits,Constant * AlignInBits,Constant * OffsetInBits,unsigned Flags,unsigned Encoding)806 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
807                                          StringRef Name,
808                                          DIFile F,
809                                          unsigned LineNumber,
810                                          Constant *SizeInBits,
811                                          Constant *AlignInBits,
812                                          Constant *OffsetInBits, unsigned Flags,
813                                          unsigned Encoding) {
814   Value *Elts[] = {
815     GetTagConstant(dwarf::DW_TAG_base_type),
816     Context,
817     MDString::get(VMContext, Name),
818     F,
819     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
820     SizeInBits,
821     AlignInBits,
822     OffsetInBits,
823     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
824     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
825   };
826   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
827 }
828 
829 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
CreateArtificialType(DIType Ty)830 DIType DIFactory::CreateArtificialType(DIType Ty) {
831   if (Ty.isArtificial())
832     return Ty;
833 
834   SmallVector<Value *, 9> Elts;
835   MDNode *N = Ty;
836   assert (N && "Unexpected input DIType!");
837   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
838     if (Value *V = N->getOperand(i))
839       Elts.push_back(V);
840     else
841       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
842   }
843 
844   unsigned CurFlags = Ty.getFlags();
845   CurFlags = CurFlags | DIType::FlagArtificial;
846 
847   // Flags are stored at this slot.
848   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
849 
850   return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
851 }
852 
853 /// CreateDerivedType - Create a derived type like const qualified type,
854 /// pointer, typedef, etc.
CreateDerivedType(unsigned Tag,DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,DIType DerivedFrom)855 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
856                                            DIDescriptor Context,
857                                            StringRef Name,
858                                            DIFile F,
859                                            unsigned LineNumber,
860                                            uint64_t SizeInBits,
861                                            uint64_t AlignInBits,
862                                            uint64_t OffsetInBits,
863                                            unsigned Flags,
864                                            DIType DerivedFrom) {
865   Value *Elts[] = {
866     GetTagConstant(Tag),
867     Context,
868     MDString::get(VMContext, Name),
869     F,
870     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
871     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
872     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
873     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
874     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
875     DerivedFrom,
876   };
877   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
878 }
879 
880 
881 /// CreateDerivedType - Create a derived type like const qualified type,
882 /// pointer, typedef, etc.
CreateDerivedTypeEx(unsigned Tag,DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,Constant * SizeInBits,Constant * AlignInBits,Constant * OffsetInBits,unsigned Flags,DIType DerivedFrom)883 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
884                                              DIDescriptor Context,
885                                              StringRef Name,
886                                              DIFile F,
887                                              unsigned LineNumber,
888                                              Constant *SizeInBits,
889                                              Constant *AlignInBits,
890                                              Constant *OffsetInBits,
891                                              unsigned Flags,
892                                              DIType DerivedFrom) {
893   Value *Elts[] = {
894     GetTagConstant(Tag),
895     Context,
896     MDString::get(VMContext, Name),
897     F,
898     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
899     SizeInBits,
900     AlignInBits,
901     OffsetInBits,
902     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
903     DerivedFrom,
904   };
905   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
906 }
907 
908 
909 /// CreateCompositeType - Create a composite type like array, struct, etc.
CreateCompositeType(unsigned Tag,DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,uint64_t SizeInBits,uint64_t AlignInBits,uint64_t OffsetInBits,unsigned Flags,DIType DerivedFrom,DIArray Elements,unsigned RuntimeLang,MDNode * ContainingType)910 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
911                                                DIDescriptor Context,
912                                                StringRef Name,
913                                                DIFile F,
914                                                unsigned LineNumber,
915                                                uint64_t SizeInBits,
916                                                uint64_t AlignInBits,
917                                                uint64_t OffsetInBits,
918                                                unsigned Flags,
919                                                DIType DerivedFrom,
920                                                DIArray Elements,
921                                                unsigned RuntimeLang,
922                                                MDNode *ContainingType) {
923 
924   Value *Elts[] = {
925     GetTagConstant(Tag),
926     Context,
927     MDString::get(VMContext, Name),
928     F,
929     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
930     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
931     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
932     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
933     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
934     DerivedFrom,
935     Elements,
936     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
937     ContainingType
938   };
939 
940   MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
941   // Create a named metadata so that we do not lose this enum info.
942   if (Tag == dwarf::DW_TAG_enumeration_type) {
943     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
944     NMD->addOperand(Node);
945   }
946   return DICompositeType(Node);
947 }
948 
949 
950 /// CreateTemporaryType - Create a temporary forward-declared type.
CreateTemporaryType()951 DIType DIFactory::CreateTemporaryType() {
952   // Give the temporary MDNode a tag. It doesn't matter what tag we
953   // use here as long as DIType accepts it.
954   Value *Elts[] = {
955     GetTagConstant(DW_TAG_base_type)
956   };
957   MDNode *Node = MDNode::getTemporary(VMContext, Elts, array_lengthof(Elts));
958   return DIType(Node);
959 }
960 
961 
962 /// CreateCompositeType - Create a composite type like array, struct, etc.
CreateCompositeTypeEx(unsigned Tag,DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNumber,Constant * SizeInBits,Constant * AlignInBits,Constant * OffsetInBits,unsigned Flags,DIType DerivedFrom,DIArray Elements,unsigned RuntimeLang,MDNode * ContainingType)963 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
964                                                  DIDescriptor Context,
965                                                  StringRef Name,
966                                                  DIFile F,
967                                                  unsigned LineNumber,
968                                                  Constant *SizeInBits,
969                                                  Constant *AlignInBits,
970                                                  Constant *OffsetInBits,
971                                                  unsigned Flags,
972                                                  DIType DerivedFrom,
973                                                  DIArray Elements,
974                                                  unsigned RuntimeLang,
975                                                  MDNode *ContainingType) {
976   Value *Elts[] = {
977     GetTagConstant(Tag),
978     Context,
979     MDString::get(VMContext, Name),
980     F,
981     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
982     SizeInBits,
983     AlignInBits,
984     OffsetInBits,
985     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
986     DerivedFrom,
987     Elements,
988     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
989     ContainingType
990   };
991   MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
992   // Create a named metadata so that we do not lose this enum info.
993   if (Tag == dwarf::DW_TAG_enumeration_type) {
994     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
995     NMD->addOperand(Node);
996   }
997   return DICompositeType(Node);
998 }
999 
1000 
1001 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
1002 /// See comments in DISubprogram for descriptions of these fields.  This
1003 /// method does not unique the generated descriptors.
CreateSubprogram(DIDescriptor Context,StringRef Name,StringRef DisplayName,StringRef LinkageName,DIFile F,unsigned LineNo,DIType Ty,bool isLocalToUnit,bool isDefinition,unsigned VK,unsigned VIndex,DIType ContainingType,bool isArtificial,bool isOptimized,Function * Fn)1004 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
1005                                          StringRef Name,
1006                                          StringRef DisplayName,
1007                                          StringRef LinkageName,
1008                                          DIFile F,
1009                                          unsigned LineNo, DIType Ty,
1010                                          bool isLocalToUnit,
1011                                          bool isDefinition,
1012                                          unsigned VK, unsigned VIndex,
1013                                          DIType ContainingType,
1014                                          bool isArtificial,
1015                                          bool isOptimized,
1016                                          Function *Fn) {
1017 
1018   Value *Elts[] = {
1019     GetTagConstant(dwarf::DW_TAG_subprogram),
1020     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1021     Context,
1022     MDString::get(VMContext, Name),
1023     MDString::get(VMContext, DisplayName),
1024     MDString::get(VMContext, LinkageName),
1025     F,
1026     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1027     Ty,
1028     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1029     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1030     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
1031     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1032     ContainingType,
1033     ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
1034     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1035     Fn
1036   };
1037   MDNode *Node = MDNode::get(VMContext, &Elts[0], 17);
1038 
1039   // Create a named metadata so that we do not lose this mdnode.
1040   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1041   NMD->addOperand(Node);
1042   return DISubprogram(Node);
1043 }
1044 
1045 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
1046 /// given declaration.
CreateSubprogramDefinition(DISubprogram & SPDeclaration)1047 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration){
1048   if (SPDeclaration.isDefinition())
1049     return DISubprogram(SPDeclaration);
1050 
1051   MDNode *DeclNode = SPDeclaration;
1052   Value *Elts[] = {
1053     GetTagConstant(dwarf::DW_TAG_subprogram),
1054     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1055     DeclNode->getOperand(2), // Context
1056     DeclNode->getOperand(3), // Name
1057     DeclNode->getOperand(4), // DisplayName
1058     DeclNode->getOperand(5), // LinkageName
1059     DeclNode->getOperand(6), // CompileUnit
1060     DeclNode->getOperand(7), // LineNo
1061     DeclNode->getOperand(8), // Type
1062     DeclNode->getOperand(9), // isLocalToUnit
1063     ConstantInt::get(Type::getInt1Ty(VMContext), true),
1064     DeclNode->getOperand(11), // Virtuality
1065     DeclNode->getOperand(12), // VIndex
1066     DeclNode->getOperand(13), // Containting Type
1067     DeclNode->getOperand(14), // isArtificial
1068     DeclNode->getOperand(15), // isOptimized
1069     SPDeclaration.getFunction()
1070   };
1071   MDNode *Node =MDNode::get(VMContext, &Elts[0], 16);
1072 
1073   // Create a named metadata so that we do not lose this mdnode.
1074   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1075   NMD->addOperand(Node);
1076   return DISubprogram(Node);
1077 }
1078 
1079 /// CreateGlobalVariable - Create a new descriptor for the specified global.
1080 DIGlobalVariable
CreateGlobalVariable(DIDescriptor Context,StringRef Name,StringRef DisplayName,StringRef LinkageName,DIFile F,unsigned LineNo,DIType Ty,bool isLocalToUnit,bool isDefinition,llvm::GlobalVariable * Val)1081 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1082                                 StringRef DisplayName,
1083                                 StringRef LinkageName,
1084                                 DIFile F,
1085                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1086                                 bool isDefinition, llvm::GlobalVariable *Val) {
1087   Value *Elts[] = {
1088     GetTagConstant(dwarf::DW_TAG_variable),
1089     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1090     Context,
1091     MDString::get(VMContext, Name),
1092     MDString::get(VMContext, DisplayName),
1093     MDString::get(VMContext, LinkageName),
1094     F,
1095     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1096     Ty,
1097     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1098     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1099     Val
1100   };
1101 
1102   Value *const *Vs = &Elts[0];
1103   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1104 
1105   // Create a named metadata so that we do not lose this mdnode.
1106   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1107   NMD->addOperand(Node);
1108 
1109   return DIGlobalVariable(Node);
1110 }
1111 
1112 /// CreateGlobalVariable - Create a new descriptor for the specified constant.
1113 DIGlobalVariable
CreateGlobalVariable(DIDescriptor Context,StringRef Name,StringRef DisplayName,StringRef LinkageName,DIFile F,unsigned LineNo,DIType Ty,bool isLocalToUnit,bool isDefinition,llvm::Constant * Val)1114 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1115                                 StringRef DisplayName,
1116                                 StringRef LinkageName,
1117                                 DIFile F,
1118                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1119                                 bool isDefinition, llvm::Constant *Val) {
1120   Value *Elts[] = {
1121     GetTagConstant(dwarf::DW_TAG_variable),
1122     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1123     Context,
1124     MDString::get(VMContext, Name),
1125     MDString::get(VMContext, DisplayName),
1126     MDString::get(VMContext, LinkageName),
1127     F,
1128     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1129     Ty,
1130     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1131     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1132     Val
1133   };
1134 
1135   Value *const *Vs = &Elts[0];
1136   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1137 
1138   // Create a named metadata so that we do not lose this mdnode.
1139   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1140   NMD->addOperand(Node);
1141 
1142   return DIGlobalVariable(Node);
1143 }
1144 
1145 /// CreateVariable - Create a new descriptor for the specified variable.
CreateVariable(unsigned Tag,DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNo,DIType Ty,bool AlwaysPreserve)1146 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1147                                      StringRef Name,
1148                                      DIFile F,
1149                                      unsigned LineNo,
1150                                      DIType Ty, bool AlwaysPreserve) {
1151   Value *Elts[] = {
1152     GetTagConstant(Tag),
1153     Context,
1154     MDString::get(VMContext, Name),
1155     F,
1156     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1157     Ty,
1158   };
1159   MDNode *Node = MDNode::get(VMContext, &Elts[0], 6);
1160   if (AlwaysPreserve) {
1161     // The optimizer may remove local variable. If there is an interest
1162     // to preserve variable info in such situation then stash it in a
1163     // named mdnode.
1164     DISubprogram Fn(getDISubprogram(Context));
1165     StringRef FName = "fn";
1166     if (Fn.getFunction())
1167       FName = Fn.getFunction()->getName();
1168     char One = '\1';
1169     if (FName.startswith(StringRef(&One, 1)))
1170       FName = FName.substr(1);
1171 
1172     SmallString<32> Out;
1173     NamedMDNode *FnLocals =
1174       M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FName).toStringRef(Out));
1175     FnLocals->addOperand(Node);
1176   }
1177   return DIVariable(Node);
1178 }
1179 
1180 
1181 /// CreateComplexVariable - Create a new descriptor for the specified variable
1182 /// which has a complex address expression for its address.
CreateComplexVariable(unsigned Tag,DIDescriptor Context,const std::string & Name,DIFile F,unsigned LineNo,DIType Ty,SmallVector<Value *,9> & addr)1183 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1184                                             const std::string &Name,
1185                                             DIFile F,
1186                                             unsigned LineNo,
1187                                             DIType Ty,
1188                                             SmallVector<Value *, 9> &addr) {
1189   SmallVector<Value *, 9> Elts;
1190   Elts.push_back(GetTagConstant(Tag));
1191   Elts.push_back(Context);
1192   Elts.push_back(MDString::get(VMContext, Name));
1193   Elts.push_back(F);
1194   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1195   Elts.push_back(Ty);
1196   Elts.insert(Elts.end(), addr.begin(), addr.end());
1197 
1198   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1199 }
1200 
1201 
1202 /// CreateBlock - This creates a descriptor for a lexical block with the
1203 /// specified parent VMContext.
CreateLexicalBlock(DIDescriptor Context,DIFile F,unsigned LineNo,unsigned Col)1204 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1205                                              DIFile F, unsigned LineNo,
1206                                              unsigned Col) {
1207   // Defeat MDNode uniqing for lexical blocks.
1208   static unsigned int unique_id = 0;
1209   Value *Elts[] = {
1210     GetTagConstant(dwarf::DW_TAG_lexical_block),
1211     Context,
1212     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1213     ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1214     F,
1215     ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1216   };
1217   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1218 }
1219 
1220 /// CreateNameSpace - This creates new descriptor for a namespace
1221 /// with the specified parent context.
CreateNameSpace(DIDescriptor Context,StringRef Name,DIFile F,unsigned LineNo)1222 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1223                                        DIFile F,
1224                                        unsigned LineNo) {
1225   Value *Elts[] = {
1226     GetTagConstant(dwarf::DW_TAG_namespace),
1227     Context,
1228     MDString::get(VMContext, Name),
1229     F,
1230     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1231   };
1232   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1233 }
1234 
1235 /// CreateLocation - Creates a debug info location.
CreateLocation(unsigned LineNo,unsigned ColumnNo,DIScope S,DILocation OrigLoc)1236 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1237                                      DIScope S, DILocation OrigLoc) {
1238   Value *Elts[] = {
1239     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1240     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1241     S,
1242     OrigLoc,
1243   };
1244   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1245 }
1246 
1247 //===----------------------------------------------------------------------===//
1248 // DIFactory: Routines for inserting code into a function
1249 //===----------------------------------------------------------------------===//
1250 
1251 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
InsertDeclare(Value * Storage,DIVariable D,Instruction * InsertBefore)1252 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1253                                       Instruction *InsertBefore) {
1254   assert(Storage && "no storage passed to dbg.declare");
1255   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1256   if (!DeclareFn)
1257     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1258 
1259   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1260                     D };
1261   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1262 }
1263 
1264 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
InsertDeclare(Value * Storage,DIVariable D,BasicBlock * InsertAtEnd)1265 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1266                                       BasicBlock *InsertAtEnd) {
1267   assert(Storage && "no storage passed to dbg.declare");
1268   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1269   if (!DeclareFn)
1270     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1271 
1272   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1273                     D };
1274 
1275   // If this block already has a terminator then insert this intrinsic
1276   // before the terminator.
1277   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1278     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1279   else
1280     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1281 
1282 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
InsertDbgValueIntrinsic(Value * V,uint64_t Offset,DIVariable D,Instruction * InsertBefore)1283 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1284                                                 DIVariable D,
1285                                                 Instruction *InsertBefore) {
1286   assert(V && "no value passed to dbg.value");
1287   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1288   if (!ValueFn)
1289     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1290 
1291   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1292                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1293                     D };
1294   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1295 }
1296 
1297 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
InsertDbgValueIntrinsic(Value * V,uint64_t Offset,DIVariable D,BasicBlock * InsertAtEnd)1298 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1299                                                 DIVariable D,
1300                                                 BasicBlock *InsertAtEnd) {
1301   assert(V && "no value passed to dbg.value");
1302   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1303   if (!ValueFn)
1304     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1305 
1306   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1307                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1308                     D };
1309   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1310 }
1311 
1312 //===----------------------------------------------------------------------===//
1313 // DebugInfoFinder implementations.
1314 //===----------------------------------------------------------------------===//
1315 
1316 /// processModule - Process entire module and collect debug info.
processModule(Module & M)1317 void DebugInfoFinder::processModule(Module &M) {
1318   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1319     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1320       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1321            ++BI) {
1322         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1323           processDeclare(DDI);
1324 
1325         DebugLoc Loc = BI->getDebugLoc();
1326         if (Loc.isUnknown())
1327           continue;
1328 
1329         LLVMContext &Ctx = BI->getContext();
1330         DIDescriptor Scope(Loc.getScope(Ctx));
1331 
1332         if (Scope.isCompileUnit())
1333           addCompileUnit(DICompileUnit(Scope));
1334         else if (Scope.isSubprogram())
1335           processSubprogram(DISubprogram(Scope));
1336         else if (Scope.isLexicalBlock())
1337           processLexicalBlock(DILexicalBlock(Scope));
1338 
1339         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1340           processLocation(DILocation(IA));
1341       }
1342 
1343   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1344     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1345       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1346       if (addGlobalVariable(DIG)) {
1347         addCompileUnit(DIG.getCompileUnit());
1348         processType(DIG.getType());
1349       }
1350     }
1351   }
1352 
1353   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1354     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1355       processSubprogram(DISubprogram(NMD->getOperand(i)));
1356 }
1357 
1358 /// processLocation - Process DILocation.
processLocation(DILocation Loc)1359 void DebugInfoFinder::processLocation(DILocation Loc) {
1360   if (!Loc.Verify()) return;
1361   DIDescriptor S(Loc.getScope());
1362   if (S.isCompileUnit())
1363     addCompileUnit(DICompileUnit(S));
1364   else if (S.isSubprogram())
1365     processSubprogram(DISubprogram(S));
1366   else if (S.isLexicalBlock())
1367     processLexicalBlock(DILexicalBlock(S));
1368   processLocation(Loc.getOrigLocation());
1369 }
1370 
1371 /// processType - Process DIType.
processType(DIType DT)1372 void DebugInfoFinder::processType(DIType DT) {
1373   if (!addType(DT))
1374     return;
1375 
1376   addCompileUnit(DT.getCompileUnit());
1377   if (DT.isCompositeType()) {
1378     DICompositeType DCT(DT);
1379     processType(DCT.getTypeDerivedFrom());
1380     DIArray DA = DCT.getTypeArray();
1381     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1382       DIDescriptor D = DA.getElement(i);
1383       if (D.isType())
1384         processType(DIType(D));
1385       else if (D.isSubprogram())
1386         processSubprogram(DISubprogram(D));
1387     }
1388   } else if (DT.isDerivedType()) {
1389     DIDerivedType DDT(DT);
1390     processType(DDT.getTypeDerivedFrom());
1391   }
1392 }
1393 
1394 /// processLexicalBlock
processLexicalBlock(DILexicalBlock LB)1395 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1396   DIScope Context = LB.getContext();
1397   if (Context.isLexicalBlock())
1398     return processLexicalBlock(DILexicalBlock(Context));
1399   else
1400     return processSubprogram(DISubprogram(Context));
1401 }
1402 
1403 /// processSubprogram - Process DISubprogram.
processSubprogram(DISubprogram SP)1404 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1405   if (!addSubprogram(SP))
1406     return;
1407   addCompileUnit(SP.getCompileUnit());
1408   processType(SP.getType());
1409 }
1410 
1411 /// processDeclare - Process DbgDeclareInst.
processDeclare(DbgDeclareInst * DDI)1412 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1413   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1414   if (!N) return;
1415 
1416   DIDescriptor DV(N);
1417   if (!DV.isVariable())
1418     return;
1419 
1420   if (!NodesSeen.insert(DV))
1421     return;
1422 
1423   addCompileUnit(DIVariable(N).getCompileUnit());
1424   processType(DIVariable(N).getType());
1425 }
1426 
1427 /// addType - Add type into Tys.
addType(DIType DT)1428 bool DebugInfoFinder::addType(DIType DT) {
1429   if (!DT.isValid())
1430     return false;
1431 
1432   if (!NodesSeen.insert(DT))
1433     return false;
1434 
1435   TYs.push_back(DT);
1436   return true;
1437 }
1438 
1439 /// addCompileUnit - Add compile unit into CUs.
addCompileUnit(DICompileUnit CU)1440 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1441   if (!CU.Verify())
1442     return false;
1443 
1444   if (!NodesSeen.insert(CU))
1445     return false;
1446 
1447   CUs.push_back(CU);
1448   return true;
1449 }
1450 
1451 /// addGlobalVariable - Add global variable into GVs.
addGlobalVariable(DIGlobalVariable DIG)1452 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1453   if (!DIDescriptor(DIG).isGlobalVariable())
1454     return false;
1455 
1456   if (!NodesSeen.insert(DIG))
1457     return false;
1458 
1459   GVs.push_back(DIG);
1460   return true;
1461 }
1462 
1463 // addSubprogram - Add subprgoram into SPs.
addSubprogram(DISubprogram SP)1464 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1465   if (!DIDescriptor(SP).isSubprogram())
1466     return false;
1467 
1468   if (!NodesSeen.insert(SP))
1469     return false;
1470 
1471   SPs.push_back(SP);
1472   return true;
1473 }
1474 
1475 /// Find the debug info descriptor corresponding to this global variable.
findDbgGlobalDeclare(GlobalVariable * V)1476 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1477   const Module *M = V->getParent();
1478   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1479   if (!NMD)
1480     return 0;
1481 
1482   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1483     DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
1484     if (!DIG.isGlobalVariable())
1485       continue;
1486     if (DIGlobalVariable(DIG).getGlobal() == V)
1487       return DIG;
1488   }
1489   return 0;
1490 }
1491 
1492 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1493 /// It looks through pointer casts too.
findDbgDeclare(const Value * V)1494 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1495   V = V->stripPointerCasts();
1496 
1497   if (!isa<Instruction>(V) && !isa<Argument>(V))
1498     return 0;
1499 
1500   const Function *F = NULL;
1501   if (const Instruction *I = dyn_cast<Instruction>(V))
1502     F = I->getParent()->getParent();
1503   else if (const Argument *A = dyn_cast<Argument>(V))
1504     F = A->getParent();
1505 
1506   for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1507     for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1508          BI != BE; ++BI)
1509       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1510         if (DDI->getAddress() == V)
1511           return DDI;
1512 
1513   return 0;
1514 }
1515 
getLocationInfo(const Value * V,std::string & DisplayName,std::string & Type,unsigned & LineNo,std::string & File,std::string & Dir)1516 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1517                            std::string &Type, unsigned &LineNo,
1518                            std::string &File, std::string &Dir) {
1519   DICompileUnit Unit;
1520   DIType TypeD;
1521 
1522   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1523     Value *DIGV = findDbgGlobalDeclare(GV);
1524     if (!DIGV) return false;
1525     DIGlobalVariable Var(cast<MDNode>(DIGV));
1526 
1527     StringRef D = Var.getDisplayName();
1528     if (!D.empty())
1529       DisplayName = D;
1530     LineNo = Var.getLineNumber();
1531     Unit = Var.getCompileUnit();
1532     TypeD = Var.getType();
1533   } else {
1534     const DbgDeclareInst *DDI = findDbgDeclare(V);
1535     if (!DDI) return false;
1536     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1537 
1538     StringRef D = Var.getName();
1539     if (!D.empty())
1540       DisplayName = D;
1541     LineNo = Var.getLineNumber();
1542     Unit = Var.getCompileUnit();
1543     TypeD = Var.getType();
1544   }
1545 
1546   StringRef T = TypeD.getName();
1547   if (!T.empty())
1548     Type = T;
1549   StringRef F = Unit.getFilename();
1550   if (!F.empty())
1551     File = F;
1552   StringRef D = Unit.getDirectory();
1553   if (!D.empty())
1554     Dir = D;
1555   return true;
1556 }
1557 
1558 /// getDISubprogram - Find subprogram that is enclosing this scope.
getDISubprogram(const MDNode * Scope)1559 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1560   DIDescriptor D(Scope);
1561   if (D.isSubprogram())
1562     return DISubprogram(Scope);
1563 
1564   if (D.isLexicalBlock())
1565     return getDISubprogram(DILexicalBlock(Scope).getContext());
1566 
1567   return DISubprogram();
1568 }
1569 
1570 /// getDICompositeType - Find underlying composite type.
getDICompositeType(DIType T)1571 DICompositeType llvm::getDICompositeType(DIType T) {
1572   if (T.isCompositeType())
1573     return DICompositeType(T);
1574 
1575   if (T.isDerivedType())
1576     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1577 
1578   return DICompositeType();
1579 }
1580