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