LLVM API Documentation

DebugInfo.cpp
Go to the documentation of this file.
00001 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the helper classes used to build and interpret debug
00011 // information in LLVM IR form.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/IR/DebugInfo.h"
00016 #include "LLVMContextImpl.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/Analysis/ValueTracking.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/Instructions.h"
00024 #include "llvm/IR/IntrinsicInst.h"
00025 #include "llvm/IR/Intrinsics.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/Dwarf.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 using namespace llvm;
00032 using namespace llvm::dwarf;
00033 
00034 //===----------------------------------------------------------------------===//
00035 // DIDescriptor
00036 //===----------------------------------------------------------------------===//
00037 
00038 bool DIDescriptor::Verify() const {
00039   return DbgNode &&
00040          (DIDerivedType(DbgNode).Verify() ||
00041           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
00042           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
00043           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
00044           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
00045           DILexicalBlock(DbgNode).Verify() ||
00046           DILexicalBlockFile(DbgNode).Verify() ||
00047           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
00048           DIObjCProperty(DbgNode).Verify() ||
00049           DITemplateTypeParameter(DbgNode).Verify() ||
00050           DITemplateValueParameter(DbgNode).Verify() ||
00051           DIImportedEntity(DbgNode).Verify());
00052 }
00053 
00054 static Value *getField(const MDNode *DbgNode, unsigned Elt) {
00055   if (!DbgNode || Elt >= DbgNode->getNumOperands())
00056     return nullptr;
00057   return DbgNode->getOperand(Elt);
00058 }
00059 
00060 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
00061   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
00062 }
00063 
00064 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
00065   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
00066     return MDS->getString();
00067   return StringRef();
00068 }
00069 
00070 StringRef DIDescriptor::getStringField(unsigned Elt) const {
00071   return ::getStringField(DbgNode, Elt);
00072 }
00073 
00074 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
00075   if (!DbgNode)
00076     return 0;
00077 
00078   if (Elt < DbgNode->getNumOperands())
00079     if (ConstantInt *CI =
00080             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
00081       return CI->getZExtValue();
00082 
00083   return 0;
00084 }
00085 
00086 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
00087   if (!DbgNode)
00088     return 0;
00089 
00090   if (Elt < DbgNode->getNumOperands())
00091     if (ConstantInt *CI =
00092             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
00093       return CI->getSExtValue();
00094 
00095   return 0;
00096 }
00097 
00098 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
00099   MDNode *Field = getNodeField(DbgNode, Elt);
00100   return DIDescriptor(Field);
00101 }
00102 
00103 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
00104   if (!DbgNode)
00105     return nullptr;
00106 
00107   if (Elt < DbgNode->getNumOperands())
00108     return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
00109   return nullptr;
00110 }
00111 
00112 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
00113   if (!DbgNode)
00114     return nullptr;
00115 
00116   if (Elt < DbgNode->getNumOperands())
00117     return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
00118   return nullptr;
00119 }
00120 
00121 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
00122   if (!DbgNode)
00123     return nullptr;
00124 
00125   if (Elt < DbgNode->getNumOperands())
00126     return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
00127   return nullptr;
00128 }
00129 
00130 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
00131   if (!DbgNode)
00132     return;
00133 
00134   if (Elt < DbgNode->getNumOperands()) {
00135     MDNode *Node = const_cast<MDNode *>(DbgNode);
00136     Node->replaceOperandWith(Elt, F);
00137   }
00138 }
00139 
00140 uint64_t DIVariable::getAddrElement(unsigned Idx) const {
00141   DIDescriptor ComplexExpr = getDescriptorField(8);
00142   if (Idx < ComplexExpr->getNumOperands())
00143     if (auto *CI = dyn_cast_or_null<ConstantInt>(ComplexExpr->getOperand(Idx)))
00144       return CI->getZExtValue();
00145 
00146   assert(false && "non-existing complex address element requested");
00147   return 0;
00148 }
00149 
00150 /// getInlinedAt - If this variable is inlined then return inline location.
00151 MDNode *DIVariable::getInlinedAt() const { return getNodeField(DbgNode, 7); }
00152 
00153 //===----------------------------------------------------------------------===//
00154 // Predicates
00155 //===----------------------------------------------------------------------===//
00156 
00157 bool DIDescriptor::isSubroutineType() const {
00158   return isCompositeType() && getTag() == dwarf::DW_TAG_subroutine_type;
00159 }
00160 
00161 /// isBasicType - Return true if the specified tag is legal for
00162 /// DIBasicType.
00163 bool DIDescriptor::isBasicType() const {
00164   if (!DbgNode)
00165     return false;
00166   switch (getTag()) {
00167   case dwarf::DW_TAG_base_type:
00168   case dwarf::DW_TAG_unspecified_type:
00169     return true;
00170   default:
00171     return false;
00172   }
00173 }
00174 
00175 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
00176 bool DIDescriptor::isDerivedType() const {
00177   if (!DbgNode)
00178     return false;
00179   switch (getTag()) {
00180   case dwarf::DW_TAG_typedef:
00181   case dwarf::DW_TAG_pointer_type:
00182   case dwarf::DW_TAG_ptr_to_member_type:
00183   case dwarf::DW_TAG_reference_type:
00184   case dwarf::DW_TAG_rvalue_reference_type:
00185   case dwarf::DW_TAG_const_type:
00186   case dwarf::DW_TAG_volatile_type:
00187   case dwarf::DW_TAG_restrict_type:
00188   case dwarf::DW_TAG_member:
00189   case dwarf::DW_TAG_inheritance:
00190   case dwarf::DW_TAG_friend:
00191     return true;
00192   default:
00193     // CompositeTypes are currently modelled as DerivedTypes.
00194     return isCompositeType();
00195   }
00196 }
00197 
00198 /// isCompositeType - Return true if the specified tag is legal for
00199 /// DICompositeType.
00200 bool DIDescriptor::isCompositeType() const {
00201   if (!DbgNode)
00202     return false;
00203   switch (getTag()) {
00204   case dwarf::DW_TAG_array_type:
00205   case dwarf::DW_TAG_structure_type:
00206   case dwarf::DW_TAG_union_type:
00207   case dwarf::DW_TAG_enumeration_type:
00208   case dwarf::DW_TAG_subroutine_type:
00209   case dwarf::DW_TAG_class_type:
00210     return true;
00211   default:
00212     return false;
00213   }
00214 }
00215 
00216 /// isVariable - Return true if the specified tag is legal for DIVariable.
00217 bool DIDescriptor::isVariable() const {
00218   if (!DbgNode)
00219     return false;
00220   switch (getTag()) {
00221   case dwarf::DW_TAG_auto_variable:
00222   case dwarf::DW_TAG_arg_variable:
00223     return true;
00224   default:
00225     return false;
00226   }
00227 }
00228 
00229 /// isType - Return true if the specified tag is legal for DIType.
00230 bool DIDescriptor::isType() const {
00231   return isBasicType() || isCompositeType() || isDerivedType();
00232 }
00233 
00234 /// isSubprogram - Return true if the specified tag is legal for
00235 /// DISubprogram.
00236 bool DIDescriptor::isSubprogram() const {
00237   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
00238 }
00239 
00240 /// isGlobalVariable - Return true if the specified tag is legal for
00241 /// DIGlobalVariable.
00242 bool DIDescriptor::isGlobalVariable() const {
00243   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
00244                      getTag() == dwarf::DW_TAG_constant);
00245 }
00246 
00247 /// isScope - Return true if the specified tag is one of the scope
00248 /// related tag.
00249 bool DIDescriptor::isScope() const {
00250   if (!DbgNode)
00251     return false;
00252   switch (getTag()) {
00253   case dwarf::DW_TAG_compile_unit:
00254   case dwarf::DW_TAG_lexical_block:
00255   case dwarf::DW_TAG_subprogram:
00256   case dwarf::DW_TAG_namespace:
00257   case dwarf::DW_TAG_file_type:
00258     return true;
00259   default:
00260     break;
00261   }
00262   return isType();
00263 }
00264 
00265 /// isTemplateTypeParameter - Return true if the specified tag is
00266 /// DW_TAG_template_type_parameter.
00267 bool DIDescriptor::isTemplateTypeParameter() const {
00268   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
00269 }
00270 
00271 /// isTemplateValueParameter - Return true if the specified tag is
00272 /// DW_TAG_template_value_parameter.
00273 bool DIDescriptor::isTemplateValueParameter() const {
00274   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
00275                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
00276                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
00277 }
00278 
00279 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
00280 bool DIDescriptor::isCompileUnit() const {
00281   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
00282 }
00283 
00284 /// isFile - Return true if the specified tag is DW_TAG_file_type.
00285 bool DIDescriptor::isFile() const {
00286   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
00287 }
00288 
00289 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
00290 bool DIDescriptor::isNameSpace() const {
00291   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
00292 }
00293 
00294 /// isLexicalBlockFile - Return true if the specified descriptor is a
00295 /// lexical block with an extra file.
00296 bool DIDescriptor::isLexicalBlockFile() const {
00297   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
00298          (DbgNode->getNumOperands() == 3);
00299 }
00300 
00301 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
00302 bool DIDescriptor::isLexicalBlock() const {
00303   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
00304          (DbgNode->getNumOperands() > 3);
00305 }
00306 
00307 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
00308 bool DIDescriptor::isSubrange() const {
00309   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
00310 }
00311 
00312 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
00313 bool DIDescriptor::isEnumerator() const {
00314   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
00315 }
00316 
00317 /// isObjCProperty - Return true if the specified tag is DW_TAG_APPLE_property.
00318 bool DIDescriptor::isObjCProperty() const {
00319   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
00320 }
00321 
00322 /// \brief Return true if the specified tag is DW_TAG_imported_module or
00323 /// DW_TAG_imported_declaration.
00324 bool DIDescriptor::isImportedEntity() const {
00325   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
00326                      getTag() == dwarf::DW_TAG_imported_declaration);
00327 }
00328 
00329 //===----------------------------------------------------------------------===//
00330 // Simple Descriptor Constructors and other Methods
00331 //===----------------------------------------------------------------------===//
00332 
00333 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
00334 /// type with the one in the passed descriptor.
00335 void DIType::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
00336 
00337   assert(DbgNode && "Trying to replace an unverified type!");
00338 
00339   // Since we use a TrackingVH for the node, its easy for clients to manufacture
00340   // legitimate situations where they want to replaceAllUsesWith() on something
00341   // which, due to uniquing, has merged with the source. We shield clients from
00342   // this detail by allowing a value to be replaced with replaceAllUsesWith()
00343   // itself.
00344   const MDNode *DN = D;
00345   if (DbgNode == DN) {
00346     SmallVector<Value*, 10> Ops(DbgNode->getNumOperands());
00347     for (size_t i = 0; i != Ops.size(); ++i)
00348       Ops[i] = DbgNode->getOperand(i);
00349     DN = MDNode::get(VMContext, Ops);
00350   }
00351 
00352   MDNode *Node = const_cast<MDNode *>(DbgNode);
00353   const Value *V = cast_or_null<Value>(DN);
00354   Node->replaceAllUsesWith(const_cast<Value *>(V));
00355   MDNode::deleteTemporary(Node);
00356   DbgNode = D;
00357 }
00358 
00359 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
00360 /// type with the one in D.
00361 void DIType::replaceAllUsesWith(MDNode *D) {
00362 
00363   assert(DbgNode && "Trying to replace an unverified type!");
00364   assert(DbgNode != D && "This replacement should always happen");
00365   MDNode *Node = const_cast<MDNode *>(DbgNode);
00366   const MDNode *DN = D;
00367   const Value *V = cast_or_null<Value>(DN);
00368   Node->replaceAllUsesWith(const_cast<Value *>(V));
00369   MDNode::deleteTemporary(Node);
00370 }
00371 
00372 /// Verify - Verify that a compile unit is well formed.
00373 bool DICompileUnit::Verify() const {
00374   if (!isCompileUnit())
00375     return false;
00376 
00377   // Don't bother verifying the compilation directory or producer string
00378   // as those could be empty.
00379   if (getFilename().empty())
00380     return false;
00381 
00382   return DbgNode->getNumOperands() == 14;
00383 }
00384 
00385 /// Verify - Verify that an ObjC property is well formed.
00386 bool DIObjCProperty::Verify() const {
00387   if (!isObjCProperty())
00388     return false;
00389 
00390   // Don't worry about the rest of the strings for now.
00391   return DbgNode->getNumOperands() == 8;
00392 }
00393 
00394 /// Check if a field at position Elt of a MDNode is a MDNode.
00395 /// We currently allow an empty string and an integer.
00396 /// But we don't allow a non-empty string in a MDNode field.
00397 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
00398   // FIXME: This function should return true, if the field is null or the field
00399   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
00400   Value *Fld = getField(DbgNode, Elt);
00401   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
00402     return false;
00403   return true;
00404 }
00405 
00406 /// Check if a field at position Elt of a MDNode is a MDString.
00407 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
00408   Value *Fld = getField(DbgNode, Elt);
00409   return !Fld || isa<MDString>(Fld);
00410 }
00411 
00412 /// Check if a value can be a reference to a type.
00413 static bool isTypeRef(const Value *Val) {
00414   return !Val ||
00415          (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
00416          (isa<MDNode>(Val) && DIType(cast<MDNode>(Val)).isType());
00417 }
00418 
00419 /// Check if a field at position Elt of a MDNode can be a reference to a type.
00420 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
00421   Value *Fld = getField(DbgNode, Elt);
00422   return isTypeRef(Fld);
00423 }
00424 
00425 /// Check if a value can be a ScopeRef.
00426 static bool isScopeRef(const Value *Val) {
00427   return !Val ||
00428     (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
00429     // Not checking for Val->isScope() here, because it would work
00430     // only for lexical scopes and not all subclasses of DIScope.
00431     isa<MDNode>(Val);
00432 }
00433 
00434 /// Check if a field at position Elt of a MDNode can be a ScopeRef.
00435 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
00436   Value *Fld = getField(DbgNode, Elt);
00437   return isScopeRef(Fld);
00438 }
00439 
00440 /// Verify - Verify that a type descriptor is well formed.
00441 bool DIType::Verify() const {
00442   if (!isType())
00443     return false;
00444   // Make sure Context @ field 2 is MDNode.
00445   if (!fieldIsScopeRef(DbgNode, 2))
00446     return false;
00447 
00448   // FIXME: Sink this into the various subclass verifies.
00449   uint16_t Tag = getTag();
00450   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
00451       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
00452       Tag != dwarf::DW_TAG_ptr_to_member_type &&
00453       Tag != dwarf::DW_TAG_reference_type &&
00454       Tag != dwarf::DW_TAG_rvalue_reference_type &&
00455       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
00456       Tag != dwarf::DW_TAG_enumeration_type &&
00457       Tag != dwarf::DW_TAG_subroutine_type &&
00458       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
00459       getFilename().empty())
00460     return false;
00461   // DIType is abstract, it should be a BasicType, a DerivedType or
00462   // a CompositeType.
00463   if (isBasicType())
00464     return DIBasicType(DbgNode).Verify();
00465   else if (isCompositeType())
00466     return DICompositeType(DbgNode).Verify();
00467   else if (isDerivedType())
00468     return DIDerivedType(DbgNode).Verify();
00469   else
00470     return false;
00471 }
00472 
00473 /// Verify - Verify that a basic type descriptor is well formed.
00474 bool DIBasicType::Verify() const {
00475   return isBasicType() && DbgNode->getNumOperands() == 10;
00476 }
00477 
00478 /// Verify - Verify that a derived type descriptor is well formed.
00479 bool DIDerivedType::Verify() const {
00480   // Make sure DerivedFrom @ field 9 is TypeRef.
00481   if (!fieldIsTypeRef(DbgNode, 9))
00482     return false;
00483   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
00484     // Make sure ClassType @ field 10 is a TypeRef.
00485     if (!fieldIsTypeRef(DbgNode, 10))
00486       return false;
00487 
00488   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
00489          DbgNode->getNumOperands() <= 14;
00490 }
00491 
00492 /// Verify - Verify that a composite type descriptor is well formed.
00493 bool DICompositeType::Verify() const {
00494   if (!isCompositeType())
00495     return false;
00496 
00497   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are TypeRef.
00498   if (!fieldIsTypeRef(DbgNode, 9))
00499     return false;
00500   if (!fieldIsTypeRef(DbgNode, 12))
00501     return false;
00502 
00503   // Make sure the type identifier at field 14 is MDString, it can be null.
00504   if (!fieldIsMDString(DbgNode, 14))
00505     return false;
00506 
00507   // A subroutine type can't be both & and &&.
00508   if (isLValueReference() && isRValueReference())
00509     return false;
00510 
00511   return DbgNode->getNumOperands() == 15;
00512 }
00513 
00514 /// Verify - Verify that a subprogram descriptor is well formed.
00515 bool DISubprogram::Verify() const {
00516   if (!isSubprogram())
00517     return false;
00518 
00519   // Make sure context @ field 2 is a ScopeRef and type @ field 7 is a MDNode.
00520   if (!fieldIsScopeRef(DbgNode, 2))
00521     return false;
00522   if (!fieldIsMDNode(DbgNode, 7))
00523     return false;
00524   // Containing type @ field 12.
00525   if (!fieldIsTypeRef(DbgNode, 12))
00526     return false;
00527 
00528   // A subprogram can't be both & and &&.
00529   if (isLValueReference() && isRValueReference())
00530     return false;
00531 
00532   return DbgNode->getNumOperands() == 20;
00533 }
00534 
00535 /// Verify - Verify that a global variable descriptor is well formed.
00536 bool DIGlobalVariable::Verify() const {
00537   if (!isGlobalVariable())
00538     return false;
00539 
00540   if (getDisplayName().empty())
00541     return false;
00542   // Make sure context @ field 2 is an MDNode.
00543   if (!fieldIsMDNode(DbgNode, 2))
00544     return false;
00545   // Make sure that type @ field 8 is a DITypeRef.
00546   if (!fieldIsTypeRef(DbgNode, 8))
00547     return false;
00548   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
00549   if (!fieldIsMDNode(DbgNode, 12))
00550     return false;
00551 
00552   return DbgNode->getNumOperands() == 13;
00553 }
00554 
00555 /// Verify - Verify that a variable descriptor is well formed.
00556 bool DIVariable::Verify() const {
00557   if (!isVariable())
00558     return false;
00559 
00560   // Make sure context @ field 1 is an MDNode.
00561   if (!fieldIsMDNode(DbgNode, 1))
00562     return false;
00563   // Make sure that type @ field 5 is a DITypeRef.
00564   if (!fieldIsTypeRef(DbgNode, 5))
00565     return false;
00566 
00567   // Variable without a complex expression.
00568   if (DbgNode->getNumOperands() == 8)
00569     return true;
00570 
00571   // Make sure the complex expression is an MDNode.
00572   return (DbgNode->getNumOperands() == 9 && fieldIsMDNode(DbgNode, 8));
00573 }
00574 
00575 /// Verify - Verify that a location descriptor is well formed.
00576 bool DILocation::Verify() const {
00577   if (!DbgNode)
00578     return false;
00579 
00580   return DbgNode->getNumOperands() == 4;
00581 }
00582 
00583 /// Verify - Verify that a namespace descriptor is well formed.
00584 bool DINameSpace::Verify() const {
00585   if (!isNameSpace())
00586     return false;
00587   return DbgNode->getNumOperands() == 5;
00588 }
00589 
00590 /// \brief Retrieve the MDNode for the directory/file pair.
00591 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
00592 
00593 /// \brief Verify that the file descriptor is well formed.
00594 bool DIFile::Verify() const {
00595   return isFile() && DbgNode->getNumOperands() == 2;
00596 }
00597 
00598 /// \brief Verify that the enumerator descriptor is well formed.
00599 bool DIEnumerator::Verify() const {
00600   return isEnumerator() && DbgNode->getNumOperands() == 3;
00601 }
00602 
00603 /// \brief Verify that the subrange descriptor is well formed.
00604 bool DISubrange::Verify() const {
00605   return isSubrange() && DbgNode->getNumOperands() == 3;
00606 }
00607 
00608 /// \brief Verify that the lexical block descriptor is well formed.
00609 bool DILexicalBlock::Verify() const {
00610   return isLexicalBlock() && DbgNode->getNumOperands() == 7;
00611 }
00612 
00613 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
00614 bool DILexicalBlockFile::Verify() const {
00615   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3;
00616 }
00617 
00618 /// \brief Verify that the template type parameter descriptor is well formed.
00619 bool DITemplateTypeParameter::Verify() const {
00620   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
00621 }
00622 
00623 /// \brief Verify that the template value parameter descriptor is well formed.
00624 bool DITemplateValueParameter::Verify() const {
00625   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
00626 }
00627 
00628 /// \brief Verify that the imported module descriptor is well formed.
00629 bool DIImportedEntity::Verify() const {
00630   return isImportedEntity() &&
00631          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
00632 }
00633 
00634 /// getObjCProperty - Return property node, if this ivar is associated with one.
00635 MDNode *DIDerivedType::getObjCProperty() const {
00636   return getNodeField(DbgNode, 10);
00637 }
00638 
00639 MDString *DICompositeType::getIdentifier() const {
00640   return cast_or_null<MDString>(getField(DbgNode, 14));
00641 }
00642 
00643 #ifndef NDEBUG
00644 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
00645   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
00646     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
00647     if (i == 0 && isa<ConstantInt>(LHS->getOperand(i)))
00648       continue;
00649     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
00650     bool found = false;
00651     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
00652       found = E == RHS->getOperand(j);
00653     assert(found && "Losing a member during member list replacement");
00654   }
00655 }
00656 #endif
00657 
00658 /// \brief Set the array of member DITypes.
00659 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
00660   TrackingVH<MDNode> N(*this);
00661   if (Elements) {
00662 #ifndef NDEBUG
00663     // Check that the new list of members contains all the old members as well.
00664     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(10)))
00665       VerifySubsetOf(El, Elements);
00666 #endif
00667     N->replaceOperandWith(10, Elements);
00668   }
00669   if (TParams)
00670     N->replaceOperandWith(13, TParams);
00671   DbgNode = N;
00672 }
00673 
00674 /// Generate a reference to this DIType. Uses the type identifier instead
00675 /// of the actual MDNode if possible, to help type uniquing.
00676 DIScopeRef DIScope::getRef() const {
00677   if (!isCompositeType())
00678     return DIScopeRef(*this);
00679   DICompositeType DTy(DbgNode);
00680   if (!DTy.getIdentifier())
00681     return DIScopeRef(*this);
00682   return DIScopeRef(DTy.getIdentifier());
00683 }
00684 
00685 /// \brief Set the containing type.
00686 void DICompositeType::setContainingType(DICompositeType ContainingType) {
00687   TrackingVH<MDNode> N(*this);
00688   N->replaceOperandWith(12, ContainingType.getRef());
00689   DbgNode = N;
00690 }
00691 
00692 /// isInlinedFnArgument - Return true if this variable provides debugging
00693 /// information for an inlined function arguments.
00694 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
00695   assert(CurFn && "Invalid function");
00696   if (!getContext().isSubprogram())
00697     return false;
00698   // This variable is not inlined function argument if its scope
00699   // does not describe current function.
00700   return !DISubprogram(getContext()).describes(CurFn);
00701 }
00702 
00703 /// describes - Return true if this subprogram provides debugging
00704 /// information for the function F.
00705 bool DISubprogram::describes(const Function *F) {
00706   assert(F && "Invalid function");
00707   if (F == getFunction())
00708     return true;
00709   StringRef Name = getLinkageName();
00710   if (Name.empty())
00711     Name = getName();
00712   if (F->getName() == Name)
00713     return true;
00714   return false;
00715 }
00716 
00717 unsigned DISubprogram::isOptimized() const {
00718   assert(DbgNode && "Invalid subprogram descriptor!");
00719   if (DbgNode->getNumOperands() == 15)
00720     return getUnsignedField(14);
00721   return 0;
00722 }
00723 
00724 MDNode *DISubprogram::getVariablesNodes() const {
00725   return getNodeField(DbgNode, 18);
00726 }
00727 
00728 DIArray DISubprogram::getVariables() const {
00729   return DIArray(getNodeField(DbgNode, 18));
00730 }
00731 
00732 Value *DITemplateValueParameter::getValue() const {
00733   return getField(DbgNode, 4);
00734 }
00735 
00736 // If the current node has a parent scope then return that,
00737 // else return an empty scope.
00738 DIScopeRef DIScope::getContext() const {
00739 
00740   if (isType())
00741     return DIType(DbgNode).getContext();
00742 
00743   if (isSubprogram())
00744     return DIScopeRef(DISubprogram(DbgNode).getContext());
00745 
00746   if (isLexicalBlock())
00747     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
00748 
00749   if (isLexicalBlockFile())
00750     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
00751 
00752   if (isNameSpace())
00753     return DIScopeRef(DINameSpace(DbgNode).getContext());
00754 
00755   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
00756   return DIScopeRef(nullptr);
00757 }
00758 
00759 // If the scope node has a name, return that, else return an empty string.
00760 StringRef DIScope::getName() const {
00761   if (isType())
00762     return DIType(DbgNode).getName();
00763   if (isSubprogram())
00764     return DISubprogram(DbgNode).getName();
00765   if (isNameSpace())
00766     return DINameSpace(DbgNode).getName();
00767   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
00768           isCompileUnit()) &&
00769          "Unhandled type of scope.");
00770   return StringRef();
00771 }
00772 
00773 StringRef DIScope::getFilename() const {
00774   if (!DbgNode)
00775     return StringRef();
00776   return ::getStringField(getNodeField(DbgNode, 1), 0);
00777 }
00778 
00779 StringRef DIScope::getDirectory() const {
00780   if (!DbgNode)
00781     return StringRef();
00782   return ::getStringField(getNodeField(DbgNode, 1), 1);
00783 }
00784 
00785 DIArray DICompileUnit::getEnumTypes() const {
00786   if (!DbgNode || DbgNode->getNumOperands() < 13)
00787     return DIArray();
00788 
00789   return DIArray(getNodeField(DbgNode, 7));
00790 }
00791 
00792 DIArray DICompileUnit::getRetainedTypes() const {
00793   if (!DbgNode || DbgNode->getNumOperands() < 13)
00794     return DIArray();
00795 
00796   return DIArray(getNodeField(DbgNode, 8));
00797 }
00798 
00799 DIArray DICompileUnit::getSubprograms() const {
00800   if (!DbgNode || DbgNode->getNumOperands() < 13)
00801     return DIArray();
00802 
00803   return DIArray(getNodeField(DbgNode, 9));
00804 }
00805 
00806 DIArray DICompileUnit::getGlobalVariables() const {
00807   if (!DbgNode || DbgNode->getNumOperands() < 13)
00808     return DIArray();
00809 
00810   return DIArray(getNodeField(DbgNode, 10));
00811 }
00812 
00813 DIArray DICompileUnit::getImportedEntities() const {
00814   if (!DbgNode || DbgNode->getNumOperands() < 13)
00815     return DIArray();
00816 
00817   return DIArray(getNodeField(DbgNode, 11));
00818 }
00819 
00820 /// copyWithNewScope - Return a copy of this location, replacing the
00821 /// current scope with the given one.
00822 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
00823                                         DILexicalBlock NewScope) {
00824   SmallVector<Value *, 10> Elts;
00825   assert(Verify());
00826   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
00827     if (I != 2)
00828       Elts.push_back(DbgNode->getOperand(I));
00829     else
00830       Elts.push_back(NewScope);
00831   }
00832   MDNode *NewDIL = MDNode::get(Ctx, Elts);
00833   return DILocation(NewDIL);
00834 }
00835 
00836 /// computeNewDiscriminator - Generate a new discriminator value for this
00837 /// file and line location.
00838 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
00839   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
00840   return ++Ctx.pImpl->DiscriminatorTable[Key];
00841 }
00842 
00843 /// fixupSubprogramName - Replace contains special characters used
00844 /// in a typical Objective-C names with '.' in a given string.
00845 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
00846   StringRef FName =
00847       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
00848   FName = Function::getRealLinkageName(FName);
00849 
00850   StringRef Prefix("llvm.dbg.lv.");
00851   Out.reserve(FName.size() + Prefix.size());
00852   Out.append(Prefix.begin(), Prefix.end());
00853 
00854   bool isObjCLike = false;
00855   for (size_t i = 0, e = FName.size(); i < e; ++i) {
00856     char C = FName[i];
00857     if (C == '[')
00858       isObjCLike = true;
00859 
00860     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
00861                        C == '+' || C == '(' || C == ')'))
00862       Out.push_back('.');
00863     else
00864       Out.push_back(C);
00865   }
00866 }
00867 
00868 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
00869 /// suitable to hold function specific information.
00870 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
00871   SmallString<32> Name;
00872   fixupSubprogramName(Fn, Name);
00873   return M.getNamedMetadata(Name.str());
00874 }
00875 
00876 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
00877 /// to hold function specific information.
00878 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
00879   SmallString<32> Name;
00880   fixupSubprogramName(Fn, Name);
00881   return M.getOrInsertNamedMetadata(Name.str());
00882 }
00883 
00884 /// createInlinedVariable - Create a new inlined variable based on current
00885 /// variable.
00886 /// @param DV            Current Variable.
00887 /// @param InlinedScope  Location at current variable is inlined.
00888 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
00889                                        LLVMContext &VMContext) {
00890   SmallVector<Value *, 16> Elts;
00891   // Insert inlined scope as 7th element.
00892   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
00893     i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i));
00894   return DIVariable(MDNode::get(VMContext, Elts));
00895 }
00896 
00897 /// cleanseInlinedVariable - Remove inlined scope from the variable.
00898 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
00899   SmallVector<Value *, 16> Elts;
00900   // Insert inlined scope as 7th element.
00901   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
00902     i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)))
00903            : Elts.push_back(DV->getOperand(i));
00904   return DIVariable(MDNode::get(VMContext, Elts));
00905 }
00906 
00907 /// getDISubprogram - Find subprogram that is enclosing this scope.
00908 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
00909   DIDescriptor D(Scope);
00910   if (D.isSubprogram())
00911     return DISubprogram(Scope);
00912 
00913   if (D.isLexicalBlockFile())
00914     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
00915 
00916   if (D.isLexicalBlock())
00917     return getDISubprogram(DILexicalBlock(Scope).getContext());
00918 
00919   return DISubprogram();
00920 }
00921 
00922 /// getDICompositeType - Find underlying composite type.
00923 DICompositeType llvm::getDICompositeType(DIType T) {
00924   if (T.isCompositeType())
00925     return DICompositeType(T);
00926 
00927   if (T.isDerivedType()) {
00928     // This function is currently used by dragonegg and dragonegg does
00929     // not generate identifier for types, so using an empty map to resolve
00930     // DerivedFrom should be fine.
00931     DITypeIdentifierMap EmptyMap;
00932     return getDICompositeType(
00933         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
00934   }
00935 
00936   return DICompositeType();
00937 }
00938 
00939 /// Update DITypeIdentifierMap by going through retained types of each CU.
00940 DITypeIdentifierMap
00941 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
00942   DITypeIdentifierMap Map;
00943   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
00944     DICompileUnit CU(CU_Nodes->getOperand(CUi));
00945     DIArray Retain = CU.getRetainedTypes();
00946     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
00947       if (!Retain.getElement(Ti).isCompositeType())
00948         continue;
00949       DICompositeType Ty(Retain.getElement(Ti));
00950       if (MDString *TypeId = Ty.getIdentifier()) {
00951         // Definition has priority over declaration.
00952         // Try to insert (TypeId, Ty) to Map.
00953         std::pair<DITypeIdentifierMap::iterator, bool> P =
00954             Map.insert(std::make_pair(TypeId, Ty));
00955         // If TypeId already exists in Map and this is a definition, replace
00956         // whatever we had (declaration or definition) with the definition.
00957         if (!P.second && !Ty.isForwardDecl())
00958           P.first->second = Ty;
00959       }
00960     }
00961   }
00962   return Map;
00963 }
00964 
00965 //===----------------------------------------------------------------------===//
00966 // DebugInfoFinder implementations.
00967 //===----------------------------------------------------------------------===//
00968 
00969 void DebugInfoFinder::reset() {
00970   CUs.clear();
00971   SPs.clear();
00972   GVs.clear();
00973   TYs.clear();
00974   Scopes.clear();
00975   NodesSeen.clear();
00976   TypeIdentifierMap.clear();
00977   TypeMapInitialized = false;
00978 }
00979 
00980 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
00981   if (!TypeMapInitialized)
00982     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00983       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
00984       TypeMapInitialized = true;
00985     }
00986 }
00987 
00988 /// processModule - Process entire module and collect debug info.
00989 void DebugInfoFinder::processModule(const Module &M) {
00990   InitializeTypeMap(M);
00991   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00992     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
00993       DICompileUnit CU(CU_Nodes->getOperand(i));
00994       addCompileUnit(CU);
00995       DIArray GVs = CU.getGlobalVariables();
00996       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
00997         DIGlobalVariable DIG(GVs.getElement(i));
00998         if (addGlobalVariable(DIG)) {
00999           processScope(DIG.getContext());
01000           processType(DIG.getType().resolve(TypeIdentifierMap));
01001         }
01002       }
01003       DIArray SPs = CU.getSubprograms();
01004       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
01005         processSubprogram(DISubprogram(SPs.getElement(i)));
01006       DIArray EnumTypes = CU.getEnumTypes();
01007       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
01008         processType(DIType(EnumTypes.getElement(i)));
01009       DIArray RetainedTypes = CU.getRetainedTypes();
01010       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
01011         processType(DIType(RetainedTypes.getElement(i)));
01012       DIArray Imports = CU.getImportedEntities();
01013       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
01014         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
01015         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
01016         if (Entity.isType())
01017           processType(DIType(Entity));
01018         else if (Entity.isSubprogram())
01019           processSubprogram(DISubprogram(Entity));
01020         else if (Entity.isNameSpace())
01021           processScope(DINameSpace(Entity).getContext());
01022       }
01023     }
01024   }
01025 }
01026 
01027 /// processLocation - Process DILocation.
01028 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
01029   if (!Loc)
01030     return;
01031   InitializeTypeMap(M);
01032   processScope(Loc.getScope());
01033   processLocation(M, Loc.getOrigLocation());
01034 }
01035 
01036 /// processType - Process DIType.
01037 void DebugInfoFinder::processType(DIType DT) {
01038   if (!addType(DT))
01039     return;
01040   processScope(DT.getContext().resolve(TypeIdentifierMap));
01041   if (DT.isCompositeType()) {
01042     DICompositeType DCT(DT);
01043     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01044     if (DT.isSubroutineType()) {
01045       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
01046       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
01047         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
01048       return;
01049     }
01050     DIArray DA = DCT.getElements();
01051     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
01052       DIDescriptor D = DA.getElement(i);
01053       if (D.isType())
01054         processType(DIType(D));
01055       else if (D.isSubprogram())
01056         processSubprogram(DISubprogram(D));
01057     }
01058   } else if (DT.isDerivedType()) {
01059     DIDerivedType DDT(DT);
01060     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01061   }
01062 }
01063 
01064 void DebugInfoFinder::processScope(DIScope Scope) {
01065   if (Scope.isType()) {
01066     DIType Ty(Scope);
01067     processType(Ty);
01068     return;
01069   }
01070   if (Scope.isCompileUnit()) {
01071     addCompileUnit(DICompileUnit(Scope));
01072     return;
01073   }
01074   if (Scope.isSubprogram()) {
01075     processSubprogram(DISubprogram(Scope));
01076     return;
01077   }
01078   if (!addScope(Scope))
01079     return;
01080   if (Scope.isLexicalBlock()) {
01081     DILexicalBlock LB(Scope);
01082     processScope(LB.getContext());
01083   } else if (Scope.isLexicalBlockFile()) {
01084     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
01085     processScope(LBF.getScope());
01086   } else if (Scope.isNameSpace()) {
01087     DINameSpace NS(Scope);
01088     processScope(NS.getContext());
01089   }
01090 }
01091 
01092 /// processSubprogram - Process DISubprogram.
01093 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
01094   if (!addSubprogram(SP))
01095     return;
01096   processScope(SP.getContext().resolve(TypeIdentifierMap));
01097   processType(SP.getType());
01098   DIArray TParams = SP.getTemplateParams();
01099   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
01100     DIDescriptor Element = TParams.getElement(I);
01101     if (Element.isTemplateTypeParameter()) {
01102       DITemplateTypeParameter TType(Element);
01103       processScope(TType.getContext().resolve(TypeIdentifierMap));
01104       processType(TType.getType().resolve(TypeIdentifierMap));
01105     } else if (Element.isTemplateValueParameter()) {
01106       DITemplateValueParameter TVal(Element);
01107       processScope(TVal.getContext().resolve(TypeIdentifierMap));
01108       processType(TVal.getType().resolve(TypeIdentifierMap));
01109     }
01110   }
01111 }
01112 
01113 /// processDeclare - Process DbgDeclareInst.
01114 void DebugInfoFinder::processDeclare(const Module &M,
01115                                      const DbgDeclareInst *DDI) {
01116   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
01117   if (!N)
01118     return;
01119   InitializeTypeMap(M);
01120 
01121   DIDescriptor DV(N);
01122   if (!DV.isVariable())
01123     return;
01124 
01125   if (!NodesSeen.insert(DV))
01126     return;
01127   processScope(DIVariable(N).getContext());
01128   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01129 }
01130 
01131 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
01132   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
01133   if (!N)
01134     return;
01135   InitializeTypeMap(M);
01136 
01137   DIDescriptor DV(N);
01138   if (!DV.isVariable())
01139     return;
01140 
01141   if (!NodesSeen.insert(DV))
01142     return;
01143   processScope(DIVariable(N).getContext());
01144   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01145 }
01146 
01147 /// addType - Add type into Tys.
01148 bool DebugInfoFinder::addType(DIType DT) {
01149   if (!DT)
01150     return false;
01151 
01152   if (!NodesSeen.insert(DT))
01153     return false;
01154 
01155   TYs.push_back(DT);
01156   return true;
01157 }
01158 
01159 /// addCompileUnit - Add compile unit into CUs.
01160 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
01161   if (!CU)
01162     return false;
01163   if (!NodesSeen.insert(CU))
01164     return false;
01165 
01166   CUs.push_back(CU);
01167   return true;
01168 }
01169 
01170 /// addGlobalVariable - Add global variable into GVs.
01171 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
01172   if (!DIG)
01173     return false;
01174 
01175   if (!NodesSeen.insert(DIG))
01176     return false;
01177 
01178   GVs.push_back(DIG);
01179   return true;
01180 }
01181 
01182 // addSubprogram - Add subprgoram into SPs.
01183 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
01184   if (!SP)
01185     return false;
01186 
01187   if (!NodesSeen.insert(SP))
01188     return false;
01189 
01190   SPs.push_back(SP);
01191   return true;
01192 }
01193 
01194 bool DebugInfoFinder::addScope(DIScope Scope) {
01195   if (!Scope)
01196     return false;
01197   // FIXME: Ocaml binding generates a scope with no content, we treat it
01198   // as null for now.
01199   if (Scope->getNumOperands() == 0)
01200     return false;
01201   if (!NodesSeen.insert(Scope))
01202     return false;
01203   Scopes.push_back(Scope);
01204   return true;
01205 }
01206 
01207 //===----------------------------------------------------------------------===//
01208 // DIDescriptor: dump routines for all descriptors.
01209 //===----------------------------------------------------------------------===//
01210 
01211 /// dump - Print descriptor to dbgs() with a newline.
01212 void DIDescriptor::dump() const {
01213   print(dbgs());
01214   dbgs() << '\n';
01215 }
01216 
01217 /// print - Print descriptor.
01218 void DIDescriptor::print(raw_ostream &OS) const {
01219   if (!DbgNode)
01220     return;
01221 
01222   if (const char *Tag = dwarf::TagString(getTag()))
01223     OS << "[ " << Tag << " ]";
01224 
01225   if (this->isSubrange()) {
01226     DISubrange(DbgNode).printInternal(OS);
01227   } else if (this->isCompileUnit()) {
01228     DICompileUnit(DbgNode).printInternal(OS);
01229   } else if (this->isFile()) {
01230     DIFile(DbgNode).printInternal(OS);
01231   } else if (this->isEnumerator()) {
01232     DIEnumerator(DbgNode).printInternal(OS);
01233   } else if (this->isBasicType()) {
01234     DIType(DbgNode).printInternal(OS);
01235   } else if (this->isDerivedType()) {
01236     DIDerivedType(DbgNode).printInternal(OS);
01237   } else if (this->isCompositeType()) {
01238     DICompositeType(DbgNode).printInternal(OS);
01239   } else if (this->isSubprogram()) {
01240     DISubprogram(DbgNode).printInternal(OS);
01241   } else if (this->isGlobalVariable()) {
01242     DIGlobalVariable(DbgNode).printInternal(OS);
01243   } else if (this->isVariable()) {
01244     DIVariable(DbgNode).printInternal(OS);
01245   } else if (this->isObjCProperty()) {
01246     DIObjCProperty(DbgNode).printInternal(OS);
01247   } else if (this->isNameSpace()) {
01248     DINameSpace(DbgNode).printInternal(OS);
01249   } else if (this->isScope()) {
01250     DIScope(DbgNode).printInternal(OS);
01251   }
01252 }
01253 
01254 void DISubrange::printInternal(raw_ostream &OS) const {
01255   int64_t Count = getCount();
01256   if (Count != -1)
01257     OS << " [" << getLo() << ", " << Count - 1 << ']';
01258   else
01259     OS << " [unbounded]";
01260 }
01261 
01262 void DIScope::printInternal(raw_ostream &OS) const {
01263   OS << " [" << getDirectory() << "/" << getFilename() << ']';
01264 }
01265 
01266 void DICompileUnit::printInternal(raw_ostream &OS) const {
01267   DIScope::printInternal(OS);
01268   OS << " [";
01269   unsigned Lang = getLanguage();
01270   if (const char *LangStr = dwarf::LanguageString(Lang))
01271     OS << LangStr;
01272   else
01273     (OS << "lang 0x").write_hex(Lang);
01274   OS << ']';
01275 }
01276 
01277 void DIEnumerator::printInternal(raw_ostream &OS) const {
01278   OS << " [" << getName() << " :: " << getEnumValue() << ']';
01279 }
01280 
01281 void DIType::printInternal(raw_ostream &OS) const {
01282   if (!DbgNode)
01283     return;
01284 
01285   StringRef Res = getName();
01286   if (!Res.empty())
01287     OS << " [" << Res << "]";
01288 
01289   // TODO: Print context?
01290 
01291   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
01292      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
01293   if (isBasicType())
01294     if (const char *Enc =
01295             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
01296       OS << ", enc " << Enc;
01297   OS << "]";
01298 
01299   if (isPrivate())
01300     OS << " [private]";
01301   else if (isProtected())
01302     OS << " [protected]";
01303 
01304   if (isArtificial())
01305     OS << " [artificial]";
01306 
01307   if (isForwardDecl())
01308     OS << " [decl]";
01309   else if (getTag() == dwarf::DW_TAG_structure_type ||
01310            getTag() == dwarf::DW_TAG_union_type ||
01311            getTag() == dwarf::DW_TAG_enumeration_type ||
01312            getTag() == dwarf::DW_TAG_class_type)
01313     OS << " [def]";
01314   if (isVector())
01315     OS << " [vector]";
01316   if (isStaticMember())
01317     OS << " [static]";
01318 
01319   if (isLValueReference())
01320     OS << " [reference]";
01321 
01322   if (isRValueReference())
01323     OS << " [rvalue reference]";
01324 }
01325 
01326 void DIDerivedType::printInternal(raw_ostream &OS) const {
01327   DIType::printInternal(OS);
01328   OS << " [from " << getTypeDerivedFrom().getName() << ']';
01329 }
01330 
01331 void DICompositeType::printInternal(raw_ostream &OS) const {
01332   DIType::printInternal(OS);
01333   DIArray A = getElements();
01334   OS << " [" << A.getNumElements() << " elements]";
01335 }
01336 
01337 void DINameSpace::printInternal(raw_ostream &OS) const {
01338   StringRef Name = getName();
01339   if (!Name.empty())
01340     OS << " [" << Name << ']';
01341 
01342   OS << " [line " << getLineNumber() << ']';
01343 }
01344 
01345 void DISubprogram::printInternal(raw_ostream &OS) const {
01346   // TODO : Print context
01347   OS << " [line " << getLineNumber() << ']';
01348 
01349   if (isLocalToUnit())
01350     OS << " [local]";
01351 
01352   if (isDefinition())
01353     OS << " [def]";
01354 
01355   if (getScopeLineNumber() != getLineNumber())
01356     OS << " [scope " << getScopeLineNumber() << "]";
01357 
01358   if (isPrivate())
01359     OS << " [private]";
01360   else if (isProtected())
01361     OS << " [protected]";
01362 
01363   if (isLValueReference())
01364     OS << " [reference]";
01365 
01366   if (isRValueReference())
01367     OS << " [rvalue reference]";
01368 
01369   StringRef Res = getName();
01370   if (!Res.empty())
01371     OS << " [" << Res << ']';
01372 }
01373 
01374 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
01375   StringRef Res = getName();
01376   if (!Res.empty())
01377     OS << " [" << Res << ']';
01378 
01379   OS << " [line " << getLineNumber() << ']';
01380 
01381   // TODO : Print context
01382 
01383   if (isLocalToUnit())
01384     OS << " [local]";
01385 
01386   if (isDefinition())
01387     OS << " [def]";
01388 }
01389 
01390 void DIVariable::printInternal(raw_ostream &OS) const {
01391   StringRef Res = getName();
01392   if (!Res.empty())
01393     OS << " [" << Res << ']';
01394 
01395   OS << " [line " << getLineNumber() << ']';
01396 }
01397 
01398 void DIObjCProperty::printInternal(raw_ostream &OS) const {
01399   StringRef Name = getObjCPropertyName();
01400   if (!Name.empty())
01401     OS << " [" << Name << ']';
01402 
01403   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
01404      << ']';
01405 }
01406 
01407 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
01408                           const LLVMContext &Ctx) {
01409   if (!DL.isUnknown()) { // Print source line info.
01410     DIScope Scope(DL.getScope(Ctx));
01411     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
01412     // Omit the directory, because it's likely to be long and uninteresting.
01413     CommentOS << Scope.getFilename();
01414     CommentOS << ':' << DL.getLine();
01415     if (DL.getCol() != 0)
01416       CommentOS << ':' << DL.getCol();
01417     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
01418     if (!InlinedAtDL.isUnknown()) {
01419       CommentOS << " @[ ";
01420       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
01421       CommentOS << " ]";
01422     }
01423   }
01424 }
01425 
01426 void DIVariable::printExtendedName(raw_ostream &OS) const {
01427   const LLVMContext &Ctx = DbgNode->getContext();
01428   StringRef Res = getName();
01429   if (!Res.empty())
01430     OS << Res << "," << getLineNumber();
01431   if (MDNode *InlinedAt = getInlinedAt()) {
01432     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
01433     if (!InlinedAtDL.isUnknown()) {
01434       OS << " @[";
01435       printDebugLoc(InlinedAtDL, OS, Ctx);
01436       OS << "]";
01437     }
01438   }
01439 }
01440 
01441 /// Specialize constructor to make sure it has the correct type.
01442 template <> DIRef<DIScope>::DIRef(const Value *V) : Val(V) {
01443   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
01444 }
01445 template <> DIRef<DIType>::DIRef(const Value *V) : Val(V) {
01446   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
01447 }
01448 
01449 /// Specialize getFieldAs to handle fields that are references to DIScopes.
01450 template <>
01451 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
01452   return DIScopeRef(getField(DbgNode, Elt));
01453 }
01454 /// Specialize getFieldAs to handle fields that are references to DITypes.
01455 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
01456   return DITypeRef(getField(DbgNode, Elt));
01457 }
01458 
01459 /// Strip debug info in the module if it exists.
01460 /// To do this, we remove all calls to the debugger intrinsics and any named
01461 /// metadata for debugging. We also remove debug locations for instructions.
01462 /// Return true if module is modified.
01463 bool llvm::StripDebugInfo(Module &M) {
01464 
01465   bool Changed = false;
01466 
01467   // Remove all of the calls to the debugger intrinsics, and remove them from
01468   // the module.
01469   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
01470     while (!Declare->use_empty()) {
01471       CallInst *CI = cast<CallInst>(Declare->user_back());
01472       CI->eraseFromParent();
01473     }
01474     Declare->eraseFromParent();
01475     Changed = true;
01476   }
01477 
01478   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
01479     while (!DbgVal->use_empty()) {
01480       CallInst *CI = cast<CallInst>(DbgVal->user_back());
01481       CI->eraseFromParent();
01482     }
01483     DbgVal->eraseFromParent();
01484     Changed = true;
01485   }
01486 
01487   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
01488          NME = M.named_metadata_end(); NMI != NME;) {
01489     NamedMDNode *NMD = NMI;
01490     ++NMI;
01491     if (NMD->getName().startswith("llvm.dbg.")) {
01492       NMD->eraseFromParent();
01493       Changed = true;
01494     }
01495   }
01496 
01497   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
01498     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
01499          ++FI)
01500       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
01501            ++BI) {
01502         if (!BI->getDebugLoc().isUnknown()) {
01503           Changed = true;
01504           BI->setDebugLoc(DebugLoc());
01505         }
01506       }
01507 
01508   return Changed;
01509 }
01510 
01511 /// Return Debug Info Metadata Version by checking module flags.
01512 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
01513   Value *Val = M.getModuleFlag("Debug Info Version");
01514   if (!Val)
01515     return 0;
01516   return cast<ConstantInt>(Val)->getZExtValue();
01517 }
01518 
01519 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
01520 llvm::makeSubprogramMap(const Module &M) {
01521   DenseMap<const Function *, DISubprogram> R;
01522 
01523   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
01524   if (!CU_Nodes)
01525     return R;
01526 
01527   for (MDNode *N : CU_Nodes->operands()) {
01528     DICompileUnit CUNode(N);
01529     DIArray SPs = CUNode.getSubprograms();
01530     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
01531       DISubprogram SP(SPs.getElement(i));
01532       if (Function *F = SP.getFunction())
01533         R.insert(std::make_pair(F, SP));
01534     }
01535   }
01536   return R;
01537 }